1c6d08702a0075270e8cc5d7f6f4f395b17c8906
[platform/upstream/iotjs.git] / tools / src / module / iotjs_module_testdriver.c
1 /* Copyright 2016-present Samsung Electronics Co., Ltd. and other contributors
2  *
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15
16 #include "iotjs_def.h"
17 #include "iotjs_module_timer.h"
18
19
20 // Only for test driver
21 JHANDLER_FUNCTION(IsAliveExceptFor) {
22   JHANDLER_CHECK(iotjs_jhandler_get_arg_length(jhandler) == 1);
23   const iotjs_environment_t* env = iotjs_environment_get();
24   uv_loop_t* loop = iotjs_environment_loop(env);
25
26   const iotjs_jval_t* arg0 = iotjs_jhandler_get_arg(jhandler, 0);
27
28   if (iotjs_jval_is_null(arg0)) {
29     int alive = uv_loop_alive(loop);
30
31     iotjs_jhandler_return_boolean(jhandler, alive);
32   } else {
33     JHANDLER_CHECK(iotjs_jval_is_object(arg0));
34
35     iotjs_jval_t jtimer =
36         iotjs_jval_get_property(arg0, IOTJS_MAGIC_STRING_HANDLER);
37
38     iotjs_timerwrap_t* timer_wrap = iotjs_timerwrap_from_jobject(&jtimer);
39     iotjs_jval_destroy(&jtimer);
40
41     bool has_active_reqs = uv_loop_has_active_reqs(loop);
42     bool has_closing_handler = loop->closing_handles != NULL;
43
44     bool ret = true;
45     bool alive = !has_active_reqs && !has_closing_handler;
46     if (alive) {
47       int active_handlers = loop->active_handles;
48       if (active_handlers == 1) {
49         const uv_timer_t* timer_handle = iotjs_timerwrap_handle(timer_wrap);
50         int timer_alive = uv_is_active((uv_handle_t*)timer_handle);
51
52         if (timer_alive) {
53           // If the timer handler we set for test driver is alive,
54           // then it can be safely terminated.
55           ret = false;
56         }
57       }
58     }
59
60     iotjs_jhandler_return_boolean(jhandler, ret);
61   }
62 }
63
64
65 iotjs_jval_t InitTestdriver() {
66   iotjs_jval_t testdriver = iotjs_jval_create_object();
67   iotjs_jval_set_method(&testdriver, IOTJS_MAGIC_STRING_ISALIVEEXCEPTFOR,
68                         IsAliveExceptFor);
69
70   return testdriver;
71 }