unittests.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  1. /*##############################################################################
  2. HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ############################################################################## */
  13. #ifdef _USE_CPPUNIT
  14. #include "unittests.hpp"
  15. #include "jstats.h"
  16. #include "jregexp.hpp"
  17. #include "jfile.hpp"
  18. #include "deftype.hpp"
  19. #include "rmtfile.hpp"
  20. /*
  21. * This is the main unittest driver for HPCC. From here,
  22. * all unit tests, be they internal or external (API),
  23. * will run.
  24. *
  25. * All internal unit tests, written on the same source
  26. * files as the implementation they're testing, can be
  27. * dynamically linked via the helper class below.
  28. *
  29. * All external unit tests (API tests, test-driven
  30. * development, interface documentation and general
  31. * usability tests) should be implemented as source
  32. * files within the same directory as this file, and
  33. * statically linked together.
  34. *
  35. * CPPUnit will automatically recognise and run them all.
  36. */
  37. void usage()
  38. {
  39. printf("\n"
  40. "Usage:\n"
  41. " unittests <options> <testnames>\n"
  42. "\n"
  43. "Options:\n"
  44. " -a --all Include all tests, including timing and stress tests\n"
  45. " -d --load path Dynamically load a library/all libraries in a directory.\n"
  46. " By default, the HPCCSystems lib directory is loaded.\n"
  47. " -e --exact Match subsequent test names exactly\n"
  48. " -h --help Display this help text\n"
  49. " -l --list List matching tests but do not execute them\n"
  50. " -x --exclude Exclude subsequent test names\n"
  51. "\n");
  52. }
  53. bool matchName(const char *name, const StringArray &patterns)
  54. {
  55. ForEachItemIn(idx, patterns)
  56. {
  57. bool match;
  58. const char *pattern = patterns.item(idx);
  59. if (strchr(pattern, '*'))
  60. {
  61. match = WildMatch(name, pattern, true);
  62. }
  63. else
  64. match = streq(name, pattern);
  65. if (match)
  66. return true;
  67. }
  68. return false;
  69. }
  70. LoadedObject *loadDll(const char *thisDll)
  71. {
  72. try
  73. {
  74. DBGLOG("Loading %s", thisDll);
  75. return new LoadedObject(thisDll);
  76. }
  77. catch (IException *E)
  78. {
  79. E->Release();
  80. }
  81. catch (...)
  82. {
  83. }
  84. return NULL;
  85. }
  86. void loadDlls(IArray &objects, const char * libDirectory)
  87. {
  88. const char * mask = "*" SharedObjectExtension;
  89. Owned<IFile> libDir = createIFile(libDirectory);
  90. Owned<IDirectoryIterator> libFiles = libDir->directoryFiles(mask,false,false);
  91. ForEach(*libFiles)
  92. {
  93. const char *thisDll = libFiles->query().queryFilename();
  94. if (!strstr(thisDll, "javaembed")) // Bit of a hack, but loading this if java not present terminates...
  95. if (!strstr(thisDll, "py2embed")) // These two clash, so ...
  96. if (!strstr(thisDll, "py3embed")) // ... best to load neither...
  97. {
  98. LoadedObject *loaded = loadDll(thisDll);
  99. if (loaded)
  100. objects.append(*loaded);
  101. }
  102. }
  103. }
  104. int main(int argc, char* argv[])
  105. {
  106. InitModuleObjects();
  107. StringArray includeNames;
  108. StringArray excludeNames;
  109. StringArray loadLocations;
  110. bool wildMatch = true;
  111. bool exclude = false;
  112. bool includeAll = false;
  113. bool verbose = false;
  114. bool list = false;
  115. bool useDefaultLocations = true;
  116. for (int argNo = 1; argNo < argc; argNo++)
  117. {
  118. const char *arg = argv[argNo];
  119. if (arg[0]=='-')
  120. {
  121. if (streq(arg, "-x") || streq(arg, "--exclude"))
  122. exclude = true;
  123. else if (streq(arg, "-v") || streq(arg, "--verbose"))
  124. verbose = true;
  125. else if (streq(arg, "-e") || streq(arg, "--exact"))
  126. wildMatch = false;
  127. else if (streq(arg, "-a") || streq(arg, "--all"))
  128. includeAll = true;
  129. else if (streq(arg, "-l") || streq(arg, "--list"))
  130. list = true;
  131. else if (streq(arg, "-d") || streq(arg, "--load"))
  132. {
  133. useDefaultLocations = false;
  134. argNo++;
  135. if (argNo<argc)
  136. loadLocations.append(argv[argNo]);
  137. }
  138. else
  139. {
  140. usage();
  141. exit(streq(arg, "-h") || streq(arg, "--help")?0:4);
  142. }
  143. }
  144. else
  145. {
  146. VStringBuffer pattern("*%s*", arg);
  147. if (wildMatch && !strchr(arg, '*'))
  148. arg = pattern.str();
  149. if (exclude)
  150. excludeNames.append(arg);
  151. else
  152. includeNames.append(arg);
  153. }
  154. }
  155. if (verbose)
  156. queryStderrLogMsgHandler()->setMessageFields(MSGFIELD_time);
  157. else
  158. removeLog();
  159. if (!includeNames.length())
  160. includeNames.append("*");
  161. if (!includeAll)
  162. {
  163. excludeNames.append("*stress*");
  164. excludeNames.append("*timing*");
  165. }
  166. if (useDefaultLocations)
  167. {
  168. // Default library location depends on the executable location...
  169. StringBuffer dir;
  170. splitFilename(argv[0], &dir, &dir, NULL, NULL);
  171. dir.replaceString(PATHSEPSTR "bin" PATHSEPSTR, PATHSEPSTR "lib" PATHSEPSTR);
  172. if (verbose)
  173. DBGLOG("Adding default library location %s", dir.str());
  174. loadLocations.append(dir);
  175. #ifdef _DEBUG
  176. dir.replaceString(PATHSEPSTR "lib" PATHSEPSTR, PATHSEPSTR "libs" PATHSEPSTR);
  177. loadLocations.append(dir);
  178. if (verbose)
  179. DBGLOG("Adding default library location %s", dir.str());
  180. #endif
  181. }
  182. IArray objects;
  183. ForEachItemIn(idx, loadLocations)
  184. {
  185. const char *location = loadLocations.item(idx);
  186. Owned<IFile> file = createIFile(location);
  187. switch (file->isDirectory())
  188. {
  189. case notFound:
  190. if (verbose && !useDefaultLocations)
  191. DBGLOG("Specified library location %s not found", location);
  192. break;
  193. case foundYes:
  194. loadDlls(objects, location);
  195. break;
  196. case foundNo:
  197. LoadedObject *loaded = loadDll(location);
  198. if (loaded)
  199. objects.append(*loaded);
  200. break;
  201. }
  202. }
  203. bool wasSuccessful = false;
  204. {
  205. // New scope as we need the TestRunner to be destroyed before unloading the dlls...
  206. CppUnit::TestFactoryRegistry &registry = CppUnit::TestFactoryRegistry::getRegistry();
  207. CppUnit::TextUi::TestRunner runner;
  208. CppUnit::Test *all = registry.makeTest();
  209. int numTests = all->getChildTestCount();
  210. for (int i = 0; i < numTests; i++)
  211. {
  212. CppUnit::Test *sub = all->getChildTestAt(i);
  213. std::string name = sub->getName();
  214. if (matchName(name.c_str(), includeNames))
  215. {
  216. if (matchName(name.c_str(), excludeNames))
  217. {
  218. if (verbose)
  219. DBGLOG("Excluding test %s", name.c_str());
  220. }
  221. else if (list)
  222. printf("%s\n", name.c_str());
  223. else
  224. {
  225. if (verbose)
  226. DBGLOG("Including test %s", name.c_str());
  227. runner.addTest(sub);
  228. }
  229. }
  230. }
  231. wasSuccessful = list || runner.run( "", false );
  232. }
  233. releaseAtoms();
  234. ClearTypeCache(); // Clear this cache before the file hooks are unloaded
  235. removeFileHooks();
  236. objects.kill();
  237. ExitModuleObjects();
  238. return wasSuccessful;
  239. }
  240. //MORE: This can't be included in jlib because of the dll dependency
  241. class InternalStatisticsTest : public CppUnit::TestFixture
  242. {
  243. CPPUNIT_TEST_SUITE( InternalStatisticsTest );
  244. CPPUNIT_TEST(testMappings);
  245. CPPUNIT_TEST_SUITE_END();
  246. void testMappings()
  247. {
  248. try
  249. {
  250. verifyStatisticFunctions();
  251. }
  252. catch (IException * e)
  253. {
  254. StringBuffer msg;
  255. fprintf(stderr, "Failure: %s", e->errorMessage(msg).str());
  256. e->Release();
  257. ASSERT(false);
  258. }
  259. }
  260. };
  261. CPPUNIT_TEST_SUITE_REGISTRATION( InternalStatisticsTest );
  262. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( InternalStatisticsTest, "StatisticsTest" );
  263. class PtreeThreadingTest : public CppUnit::TestFixture
  264. {
  265. CPPUNIT_TEST_SUITE( PtreeThreadingTest );
  266. CPPUNIT_TEST(testContention);
  267. CPPUNIT_TEST_SUITE_END();
  268. void testContention()
  269. {
  270. _testContention(ipt_lowmem);
  271. _testContention(ipt_fast);
  272. }
  273. void _testContention(byte flags)
  274. {
  275. class casyncfor: public CAsyncFor
  276. {
  277. volatile int v;
  278. void donothing()
  279. {
  280. v++;
  281. }
  282. byte flags = ipt_none;
  283. int mode = 0;
  284. int iterations = 0;
  285. const char *desc = nullptr;
  286. public:
  287. casyncfor(const char *_desc, byte _flags, int _mode, int _iter)
  288. : flags(_flags), mode(_mode), iterations(_iter), desc(_desc)
  289. {
  290. };
  291. double For(unsigned num, unsigned maxatonce, double overhead = 0.0)
  292. {
  293. unsigned start = msTick();
  294. CAsyncFor::For(num, maxatonce);
  295. unsigned elapsed = msTick()-start;
  296. double looptime = (elapsed * 1.0) / (iterations*num);
  297. if (mode < 3)
  298. DBGLOG("%s (%s) test completed in %d ms (%f ms/iter)", desc, flags & ipt_fast ? "fast" : "lowmem", elapsed, looptime-overhead);
  299. return looptime;
  300. }
  301. void Do(unsigned i)
  302. {
  303. for (unsigned i = 0; i < iterations; i++)
  304. {
  305. Owned<IPropertyTree> p = mode >= 3 ? nullptr : createPTreeFromXMLString(
  306. "<W_LOCAL buildVersion='community_6.0.0-trunk0Debug[heads/cass-wu-part3-0-g10b954-dirty]'"
  307. " cloneable='1'"
  308. " clusterName=''"
  309. " codeVersion='158'"
  310. " eclVersion='6.0.0'"
  311. " hash='2796091347'"
  312. " state='completed'"
  313. " xmlns:xsi='http://www.w3.org/1999/XMLSchema-instance'>"
  314. " <Debug>"
  315. " <debugquery>1</debugquery>"
  316. " <expandpersistinputdependencies>1</expandpersistinputdependencies>"
  317. " <savecpptempfiles>1</savecpptempfiles>"
  318. " <saveecltempfiles>1</saveecltempfiles>"
  319. " <spanmultiplecpp>0</spanmultiplecpp>"
  320. " <standaloneexe>1</standaloneexe>"
  321. " <targetclustertype>hthor</targetclustertype>"
  322. " </Debug>"
  323. " <FilesRead>"
  324. " <File name='myfile' useCount='2' cluster = 'mycluster'/>"
  325. " <File name='mysuperfile' useCount='2' cluster = 'mycluster'>"
  326. " <Subfile name='myfile'/>"
  327. " </File>"
  328. "</FilesRead>"
  329. " <Graphs>"
  330. " <Graph name='graph1' type='activities'>"
  331. " <xgmml>"
  332. " <graph wfid='2'>"
  333. " <node id='1'>"
  334. " <att>"
  335. " <graph>"
  336. " <att name='rootGraph' value='1'/>"
  337. " <edge id='2_0' source='2' target='3'/>"
  338. " <edge id='3_0' source='3' target='4'/>"
  339. " <edge id='4_0' source='4' target='5'/>"
  340. " <node id='2' label='Inline Row&#10;{1}'>"
  341. " <att name='definition' value='./sets.ecl(2,13)'/>"
  342. " <att name='_kind' value='148'/>"
  343. " <att name='ecl' value='ROW(TRANSFORM({ integer8 v },SELF.v := 1;));&#10;'/>"
  344. " <att name='recordSize' value='8'/>"
  345. " <att name='predictedCount' value='1'/>"
  346. " </node>"
  347. " <node id='3' label='Filter'>"
  348. " <att name='definition' value='./sets.ecl(3,15)'/>"
  349. " <att name='_kind' value='5'/>"
  350. " <att name='ecl' value='FILTER(v = STORED(&apos;one&apos;));&#10;'/>"
  351. " <att name='recordSize' value='8'/>"
  352. " <att name='predictedCount' value='0..?[disk]'/>"
  353. " </node>"
  354. " <node id='4' label='Count'>"
  355. " <att name='_kind' value='125'/>"
  356. " <att name='ecl' value='TABLE({ integer8 value := COUNT(group) });&#10;'/>"
  357. " <att name='recordSize' value='8'/>"
  358. " <att name='predictedCount' value='1'/>"
  359. " </node>"
  360. " <node id='5' label='Store&#10;Internal(&apos;wf2&apos;)'>"
  361. " <att name='_kind' value='22'/>"
  362. " <att name='ecl' value='extractresult(value, named(&apos;wf2&apos;));&#10;'/>"
  363. " <att name='recordSize' value='8'/>"
  364. " </node>"
  365. " </graph>"
  366. " </att>"
  367. " </node>"
  368. " </graph>"
  369. " </xgmml>"
  370. " </Graph>"
  371. " <Graph name='graph2' type='activities'>"
  372. " <xgmml>"
  373. " <graph wfid='3'>"
  374. " <node id='6'>"
  375. " <att>"
  376. " <graph>"
  377. " <att name='rootGraph' value='1'/>"
  378. " <edge id='7_0' source='7' target='8'/>"
  379. " <edge id='8_0' source='8' target='9'/>"
  380. " <node id='7' label='Inline Row&#10;{1}'>"
  381. " <att name='definition' value='./sets.ecl(2,13)'/>"
  382. " <att name='_kind' value='148'/>"
  383. " <att name='ecl' value='ROW(TRANSFORM({ integer8 v },SELF.v := 1;));&#10;'/>"
  384. " <att name='recordSize' value='8'/>"
  385. " <att name='predictedCount' value='1'/>"
  386. " </node>"
  387. " <node id='8' label='Filter'>"
  388. " <att name='definition' value='./sets.ecl(5,1)'/>"
  389. " <att name='_kind' value='5'/>"
  390. " <att name='ecl' value='FILTER(v = INTERNAL(&apos;wf2&apos;));&#10;'/>"
  391. " <att name='recordSize' value='8'/>"
  392. " <att name='predictedCount' value='0..?[disk]'/>"
  393. " </node>"
  394. " <node id='9' label='Output&#10;Result #1'>"
  395. " <att name='definition' value='./sets.ecl(1,1)'/>"
  396. " <att name='name' value='sets'/>"
  397. " <att name='definition' value='./sets.ecl(5,1)'/>"
  398. " <att name='_kind' value='16'/>"
  399. " <att name='ecl' value='OUTPUT(..., workunit);&#10;'/>"
  400. " <att name='recordSize' value='8'/>"
  401. " </node>"
  402. " </graph>"
  403. " </att>"
  404. " </node>"
  405. " </graph>"
  406. " </xgmml>"
  407. " </Graph>"
  408. " </Graphs>"
  409. " <Query fetchEntire='1'>"
  410. " <Associated>"
  411. " <File desc='a.out.cpp'"
  412. " filename='/Users/rchapman/HPCC-Platform/ossd/a.out.cpp'"
  413. " ip='192.168.2.203'"
  414. " type='cpp'/>"
  415. " </Associated>"
  416. " </Query>"
  417. " <Results>"
  418. " <Result isScalar='0'"
  419. " name='Result 1'"
  420. " recordSizeEntry='mf1'"
  421. " rowLimit='-1'"
  422. " sequence='0'"
  423. " status='calculated'>"
  424. " <rowCount>1</rowCount>"
  425. " <SchemaRaw xsi:type='SOAP-ENC:base64'>"
  426. " dgABCAEAGBAAAAB7IGludGVnZXI4IHYgfTsK </SchemaRaw>"
  427. " <totalRowCount>1</totalRowCount>"
  428. " <Value xsi:type='SOAP-ENC:base64'>"
  429. " AQAAAAAAAAA= </Value>"
  430. " </Result>"
  431. " </Results>"
  432. " <State>completed</State>"
  433. " <Statistics>"
  434. " <Statistic c='eclcc'"
  435. " count='1'"
  436. " creator='eclcc'"
  437. " kind='TimeElapsed'"
  438. " s='compile'"
  439. " scope='compile:parseTime'"
  440. " ts='1431603789722535'"
  441. " unit='ns'"
  442. " value='805622'/>"
  443. " <Statistic c='unknown'"
  444. " count='1'"
  445. " creator='unknownRichards-iMac.local'"
  446. " kind='WhenQueryStarted'"
  447. " s='global'"
  448. " scope='workunit'"
  449. " ts='1431603790007020'"
  450. " unit='ts'"
  451. " value='1431603790007001'/>"
  452. " <Statistic c='unknown'"
  453. " count='1'"
  454. " creator='unknownRichards-iMac.local'"
  455. " desc='Graph graph1'"
  456. " kind='TimeElapsed'"
  457. " s='graph'"
  458. " scope='graph1'"
  459. " ts='1431603790007912'"
  460. " unit='ns'"
  461. " value='0'/>"
  462. " </Statistics>"
  463. " <Temporaries>"
  464. " <Variable name='wf2' status='calculated'>"
  465. " <rowCount>1</rowCount>"
  466. " <totalRowCount>1</totalRowCount>"
  467. " <Value xsi:type='SOAP-ENC:base64'>"
  468. " AQAAAAAAAAA= </Value>"
  469. " </Variable>"
  470. " </Temporaries>"
  471. " <Tracing>"
  472. " <EclAgentBuild>community_6.0.0-trunk0Debug[heads/cass-wu-part3-0-g10b954-dirty]</EclAgentBuild>"
  473. " </Tracing>"
  474. " <Variables>"
  475. " <Variable name='one' sequence='-1' status='calculated'>"
  476. " <rowCount>1</rowCount>"
  477. " <SchemaRaw xsi:type='SOAP-ENC:base64'>"
  478. " b25lAAEIAQAYAAAAAA== </SchemaRaw>"
  479. " <totalRowCount>1</totalRowCount>"
  480. " <Value xsi:type='SOAP-ENC:base64'>"
  481. " AQAAAAAAAAA= </Value>"
  482. " </Variable>"
  483. " </Variables>"
  484. " <Workflow>"
  485. " <Item mode='normal'"
  486. " state='done'"
  487. " type='normal'"
  488. " wfid='1'/>"
  489. " <Item mode='normal'"
  490. " state='done'"
  491. " type='normal'"
  492. " wfid='2'>"
  493. " <Dependency wfid='1'/>"
  494. " </Item>"
  495. " <Item mode='normal'"
  496. " state='done'"
  497. " type='normal'"
  498. " wfid='3'>"
  499. " <Dependency wfid='2'/>"
  500. " <Schedule/>"
  501. " </Item>"
  502. " </Workflow>"
  503. "</W_LOCAL>"
  504. , flags);
  505. switch(mode)
  506. {
  507. case 1: case 3: for (int j = 0; j < 100000; j++) donothing(); break;
  508. case 2: case 4: for (int j = 0; j < 1000000; j++) donothing(); break;
  509. }
  510. }
  511. }
  512. } max("maxContention",flags,0,1000),
  513. some("someContention",flags,1,200),
  514. min("minContention",flags,2,200),
  515. csome("control some",flags,3,200),
  516. cmin("control min",flags,4,200),
  517. seq("single",flags,0,1000);
  518. max.For(8,8);
  519. some.For(8,8,csome.For(8,8));
  520. min.For(8,8,cmin.For(8,8));
  521. seq.For(8,1);
  522. }
  523. };
  524. CPPUNIT_TEST_SUITE_REGISTRATION( PtreeThreadingTest );
  525. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( PtreeThreadingTest, "PtreeThreadingTest" );
  526. //MORE: This can't be included in jlib because of the dll dependency
  527. class StringBufferTest : public CppUnit::TestFixture
  528. {
  529. CPPUNIT_TEST_SUITE( StringBufferTest );
  530. CPPUNIT_TEST(testReplace);
  531. CPPUNIT_TEST_SUITE_END();
  532. void testReplace()
  533. {
  534. StringBuffer r ("1 bb c");
  535. r.replaceString(" ", "x");
  536. ASSERT(streq(r, "1xbbxc"));
  537. }
  538. };
  539. CPPUNIT_TEST_SUITE_REGISTRATION( StringBufferTest );
  540. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( StringBufferTest, "StringBufferTest" );
  541. #endif // _USE_CPPUNIT