// Copyright (c) 2016, Salvatore Sanfilippo <antirez at gmail dot com>
// SPDX-FileCopyrightText: 2024 Redict Contributors
// SPDX-FileCopyrightText: 2024 Salvatore Sanfilippo <antirez at gmail dot com>
//
// SPDX-License-Identifier: BSD-3-Clause
// SPDX-License-Identifier: LGPL-3.0-only

#include "redictmodule.h"
#include <string.h>
#include <stdlib.h>

/* --------------------------------- Helpers -------------------------------- */

/* Return true if the reply and the C null term string matches. */
int TestMatchReply(RedictModuleCallReply *reply, char *str) {
    RedictModuleString *mystr;
    mystr = RedictModule_CreateStringFromCallReply(reply);
    if (!mystr) return 0;
    const char *ptr = RedictModule_StringPtrLen(mystr,NULL);
    return strcmp(ptr,str) == 0;
}

/* ------------------------------- Test units ------------------------------- */

/* TEST.CALL -- Test Call() API. */
int TestCall(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    REDICTMODULE_NOT_USED(argv);
    REDICTMODULE_NOT_USED(argc);

    RedictModule_AutoMemory(ctx);
    RedictModuleCallReply *reply;

    RedictModule_Call(ctx,"DEL","c","mylist");
    RedictModuleString *mystr = RedictModule_CreateString(ctx,"foo",3);
    RedictModule_Call(ctx,"RPUSH","csl","mylist",mystr,(long long)1234);
    reply = RedictModule_Call(ctx,"LRANGE","ccc","mylist","0","-1");
    long long items = RedictModule_CallReplyLength(reply);
    if (items != 2) goto fail;

    RedictModuleCallReply *item0, *item1;

    item0 = RedictModule_CallReplyArrayElement(reply,0);
    item1 = RedictModule_CallReplyArrayElement(reply,1);
    if (!TestMatchReply(item0,"foo")) goto fail;
    if (!TestMatchReply(item1,"1234")) goto fail;

    RedictModule_ReplyWithSimpleString(ctx,"OK");
    return REDICTMODULE_OK;

fail:
    RedictModule_ReplyWithSimpleString(ctx,"ERR");
    return REDICTMODULE_OK;
}

int TestCallResp3Attribute(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    REDICTMODULE_NOT_USED(argv);
    REDICTMODULE_NOT_USED(argc);

    RedictModule_AutoMemory(ctx);
    RedictModuleCallReply *reply;

    reply = RedictModule_Call(ctx,"DEBUG","3cc" ,"PROTOCOL", "attrib"); /* 3 stands for resp 3 reply */
    if (RedictModule_CallReplyType(reply) != REDICTMODULE_REPLY_STRING) goto fail;

    /* make sure we can not reply to resp2 client with resp3 (it might be a string but it contains attribute) */
    if (RedictModule_ReplyWithCallReply(ctx, reply) != REDICTMODULE_ERR) goto fail;

    if (!TestMatchReply(reply,"Some real reply following the attribute")) goto fail;

    reply = RedictModule_CallReplyAttribute(reply);
    if (!reply || RedictModule_CallReplyType(reply) != REDICTMODULE_REPLY_ATTRIBUTE) goto fail;
    /* make sure we can not reply to resp2 client with resp3 attribute */
    if (RedictModule_ReplyWithCallReply(ctx, reply) != REDICTMODULE_ERR) goto fail;
    if (RedictModule_CallReplyLength(reply) != 1) goto fail;

    RedictModuleCallReply *key, *val;
    if (RedictModule_CallReplyAttributeElement(reply,0,&key,&val) != REDICTMODULE_OK) goto fail;
    if (!TestMatchReply(key,"key-popularity")) goto fail;
    if (RedictModule_CallReplyType(val) != REDICTMODULE_REPLY_ARRAY) goto fail;
    if (RedictModule_CallReplyLength(val) != 2) goto fail;
    if (!TestMatchReply(RedictModule_CallReplyArrayElement(val, 0),"key:123")) goto fail;
    if (!TestMatchReply(RedictModule_CallReplyArrayElement(val, 1),"90")) goto fail;

    RedictModule_ReplyWithSimpleString(ctx,"OK");
    return REDICTMODULE_OK;

fail:
    RedictModule_ReplyWithSimpleString(ctx,"ERR");
    return REDICTMODULE_OK;
}

int TestGetResp(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    REDICTMODULE_NOT_USED(argv);
    REDICTMODULE_NOT_USED(argc);

    int flags = RedictModule_GetContextFlags(ctx);

    if (flags & REDICTMODULE_CTX_FLAGS_RESP3) {
        RedictModule_ReplyWithLongLong(ctx, 3);
    } else {
        RedictModule_ReplyWithLongLong(ctx, 2);
    }

    return REDICTMODULE_OK;
}

int TestCallRespAutoMode(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    REDICTMODULE_NOT_USED(argv);
    REDICTMODULE_NOT_USED(argc);

    RedictModule_AutoMemory(ctx);
    RedictModuleCallReply *reply;

    RedictModule_Call(ctx,"DEL","c","myhash");
    RedictModule_Call(ctx,"HSET","ccccc","myhash", "f1", "v1", "f2", "v2");
    /* 0 stands for auto mode, we will get the reply in the same format as the client */
    reply = RedictModule_Call(ctx,"HGETALL","0c" ,"myhash");
    RedictModule_ReplyWithCallReply(ctx, reply);
    return REDICTMODULE_OK;
}

int TestCallResp3Map(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    REDICTMODULE_NOT_USED(argv);
    REDICTMODULE_NOT_USED(argc);

    RedictModule_AutoMemory(ctx);
    RedictModuleCallReply *reply;

    RedictModule_Call(ctx,"DEL","c","myhash");
    RedictModule_Call(ctx,"HSET","ccccc","myhash", "f1", "v1", "f2", "v2");
    reply = RedictModule_Call(ctx,"HGETALL","3c" ,"myhash"); /* 3 stands for resp 3 reply */
    if (RedictModule_CallReplyType(reply) != REDICTMODULE_REPLY_MAP) goto fail;

    /* make sure we can not reply to resp2 client with resp3 map */
    if (RedictModule_ReplyWithCallReply(ctx, reply) != REDICTMODULE_ERR) goto fail;

    long long items = RedictModule_CallReplyLength(reply);
    if (items != 2) goto fail;

    RedictModuleCallReply *key0, *key1;
    RedictModuleCallReply *val0, *val1;
    if (RedictModule_CallReplyMapElement(reply,0,&key0,&val0) != REDICTMODULE_OK) goto fail;
    if (RedictModule_CallReplyMapElement(reply,1,&key1,&val1) != REDICTMODULE_OK) goto fail;
    if (!TestMatchReply(key0,"f1")) goto fail;
    if (!TestMatchReply(key1,"f2")) goto fail;
    if (!TestMatchReply(val0,"v1")) goto fail;
    if (!TestMatchReply(val1,"v2")) goto fail;

    RedictModule_ReplyWithSimpleString(ctx,"OK");
    return REDICTMODULE_OK;

fail:
    RedictModule_ReplyWithSimpleString(ctx,"ERR");
    return REDICTMODULE_OK;
}

int TestCallResp3Bool(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    REDICTMODULE_NOT_USED(argv);
    REDICTMODULE_NOT_USED(argc);

    RedictModule_AutoMemory(ctx);
    RedictModuleCallReply *reply;

    reply = RedictModule_Call(ctx,"DEBUG","3cc" ,"PROTOCOL", "true"); /* 3 stands for resp 3 reply */
    if (RedictModule_CallReplyType(reply) != REDICTMODULE_REPLY_BOOL) goto fail;
    /* make sure we can not reply to resp2 client with resp3 bool */
    if (RedictModule_ReplyWithCallReply(ctx, reply) != REDICTMODULE_ERR) goto fail;

    if (!RedictModule_CallReplyBool(reply)) goto fail;
    reply = RedictModule_Call(ctx,"DEBUG","3cc" ,"PROTOCOL", "false"); /* 3 stands for resp 3 reply */
    if (RedictModule_CallReplyType(reply) != REDICTMODULE_REPLY_BOOL) goto fail;
    if (RedictModule_CallReplyBool(reply)) goto fail;

    RedictModule_ReplyWithSimpleString(ctx,"OK");
    return REDICTMODULE_OK;

fail:
    RedictModule_ReplyWithSimpleString(ctx,"ERR");
    return REDICTMODULE_OK;
}

int TestCallResp3Null(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    REDICTMODULE_NOT_USED(argv);
    REDICTMODULE_NOT_USED(argc);

    RedictModule_AutoMemory(ctx);
    RedictModuleCallReply *reply;

    reply = RedictModule_Call(ctx,"DEBUG","3cc" ,"PROTOCOL", "null"); /* 3 stands for resp 3 reply */
    if (RedictModule_CallReplyType(reply) != REDICTMODULE_REPLY_NULL) goto fail;

    /* make sure we can not reply to resp2 client with resp3 null */
    if (RedictModule_ReplyWithCallReply(ctx, reply) != REDICTMODULE_ERR) goto fail;

    RedictModule_ReplyWithSimpleString(ctx,"OK");
    return REDICTMODULE_OK;

fail:
    RedictModule_ReplyWithSimpleString(ctx,"ERR");
    return REDICTMODULE_OK;
}

int TestCallReplyWithNestedReply(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    REDICTMODULE_NOT_USED(argv);
    REDICTMODULE_NOT_USED(argc);

    RedictModule_AutoMemory(ctx);
    RedictModuleCallReply *reply;

    RedictModule_Call(ctx,"DEL","c","mylist");
    RedictModule_Call(ctx,"RPUSH","ccl","mylist","test",(long long)1234);
    reply = RedictModule_Call(ctx,"LRANGE","ccc","mylist","0","-1");
    if (RedictModule_CallReplyType(reply) != REDICTMODULE_REPLY_ARRAY) goto fail;
    if (RedictModule_CallReplyLength(reply) < 1) goto fail;
    RedictModuleCallReply *nestedReply = RedictModule_CallReplyArrayElement(reply, 0);

    RedictModule_ReplyWithCallReply(ctx,nestedReply);
    return REDICTMODULE_OK;

fail:
    RedictModule_ReplyWithSimpleString(ctx,"ERR");
    return REDICTMODULE_OK;
}

int TestCallReplyWithArrayReply(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    REDICTMODULE_NOT_USED(argv);
    REDICTMODULE_NOT_USED(argc);

    RedictModule_AutoMemory(ctx);
    RedictModuleCallReply *reply;

    RedictModule_Call(ctx,"DEL","c","mylist");
    RedictModule_Call(ctx,"RPUSH","ccl","mylist","test",(long long)1234);
    reply = RedictModule_Call(ctx,"LRANGE","ccc","mylist","0","-1");
    if (RedictModule_CallReplyType(reply) != REDICTMODULE_REPLY_ARRAY) goto fail;

    RedictModule_ReplyWithCallReply(ctx,reply);
    return REDICTMODULE_OK;

fail:
    RedictModule_ReplyWithSimpleString(ctx,"ERR");
    return REDICTMODULE_OK;
}

int TestCallResp3Double(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    REDICTMODULE_NOT_USED(argv);
    REDICTMODULE_NOT_USED(argc);

    RedictModule_AutoMemory(ctx);
    RedictModuleCallReply *reply;

    reply = RedictModule_Call(ctx,"DEBUG","3cc" ,"PROTOCOL", "double"); /* 3 stands for resp 3 reply */
    if (RedictModule_CallReplyType(reply) != REDICTMODULE_REPLY_DOUBLE) goto fail;

    /* make sure we can not reply to resp2 client with resp3 double*/
    if (RedictModule_ReplyWithCallReply(ctx, reply) != REDICTMODULE_ERR) goto fail;

    double d = RedictModule_CallReplyDouble(reply);
    /* we compare strings, since comparing doubles directly can fail in various architectures, e.g. 32bit */
    char got[30], expected[30];
    snprintf(got, sizeof(got), "%.17g", d);
    snprintf(expected, sizeof(expected), "%.17g", 3.141);
    if (strcmp(got, expected) != 0) goto fail;
    RedictModule_ReplyWithSimpleString(ctx,"OK");
    return REDICTMODULE_OK;

fail:
    RedictModule_ReplyWithSimpleString(ctx,"ERR");
    return REDICTMODULE_OK;
}

int TestCallResp3BigNumber(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    REDICTMODULE_NOT_USED(argv);
    REDICTMODULE_NOT_USED(argc);

    RedictModule_AutoMemory(ctx);
    RedictModuleCallReply *reply;

    reply = RedictModule_Call(ctx,"DEBUG","3cc" ,"PROTOCOL", "bignum"); /* 3 stands for resp 3 reply */
    if (RedictModule_CallReplyType(reply) != REDICTMODULE_REPLY_BIG_NUMBER) goto fail;

    /* make sure we can not reply to resp2 client with resp3 big number */
    if (RedictModule_ReplyWithCallReply(ctx, reply) != REDICTMODULE_ERR) goto fail;

    size_t len;
    const char* big_num = RedictModule_CallReplyBigNumber(reply, &len);
    RedictModule_ReplyWithStringBuffer(ctx,big_num,len);
    return REDICTMODULE_OK;

fail:
    RedictModule_ReplyWithSimpleString(ctx,"ERR");
    return REDICTMODULE_OK;
}

int TestCallResp3Verbatim(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    REDICTMODULE_NOT_USED(argv);
    REDICTMODULE_NOT_USED(argc);

    RedictModule_AutoMemory(ctx);
    RedictModuleCallReply *reply;

    reply = RedictModule_Call(ctx,"DEBUG","3cc" ,"PROTOCOL", "verbatim"); /* 3 stands for resp 3 reply */
    if (RedictModule_CallReplyType(reply) != REDICTMODULE_REPLY_VERBATIM_STRING) goto fail;

    /* make sure we can not reply to resp2 client with resp3 verbatim string */
    if (RedictModule_ReplyWithCallReply(ctx, reply) != REDICTMODULE_ERR) goto fail;

    const char* format;
    size_t len;
    const char* str = RedictModule_CallReplyVerbatim(reply, &len, &format);
    RedictModuleString *s = RedictModule_CreateStringPrintf(ctx, "%.*s:%.*s", 3, format, (int)len, str);
    RedictModule_ReplyWithString(ctx,s);
    return REDICTMODULE_OK;

fail:
    RedictModule_ReplyWithSimpleString(ctx,"ERR");
    return REDICTMODULE_OK;
}

int TestCallResp3Set(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    REDICTMODULE_NOT_USED(argv);
    REDICTMODULE_NOT_USED(argc);

    RedictModule_AutoMemory(ctx);
    RedictModuleCallReply *reply;

    RedictModule_Call(ctx,"DEL","c","myset");
    RedictModule_Call(ctx,"sadd","ccc","myset", "v1", "v2");
    reply = RedictModule_Call(ctx,"smembers","3c" ,"myset"); // N stands for resp 3 reply
    if (RedictModule_CallReplyType(reply) != REDICTMODULE_REPLY_SET) goto fail;

    /* make sure we can not reply to resp2 client with resp3 set */
    if (RedictModule_ReplyWithCallReply(ctx, reply) != REDICTMODULE_ERR) goto fail;

    long long items = RedictModule_CallReplyLength(reply);
    if (items != 2) goto fail;

    RedictModuleCallReply *val0, *val1;

    val0 = RedictModule_CallReplySetElement(reply,0);
    val1 = RedictModule_CallReplySetElement(reply,1);

    /*
     * The order of elements on sets are not promised so we just
     * veridy that the reply matches one of the elements.
     */
    if (!TestMatchReply(val0,"v1") && !TestMatchReply(val0,"v2")) goto fail;
    if (!TestMatchReply(val1,"v1") && !TestMatchReply(val1,"v2")) goto fail;

    RedictModule_ReplyWithSimpleString(ctx,"OK");
    return REDICTMODULE_OK;

fail:
    RedictModule_ReplyWithSimpleString(ctx,"ERR");
    return REDICTMODULE_OK;
}

/* TEST.STRING.APPEND -- Test appending to an existing string object. */
int TestStringAppend(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    REDICTMODULE_NOT_USED(argv);
    REDICTMODULE_NOT_USED(argc);

    RedictModuleString *s = RedictModule_CreateString(ctx,"foo",3);
    RedictModule_StringAppendBuffer(ctx,s,"bar",3);
    RedictModule_ReplyWithString(ctx,s);
    RedictModule_FreeString(ctx,s);
    return REDICTMODULE_OK;
}

/* TEST.STRING.APPEND.AM -- Test append with retain when auto memory is on. */
int TestStringAppendAM(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    REDICTMODULE_NOT_USED(argv);
    REDICTMODULE_NOT_USED(argc);

    RedictModule_AutoMemory(ctx);
    RedictModuleString *s = RedictModule_CreateString(ctx,"foo",3);
    RedictModule_RetainString(ctx,s);
    RedictModule_TrimStringAllocation(s);    /* Mostly NOP, but exercises the API function */
    RedictModule_StringAppendBuffer(ctx,s,"bar",3);
    RedictModule_ReplyWithString(ctx,s);
    RedictModule_FreeString(ctx,s);
    return REDICTMODULE_OK;
}

/* TEST.STRING.TRIM -- Test we trim a string with free space. */
int TestTrimString(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    REDICTMODULE_NOT_USED(argv);
    REDICTMODULE_NOT_USED(argc);
    RedictModuleString *s = RedictModule_CreateString(ctx,"foo",3);
    char *tmp = RedictModule_Alloc(1024);
    RedictModule_StringAppendBuffer(ctx,s,tmp,1024);
    size_t string_len = RedictModule_MallocSizeString(s);
    RedictModule_TrimStringAllocation(s);
    size_t len_after_trim = RedictModule_MallocSizeString(s);

    /* Determine if using jemalloc memory allocator. */
    RedictModuleServerInfoData *info = RedictModule_GetServerInfo(ctx, "memory");
    const char *field = RedictModule_ServerInfoGetFieldC(info, "mem_allocator");
    int use_jemalloc = !strncmp(field, "jemalloc", 8);

    /* Jemalloc will reallocate `s` from 2k to 1k after RedictModule_TrimStringAllocation(),
     * but non-jemalloc memory allocators may keep the old size. */
    if ((use_jemalloc && len_after_trim < string_len) ||
        (!use_jemalloc && len_after_trim <= string_len))
    {
        RedictModule_ReplyWithSimpleString(ctx, "OK");
    } else {
        RedictModule_ReplyWithError(ctx, "String was not trimmed as expected.");
    }
    RedictModule_FreeServerInfo(ctx, info);
    RedictModule_Free(tmp);
    RedictModule_FreeString(ctx,s);
    return REDICTMODULE_OK;
}

/* TEST.STRING.PRINTF -- Test string formatting. */
int TestStringPrintf(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    RedictModule_AutoMemory(ctx);
    if (argc < 3) {
        return RedictModule_WrongArity(ctx);
    }
    RedictModuleString *s = RedictModule_CreateStringPrintf(ctx,
        "Got %d args. argv[1]: %s, argv[2]: %s",
        argc,
        RedictModule_StringPtrLen(argv[1], NULL),
        RedictModule_StringPtrLen(argv[2], NULL)
    );

    RedictModule_ReplyWithString(ctx,s);

    return REDICTMODULE_OK;
}

int failTest(RedictModuleCtx *ctx, const char *msg) {
    RedictModule_ReplyWithError(ctx, msg);
    return REDICTMODULE_ERR;
}

int TestUnlink(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    RedictModule_AutoMemory(ctx);
    REDICTMODULE_NOT_USED(argv);
    REDICTMODULE_NOT_USED(argc);

    RedictModuleKey *k = RedictModule_OpenKey(ctx, RedictModule_CreateStringPrintf(ctx, "unlinked"), REDICTMODULE_WRITE | REDICTMODULE_READ);
    if (!k) return failTest(ctx, "Could not create key");

    if (REDICTMODULE_ERR == RedictModule_StringSet(k, RedictModule_CreateStringPrintf(ctx, "Foobar"))) {
        return failTest(ctx, "Could not set string value");
    }

    RedictModuleCallReply *rep = RedictModule_Call(ctx, "EXISTS", "c", "unlinked");
    if (!rep || RedictModule_CallReplyInteger(rep) != 1) {
        return failTest(ctx, "Key does not exist before unlink");
    }

    if (REDICTMODULE_ERR == RedictModule_UnlinkKey(k)) {
        return failTest(ctx, "Could not unlink key");
    }

    rep = RedictModule_Call(ctx, "EXISTS", "c", "unlinked");
    if (!rep || RedictModule_CallReplyInteger(rep) != 0) {
        return failTest(ctx, "Could not verify key to be unlinked");
    }
    return RedictModule_ReplyWithSimpleString(ctx, "OK");
}

int TestNestedCallReplyArrayElement(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    RedictModule_AutoMemory(ctx);
    REDICTMODULE_NOT_USED(argv);
    REDICTMODULE_NOT_USED(argc);

    RedictModuleString *expect_key = RedictModule_CreateString(ctx, "mykey", strlen("mykey"));
    RedictModule_SelectDb(ctx, 1);
    RedictModule_Call(ctx, "LPUSH", "sc", expect_key, "myvalue");

    RedictModuleCallReply *scan_reply = RedictModule_Call(ctx, "SCAN", "l", (long long)0);
    RedictModule_Assert(scan_reply != NULL && RedictModule_CallReplyType(scan_reply) == REDICTMODULE_REPLY_ARRAY);
    RedictModule_Assert(RedictModule_CallReplyLength(scan_reply) == 2);

    long long scan_cursor;
    RedictModuleCallReply *cursor_reply = RedictModule_CallReplyArrayElement(scan_reply, 0);
    RedictModule_Assert(RedictModule_CallReplyType(cursor_reply) == REDICTMODULE_REPLY_STRING);
    RedictModule_Assert(RedictModule_StringToLongLong(RedictModule_CreateStringFromCallReply(cursor_reply), &scan_cursor) == REDICTMODULE_OK);
    RedictModule_Assert(scan_cursor == 0);

    RedictModuleCallReply *keys_reply = RedictModule_CallReplyArrayElement(scan_reply, 1);
    RedictModule_Assert(RedictModule_CallReplyType(keys_reply) == REDICTMODULE_REPLY_ARRAY);
    RedictModule_Assert( RedictModule_CallReplyLength(keys_reply) == 1);
 
    RedictModuleCallReply *key_reply = RedictModule_CallReplyArrayElement(keys_reply, 0);
    RedictModule_Assert(RedictModule_CallReplyType(key_reply) == REDICTMODULE_REPLY_STRING);
    RedictModuleString *key = RedictModule_CreateStringFromCallReply(key_reply);
    RedictModule_Assert(RedictModule_StringCompare(key, expect_key) == 0);

    RedictModule_ReplyWithSimpleString(ctx, "OK");
    return REDICTMODULE_OK;
}

/* TEST.STRING.TRUNCATE -- Test truncating an existing string object. */
int TestStringTruncate(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    RedictModule_AutoMemory(ctx);
    REDICTMODULE_NOT_USED(argv);
    REDICTMODULE_NOT_USED(argc);

    RedictModule_Call(ctx, "SET", "cc", "foo", "abcde");
    RedictModuleKey *k = RedictModule_OpenKey(ctx, RedictModule_CreateStringPrintf(ctx, "foo"), REDICTMODULE_READ | REDICTMODULE_WRITE);
    if (!k) return failTest(ctx, "Could not create key");

    size_t len = 0;
    char* s;

    /* expand from 5 to 8 and check null pad */
    if (REDICTMODULE_ERR == RedictModule_StringTruncate(k, 8)) {
        return failTest(ctx, "Could not truncate string value (8)");
    }
    s = RedictModule_StringDMA(k, &len, REDICTMODULE_READ);
    if (!s) {
        return failTest(ctx, "Failed to read truncated string (8)");
    } else if (len != 8) {
        return failTest(ctx, "Failed to expand string value (8)");
    } else if (0 != strncmp(s, "abcde\0\0\0", 8)) {
        return failTest(ctx, "Failed to null pad string value (8)");
    }

    /* shrink from 8 to 4 */
    if (REDICTMODULE_ERR == RedictModule_StringTruncate(k, 4)) {
        return failTest(ctx, "Could not truncate string value (4)");
    }
    s = RedictModule_StringDMA(k, &len, REDICTMODULE_READ);
    if (!s) {
        return failTest(ctx, "Failed to read truncated string (4)");
    } else if (len != 4) {
        return failTest(ctx, "Failed to shrink string value (4)");
    } else if (0 != strncmp(s, "abcd", 4)) {
        return failTest(ctx, "Failed to truncate string value (4)");
    }

    /* shrink to 0 */
    if (REDICTMODULE_ERR == RedictModule_StringTruncate(k, 0)) {
        return failTest(ctx, "Could not truncate string value (0)");
    }
    s = RedictModule_StringDMA(k, &len, REDICTMODULE_READ);
    if (!s) {
        return failTest(ctx, "Failed to read truncated string (0)");
    } else if (len != 0) {
        return failTest(ctx, "Failed to shrink string value to (0)");
    }

    return RedictModule_ReplyWithSimpleString(ctx, "OK");
}

int NotifyCallback(RedictModuleCtx *ctx, int type, const char *event,
                   RedictModuleString *key) {
  RedictModule_AutoMemory(ctx);
  /* Increment a counter on the notifications: for each key notified we
   * increment a counter */
  RedictModule_Log(ctx, "notice", "Got event type %d, event %s, key %s", type,
                  event, RedictModule_StringPtrLen(key, NULL));

  RedictModule_Call(ctx, "HINCRBY", "csc", "notifications", key, "1");
  return REDICTMODULE_OK;
}

/* TEST.NOTIFICATIONS -- Test Keyspace Notifications. */
int TestNotifications(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    RedictModule_AutoMemory(ctx);
    REDICTMODULE_NOT_USED(argv);
    REDICTMODULE_NOT_USED(argc);

#define FAIL(msg, ...)                                                                       \
    {                                                                                        \
        RedictModule_Log(ctx, "warning", "Failed NOTIFY Test. Reason: " #msg, ##__VA_ARGS__); \
        goto err;                                                                            \
    }
    RedictModule_Call(ctx, "FLUSHDB", "");

    RedictModule_Call(ctx, "SET", "cc", "foo", "bar");
    RedictModule_Call(ctx, "SET", "cc", "foo", "baz");
    RedictModule_Call(ctx, "SADD", "cc", "bar", "x");
    RedictModule_Call(ctx, "SADD", "cc", "bar", "y");

    RedictModule_Call(ctx, "HSET", "ccc", "baz", "x", "y");
    /* LPUSH should be ignored and not increment any counters */
    RedictModule_Call(ctx, "LPUSH", "cc", "l", "y");
    RedictModule_Call(ctx, "LPUSH", "cc", "l", "y");

    /* Miss some keys intentionally so we will get a "keymiss" notification. */
    RedictModule_Call(ctx, "GET", "c", "nosuchkey");
    RedictModule_Call(ctx, "SMEMBERS", "c", "nosuchkey");

    size_t sz;
    const char *rep;
    RedictModuleCallReply *r = RedictModule_Call(ctx, "HGET", "cc", "notifications", "foo");
    if (r == NULL || RedictModule_CallReplyType(r) != REDICTMODULE_REPLY_STRING) {
        FAIL("Wrong or no reply for foo");
    } else {
        rep = RedictModule_CallReplyStringPtr(r, &sz);
        if (sz != 1 || *rep != '2') {
            FAIL("Got reply '%s'. expected '2'", RedictModule_CallReplyStringPtr(r, NULL));
        }
    }

    r = RedictModule_Call(ctx, "HGET", "cc", "notifications", "bar");
    if (r == NULL || RedictModule_CallReplyType(r) != REDICTMODULE_REPLY_STRING) {
        FAIL("Wrong or no reply for bar");
    } else {
        rep = RedictModule_CallReplyStringPtr(r, &sz);
        if (sz != 1 || *rep != '2') {
            FAIL("Got reply '%s'. expected '2'", rep);
        }
    }

    r = RedictModule_Call(ctx, "HGET", "cc", "notifications", "baz");
    if (r == NULL || RedictModule_CallReplyType(r) != REDICTMODULE_REPLY_STRING) {
        FAIL("Wrong or no reply for baz");
    } else {
        rep = RedictModule_CallReplyStringPtr(r, &sz);
        if (sz != 1 || *rep != '1') {
            FAIL("Got reply '%.*s'. expected '1'", (int)sz, rep);
        }
    }
    /* For l we expect nothing since we didn't subscribe to list events */
    r = RedictModule_Call(ctx, "HGET", "cc", "notifications", "l");
    if (r == NULL || RedictModule_CallReplyType(r) != REDICTMODULE_REPLY_NULL) {
        FAIL("Wrong reply for l");
    }

    r = RedictModule_Call(ctx, "HGET", "cc", "notifications", "nosuchkey");
    if (r == NULL || RedictModule_CallReplyType(r) != REDICTMODULE_REPLY_STRING) {
        FAIL("Wrong or no reply for nosuchkey");
    } else {
        rep = RedictModule_CallReplyStringPtr(r, &sz);
        if (sz != 1 || *rep != '2') {
            FAIL("Got reply '%.*s'. expected '2'", (int)sz, rep);
        }
    }

    RedictModule_Call(ctx, "FLUSHDB", "");

    return RedictModule_ReplyWithSimpleString(ctx, "OK");
err:
    RedictModule_Call(ctx, "FLUSHDB", "");

    return RedictModule_ReplyWithSimpleString(ctx, "ERR");
}

/* TEST.CTXFLAGS -- Test GetContextFlags. */
int TestCtxFlags(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    REDICTMODULE_NOT_USED(argc);
    REDICTMODULE_NOT_USED(argv);

    RedictModule_AutoMemory(ctx);

    int ok = 1;
    const char *errString = NULL;
#undef FAIL
#define FAIL(msg)        \
    {                    \
        ok = 0;          \
        errString = msg; \
        goto end;        \
    }

    int flags = RedictModule_GetContextFlags(ctx);
    if (flags == 0) {
        FAIL("Got no flags");
    }

    if (flags & REDICTMODULE_CTX_FLAGS_LUA) FAIL("Lua flag was set");
    if (flags & REDICTMODULE_CTX_FLAGS_MULTI) FAIL("Multi flag was set");

    if (flags & REDICTMODULE_CTX_FLAGS_AOF) FAIL("AOF Flag was set")
    /* Enable AOF to test AOF flags */
    RedictModule_Call(ctx, "config", "ccc", "set", "appendonly", "yes");
    flags = RedictModule_GetContextFlags(ctx);
    if (!(flags & REDICTMODULE_CTX_FLAGS_AOF)) FAIL("AOF Flag not set after config set");

    /* Disable RDB saving and test the flag. */
    RedictModule_Call(ctx, "config", "ccc", "set", "save", "");
    flags = RedictModule_GetContextFlags(ctx);
    if (flags & REDICTMODULE_CTX_FLAGS_RDB) FAIL("RDB Flag was set");
    /* Enable RDB to test RDB flags */
    RedictModule_Call(ctx, "config", "ccc", "set", "save", "900 1");
    flags = RedictModule_GetContextFlags(ctx);
    if (!(flags & REDICTMODULE_CTX_FLAGS_RDB)) FAIL("RDB Flag was not set after config set");

    if (!(flags & REDICTMODULE_CTX_FLAGS_MASTER)) FAIL("Master flag was not set");
    if (flags & REDICTMODULE_CTX_FLAGS_SLAVE) FAIL("Slave flag was set");
    if (flags & REDICTMODULE_CTX_FLAGS_READONLY) FAIL("Read-only flag was set");
    if (flags & REDICTMODULE_CTX_FLAGS_CLUSTER) FAIL("Cluster flag was set");

    /* Disable maxmemory and test the flag. (it is implicitly set in 32bit builds. */
    RedictModule_Call(ctx, "config", "ccc", "set", "maxmemory", "0");
    flags = RedictModule_GetContextFlags(ctx);
    if (flags & REDICTMODULE_CTX_FLAGS_MAXMEMORY) FAIL("Maxmemory flag was set");

    /* Enable maxmemory and test the flag. */
    RedictModule_Call(ctx, "config", "ccc", "set", "maxmemory", "100000000");
    flags = RedictModule_GetContextFlags(ctx);
    if (!(flags & REDICTMODULE_CTX_FLAGS_MAXMEMORY))
        FAIL("Maxmemory flag was not set after config set");

    if (flags & REDICTMODULE_CTX_FLAGS_EVICT) FAIL("Eviction flag was set");
    RedictModule_Call(ctx, "config", "ccc", "set", "maxmemory-policy", "allkeys-lru");
    flags = RedictModule_GetContextFlags(ctx);
    if (!(flags & REDICTMODULE_CTX_FLAGS_EVICT)) FAIL("Eviction flag was not set after config set");

end:
    /* Revert config changes */
    RedictModule_Call(ctx, "config", "ccc", "set", "appendonly", "no");
    RedictModule_Call(ctx, "config", "ccc", "set", "save", "");
    RedictModule_Call(ctx, "config", "ccc", "set", "maxmemory", "0");
    RedictModule_Call(ctx, "config", "ccc", "set", "maxmemory-policy", "noeviction");

    if (!ok) {
        RedictModule_Log(ctx, "warning", "Failed CTXFLAGS Test. Reason: %s", errString);
        return RedictModule_ReplyWithSimpleString(ctx, "ERR");
    }

    return RedictModule_ReplyWithSimpleString(ctx, "OK");
}

/* ----------------------------- Test framework ----------------------------- */

/* Return 1 if the reply matches the specified string, otherwise log errors
 * in the server log and return 0. */
int TestAssertErrorReply(RedictModuleCtx *ctx, RedictModuleCallReply *reply, char *str, size_t len) {
    RedictModuleString *mystr, *expected;
    if (RedictModule_CallReplyType(reply) != REDICTMODULE_REPLY_ERROR) {
        return 0;
    }

    mystr = RedictModule_CreateStringFromCallReply(reply);
    expected = RedictModule_CreateString(ctx,str,len);
    if (RedictModule_StringCompare(mystr,expected) != 0) {
        const char *mystr_ptr = RedictModule_StringPtrLen(mystr,NULL);
        const char *expected_ptr = RedictModule_StringPtrLen(expected,NULL);
        RedictModule_Log(ctx,"warning",
            "Unexpected Error reply reply '%s' (instead of '%s')",
            mystr_ptr, expected_ptr);
        return 0;
    }
    return 1;
}

int TestAssertStringReply(RedictModuleCtx *ctx, RedictModuleCallReply *reply, char *str, size_t len) {
    RedictModuleString *mystr, *expected;

    if (RedictModule_CallReplyType(reply) == REDICTMODULE_REPLY_ERROR) {
        RedictModule_Log(ctx,"warning","Test error reply: %s",
            RedictModule_CallReplyStringPtr(reply, NULL));
        return 0;
    } else if (RedictModule_CallReplyType(reply) != REDICTMODULE_REPLY_STRING) {
        RedictModule_Log(ctx,"warning","Unexpected reply type %d",
            RedictModule_CallReplyType(reply));
        return 0;
    }
    mystr = RedictModule_CreateStringFromCallReply(reply);
    expected = RedictModule_CreateString(ctx,str,len);
    if (RedictModule_StringCompare(mystr,expected) != 0) {
        const char *mystr_ptr = RedictModule_StringPtrLen(mystr,NULL);
        const char *expected_ptr = RedictModule_StringPtrLen(expected,NULL);
        RedictModule_Log(ctx,"warning",
            "Unexpected string reply '%s' (instead of '%s')",
            mystr_ptr, expected_ptr);
        return 0;
    }
    return 1;
}

/* Return 1 if the reply matches the specified integer, otherwise log errors
 * in the server log and return 0. */
int TestAssertIntegerReply(RedictModuleCtx *ctx, RedictModuleCallReply *reply, long long expected) {
    if (RedictModule_CallReplyType(reply) == REDICTMODULE_REPLY_ERROR) {
        RedictModule_Log(ctx,"warning","Test error reply: %s",
            RedictModule_CallReplyStringPtr(reply, NULL));
        return 0;
    } else if (RedictModule_CallReplyType(reply) != REDICTMODULE_REPLY_INTEGER) {
        RedictModule_Log(ctx,"warning","Unexpected reply type %d",
            RedictModule_CallReplyType(reply));
        return 0;
    }
    long long val = RedictModule_CallReplyInteger(reply);
    if (val != expected) {
        RedictModule_Log(ctx,"warning",
            "Unexpected integer reply '%lld' (instead of '%lld')",
            val, expected);
        return 0;
    }
    return 1;
}

#define T(name,...) \
    do { \
        RedictModule_Log(ctx,"warning","Testing %s", name); \
        reply = RedictModule_Call(ctx,name,__VA_ARGS__); \
    } while (0)

/* TEST.BASICS -- Run all the tests.
 * Note: it is useful to run these tests from the module rather than TCL
 * since it's easier to check the reply types like that (make a distinction
 * between 0 and "0", etc. */
int TestBasics(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    REDICTMODULE_NOT_USED(argv);
    REDICTMODULE_NOT_USED(argc);

    RedictModule_AutoMemory(ctx);
    RedictModuleCallReply *reply;

    /* Make sure the DB is empty before to proceed. */
    T("dbsize","");
    if (!TestAssertIntegerReply(ctx,reply,0)) goto fail;

    T("ping","");
    if (!TestAssertStringReply(ctx,reply,"PONG",4)) goto fail;

    T("test.call","");
    if (!TestAssertStringReply(ctx,reply,"OK",2)) goto fail;

    T("test.callresp3map","");
    if (!TestAssertStringReply(ctx,reply,"OK",2)) goto fail;

    T("test.callresp3set","");
    if (!TestAssertStringReply(ctx,reply,"OK",2)) goto fail;

    T("test.callresp3double","");
    if (!TestAssertStringReply(ctx,reply,"OK",2)) goto fail;

    T("test.callresp3bool","");
    if (!TestAssertStringReply(ctx,reply,"OK",2)) goto fail;

    T("test.callresp3null","");
    if (!TestAssertStringReply(ctx,reply,"OK",2)) goto fail;

    T("test.callreplywithnestedreply","");
    if (!TestAssertStringReply(ctx,reply,"test",4)) goto fail;

    T("test.callreplywithbignumberreply","");
    if (!TestAssertStringReply(ctx,reply,"1234567999999999999999999999999999999",37)) goto fail;

    T("test.callreplywithverbatimstringreply","");
    if (!TestAssertStringReply(ctx,reply,"txt:This is a verbatim\nstring",29)) goto fail;

    T("test.ctxflags","");
    if (!TestAssertStringReply(ctx,reply,"OK",2)) goto fail;

    T("test.string.append","");
    if (!TestAssertStringReply(ctx,reply,"foobar",6)) goto fail;

    T("test.string.truncate","");
    if (!TestAssertStringReply(ctx,reply,"OK",2)) goto fail;

    T("test.unlink","");
    if (!TestAssertStringReply(ctx,reply,"OK",2)) goto fail;

    T("test.nestedcallreplyarray","");
    if (!TestAssertStringReply(ctx,reply,"OK",2)) goto fail;

    T("test.string.append.am","");
    if (!TestAssertStringReply(ctx,reply,"foobar",6)) goto fail;
    
    T("test.string.trim","");
    if (!TestAssertStringReply(ctx,reply,"OK",2)) goto fail;

    T("test.string.printf", "cc", "foo", "bar");
    if (!TestAssertStringReply(ctx,reply,"Got 3 args. argv[1]: foo, argv[2]: bar",38)) goto fail;

    T("test.notify", "");
    if (!TestAssertStringReply(ctx,reply,"OK",2)) goto fail;

    T("test.callreplywitharrayreply", "");
    if (RedictModule_CallReplyType(reply) != REDICTMODULE_REPLY_ARRAY) goto fail;
    if (RedictModule_CallReplyLength(reply) != 2) goto fail;
    if (!TestAssertStringReply(ctx,RedictModule_CallReplyArrayElement(reply, 0),"test",4)) goto fail;
    if (!TestAssertStringReply(ctx,RedictModule_CallReplyArrayElement(reply, 1),"1234",4)) goto fail;

    T("foo", "E");
    if (!TestAssertErrorReply(ctx,reply,"ERR unknown command 'foo', with args beginning with: ",53)) goto fail;

    T("set", "Ec", "x");
    if (!TestAssertErrorReply(ctx,reply,"ERR wrong number of arguments for 'set' command",47)) goto fail;

    T("shutdown", "SE");
    if (!TestAssertErrorReply(ctx,reply,"ERR command 'shutdown' is not allowed on script mode",52)) goto fail;

    T("set", "WEcc", "x", "1");
    if (!TestAssertErrorReply(ctx,reply,"ERR Write command 'set' was called while write is not allowed.",62)) goto fail;

    RedictModule_ReplyWithSimpleString(ctx,"ALL TESTS PASSED");
    return REDICTMODULE_OK;

fail:
    RedictModule_ReplyWithSimpleString(ctx,
        "SOME TEST DID NOT PASS! Check server logs");
    return REDICTMODULE_OK;
}

int RedictModule_OnLoad(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    REDICTMODULE_NOT_USED(argv);
    REDICTMODULE_NOT_USED(argc);

    if (RedictModule_Init(ctx,"test",1,REDICTMODULE_APIVER_1)
        == REDICTMODULE_ERR) return REDICTMODULE_ERR;

    /* Perform RM_Call inside the RedictModule_OnLoad
     * to verify that it works as expected without crashing.
     * The tests will verify it on different configurations
     * options (cluster/no cluster). A simple ping command
     * is enough for this test. */
    RedictModuleCallReply *reply = RedictModule_Call(ctx, "ping", "");
    if (RedictModule_CallReplyType(reply) != REDICTMODULE_REPLY_STRING) {
        RedictModule_FreeCallReply(reply);
        return REDICTMODULE_ERR;
    }
    size_t len;
    const char *reply_str = RedictModule_CallReplyStringPtr(reply, &len);
    if (len != 4) {
        RedictModule_FreeCallReply(reply);
        return REDICTMODULE_ERR;
    }
    if (memcmp(reply_str, "PONG", 4) != 0) {
        RedictModule_FreeCallReply(reply);
        return REDICTMODULE_ERR;
    }
    RedictModule_FreeCallReply(reply);

    if (RedictModule_CreateCommand(ctx,"test.call",
        TestCall,"write deny-oom",1,1,1) == REDICTMODULE_ERR)
        return REDICTMODULE_ERR;

    if (RedictModule_CreateCommand(ctx,"test.callresp3map",
        TestCallResp3Map,"write deny-oom",1,1,1) == REDICTMODULE_ERR)
        return REDICTMODULE_ERR;

    if (RedictModule_CreateCommand(ctx,"test.callresp3attribute",
        TestCallResp3Attribute,"write deny-oom",1,1,1) == REDICTMODULE_ERR)
        return REDICTMODULE_ERR;

    if (RedictModule_CreateCommand(ctx,"test.callresp3set",
        TestCallResp3Set,"write deny-oom",1,1,1) == REDICTMODULE_ERR)
        return REDICTMODULE_ERR;

    if (RedictModule_CreateCommand(ctx,"test.callresp3double",
        TestCallResp3Double,"write deny-oom",1,1,1) == REDICTMODULE_ERR)
        return REDICTMODULE_ERR;

    if (RedictModule_CreateCommand(ctx,"test.callresp3bool",
        TestCallResp3Bool,"write deny-oom",1,1,1) == REDICTMODULE_ERR)
        return REDICTMODULE_ERR;

    if (RedictModule_CreateCommand(ctx,"test.callresp3null",
        TestCallResp3Null,"write deny-oom",1,1,1) == REDICTMODULE_ERR)
        return REDICTMODULE_ERR;

    if (RedictModule_CreateCommand(ctx,"test.callreplywitharrayreply",
        TestCallReplyWithArrayReply,"write deny-oom",1,1,1) == REDICTMODULE_ERR)
        return REDICTMODULE_ERR;

    if (RedictModule_CreateCommand(ctx,"test.callreplywithnestedreply",
        TestCallReplyWithNestedReply,"write deny-oom",1,1,1) == REDICTMODULE_ERR)
        return REDICTMODULE_ERR;

    if (RedictModule_CreateCommand(ctx,"test.callreplywithbignumberreply",
        TestCallResp3BigNumber,"write deny-oom",1,1,1) == REDICTMODULE_ERR)
        return REDICTMODULE_ERR;

    if (RedictModule_CreateCommand(ctx,"test.callreplywithverbatimstringreply",
        TestCallResp3Verbatim,"write deny-oom",1,1,1) == REDICTMODULE_ERR)
        return REDICTMODULE_ERR;

    if (RedictModule_CreateCommand(ctx,"test.string.append",
        TestStringAppend,"write deny-oom",1,1,1) == REDICTMODULE_ERR)
        return REDICTMODULE_ERR;

    if (RedictModule_CreateCommand(ctx,"test.string.trim",
        TestTrimString,"write deny-oom",1,1,1) == REDICTMODULE_ERR)
        return REDICTMODULE_ERR;

    if (RedictModule_CreateCommand(ctx,"test.string.append.am",
        TestStringAppendAM,"write deny-oom",1,1,1) == REDICTMODULE_ERR)
        return REDICTMODULE_ERR;

    if (RedictModule_CreateCommand(ctx,"test.string.truncate",
        TestStringTruncate,"write deny-oom",1,1,1) == REDICTMODULE_ERR)
        return REDICTMODULE_ERR;

    if (RedictModule_CreateCommand(ctx,"test.string.printf",
        TestStringPrintf,"write deny-oom",1,1,1) == REDICTMODULE_ERR)
        return REDICTMODULE_ERR;

    if (RedictModule_CreateCommand(ctx,"test.ctxflags",
        TestCtxFlags,"readonly",1,1,1) == REDICTMODULE_ERR)
        return REDICTMODULE_ERR;

    if (RedictModule_CreateCommand(ctx,"test.unlink",
        TestUnlink,"write deny-oom",1,1,1) == REDICTMODULE_ERR)
        return REDICTMODULE_ERR;

    if (RedictModule_CreateCommand(ctx,"test.nestedcallreplyarray",
        TestNestedCallReplyArrayElement,"write deny-oom",1,1,1) == REDICTMODULE_ERR)
        return REDICTMODULE_ERR;

    if (RedictModule_CreateCommand(ctx,"test.basics",
        TestBasics,"write",1,1,1) == REDICTMODULE_ERR)
        return REDICTMODULE_ERR;

    /* the following commands are used by an external test and should not be added to TestBasics */
    if (RedictModule_CreateCommand(ctx,"test.rmcallautomode",
        TestCallRespAutoMode,"write",1,1,1) == REDICTMODULE_ERR)
        return REDICTMODULE_ERR;

    if (RedictModule_CreateCommand(ctx,"test.getresp",
        TestGetResp,"readonly",1,1,1) == REDICTMODULE_ERR)
        return REDICTMODULE_ERR;

    RedictModule_SubscribeToKeyspaceEvents(ctx,
                                            REDICTMODULE_NOTIFY_HASH |
                                            REDICTMODULE_NOTIFY_SET |
                                            REDICTMODULE_NOTIFY_STRING |
                                            REDICTMODULE_NOTIFY_KEY_MISS,
                                        NotifyCallback);
    if (RedictModule_CreateCommand(ctx,"test.notify",
        TestNotifications,"write deny-oom",1,1,1) == REDICTMODULE_ERR)
        return REDICTMODULE_ERR;

    return REDICTMODULE_OK;
}
