#include "Test.h"
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

DEFINE_TEST(atoi)
{
    START_TEST(atoi);

    const char* str = "42";
    int num = atoi(str);

    EXPECT_EQ(num, 42);

    str = "-56";
    num = atoi(str);

    EXPECT_EQ(num, -56);

    str = "Not a number";
    num = atoi(str);

    EXPECT_EQ(num, 0);

    TEST_SUCCESS();
}

DEFINE_TEST(atol)
{
    START_TEST(atol);

    const char* str = "42";
    long num = atol(str);

    EXPECT_EQ(num, 42);

    str = "-56";
    num = atol(str);

    EXPECT_EQ(num, -56);

    str = "Not a number";
    num = atol(str);

    EXPECT_EQ(num, 0);

    str = "68719476735";
    num = atol(str);

    EXPECT_EQ(num, 68719476735);

    TEST_SUCCESS();
}

DEFINE_TEST(atoll)
{
    START_TEST(atoll);

    const char* str = "42";
    long long num = atoll(str);

    EXPECT_EQ(num, 42);

    str = "-56";
    num = atoll(str);

    EXPECT_EQ(num, -56);

    str = "Not a number";
    num = atoll(str);

    EXPECT_EQ(num, 0);

    str = "68719476735";
    num = atoll(str);

    EXPECT_EQ(num, 68719476735);

    TEST_SUCCESS();
}

DEFINE_TEST(srand)
{
    START_TEST(srand);

    srand(5849);

    int val = rand();

    EXPECT_EQ(val, -1731894882);

    TEST_SUCCESS();
}

DEFINE_TEST(malloc)
{
    START_TEST(malloc);

    int* ptr = malloc(6 * sizeof(int));

    if (!ptr)
    {
        TEST_NOT_SURE(ptr);
        return true;
    }

    *ptr = 6;

    EXPECT_EQ(*ptr, 6);

    ptr[5] = 4;

    EXPECT_EQ(ptr[5], 4);

    free(ptr);

    TEST_SUCCESS();
}

DEFINE_TEST(calloc)
{
    START_TEST(calloc);

    int* ptr = calloc(6, sizeof(int));

    if (!ptr) { TEST_NOT_SURE(ptr); }

    EXPECT_EQ(*ptr, 0);
    EXPECT_EQ(ptr[5], 0);

    *ptr = 6;

    EXPECT_EQ(*ptr, 6);

    ptr[5] = 4;

    EXPECT_EQ(ptr[5], 4);

    free(ptr);

    TEST_SUCCESS();
}

DEFINE_TEST(mktemp)
{
    START_TEST(mktemp);

    char template[] = "/tmp/file.XXXXXX";

    const char* template2 = "/tmp/file.XXXXXX";

    char* ptr = mktemp(template);

    EXPECT_NOT_EQ(ptr, NULL); // mktemp only fails if we give it an invalid template.

    int rc = access(ptr, F_OK);

    EXPECT_NOT_EQ(rc, 0); // FIXME: This could actually happen, since that's why mktemp is deprecated. 
                          // Another process could create the file between generating the name and actually using it.

    rc = strcmp(ptr, template2);

    EXPECT_NOT_EQ(rc, 0);

    TEST_SUCCESS();
}