Fix for x86_64 build fail
[platform/upstream/connectedhomeip.git] / src / lib / support / UnitTestRegistration.cpp
1 /*
2  *
3  *    Copyright (c) 2020 Project CHIP Authors
4  *
5  *    Licensed under the Apache License, Version 2.0 (the "License");
6  *    you may not use this file except in compliance with the License.
7  *    You may obtain a copy of the License at
8  *
9  *        http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *    Unless required by applicable law or agreed to in writing, software
12  *    distributed under the License is distributed on an "AS IS" BASIS,
13  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *    See the License for the specific language governing permissions and
15  *    limitations under the License.
16  */
17
18 #include <stdlib.h>
19 #include <string.h>
20 #include <support/UnitTestRegistration.h>
21
22 namespace chip {
23
24 const size_t kTestSuitesMax = 64;
25
26 typedef struct
27 {
28     UnitTestTriggerFunction test_suites[kTestSuitesMax];
29     uint32_t num_test_suites;
30 } test_suites_t;
31
32 static test_suites_t gs_test_suites;
33
34 #if __ZEPHYR__
35 inline static bool AlreadyExists(UnitTestTriggerFunction tests)
36 {
37     for (uint32_t i = 0; i < gs_test_suites.num_test_suites; ++i)
38         if (gs_test_suites.test_suites[i] == tests)
39             return true;
40     return false;
41 }
42 #endif
43
44 CHIP_ERROR RegisterUnitTests(UnitTestTriggerFunction tests)
45 {
46     if (gs_test_suites.num_test_suites >= kTestSuitesMax)
47     {
48         return CHIP_ERROR_NO_MEMORY;
49     }
50
51 #if __ZEPHYR__
52     // Not sure yet if it's a Zephyr bug or misconfiguration, but global constructors are called
53     // twice on native_posix platform - by libc and by Zephyr's main thread initialization code.
54     // This makes sure tests are not run twice for that reason.
55     if (AlreadyExists(tests))
56         return CHIP_NO_ERROR;
57 #endif
58
59     gs_test_suites.test_suites[gs_test_suites.num_test_suites] = tests;
60     gs_test_suites.num_test_suites++;
61     return CHIP_NO_ERROR;
62 }
63
64 int RunRegisteredUnitTests()
65 {
66     int status = 0;
67     for (uint32_t i = 0; i < gs_test_suites.num_test_suites; i++)
68     {
69         status += gs_test_suites.test_suites[i]();
70     }
71     return status;
72 }
73
74 } // namespace chip