Browse Source

Update module testcase with module.exports example

pull/589/head
Sami Vaarala 9 years ago
parent
commit
790393008d
  1. 76
      tests/api/test-dev-cmodule-guide.c

76
tests/api/test-dev-cmodule-guide.c

@ -2,13 +2,6 @@
* Module example from guide, as a more concrete test case.
*/
/*===
*** test_use_module (duk_safe_call)
my_func_2() called
final top: 0
==> rc=0, result='undefined'
===*/
/* Include duktape.h and whatever platform headers are needed. */
#include "duktape.h"
@ -52,6 +45,13 @@ static duk_ret_t dukopen_my_module(duk_context *ctx) {
* Calling code
*/
/*===
*** test_use_module (duk_safe_call)
my_func_2() called
final top: 0
==> rc=0, result='undefined'
===*/
static duk_ret_t test_use_module(duk_context *ignored_ctx) {
duk_context *ctx;
@ -72,6 +72,68 @@ static duk_ret_t test_use_module(duk_context *ignored_ctx) {
return 0;
}
/*
* Example of how a modSearch() function can use module.exports to return
* the C module initialization value.
*/
/*===
*** test_modsearch_module (duk_safe_call)
1
my_func_1() called
final top: 0
==> rc=0, result='undefined'
===*/
static duk_ret_t my_modsearch(duk_context *ctx) {
/* Arguments: id, require, exports, module.
*
* The 'id' is ignored in this example, normally you'd use 'id' to
* select which module to initialize.
*/
/* Initialize the C module. */
duk_push_c_function(ctx, dukopen_my_module, 0);
duk_call(ctx, 0);
/* Result is now on stack top. Overwrite module.exports to make
* that value come out from require().
*/
/* [ id require exports module c_module ] */
duk_put_prop_string(ctx, 3 /*module*/, "exports"); /* module.exports = c_module; */
return 0; /* return undefined, no Ecmascript source code */
}
static duk_ret_t test_modsearch_module(duk_context *ignored_ctx) {
duk_context *ctx;
ctx = duk_create_heap_default();
if (!ctx) {
printf("Failed to create heap\n");
return 0;
}
/* Register Duktape.modSearch. */
duk_eval_string(ctx, "(function (fun) { Duktape.modSearch = fun; })");
duk_push_c_function(ctx, my_modsearch, 4 /*nargs*/);
duk_call(ctx, 1);
duk_pop(ctx);
/* Require test. */
duk_eval_string_noresult(ctx, "var mod = require('my_module'); print(mod.FLAG_FOO); mod.func1();");
printf("final top: %ld\n", (long) duk_get_top(ctx));
duk_destroy_heap(ctx);
return 0;
}
/*
* Main
*/
void test(duk_context *ctx) {
TEST_SAFE_CALL(test_use_module);
TEST_SAFE_CALL(test_modsearch_module);
}

Loading…
Cancel
Save