unittests.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868
  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. #include "thorhelper.hpp"
  21. #include "libbase58.h"
  22. /*
  23. * This is the main unittest driver for HPCC. From here,
  24. * all unit tests, be they internal or external (API),
  25. * will run.
  26. *
  27. * All internal unit tests, written on the same source
  28. * files as the implementation they're testing, can be
  29. * dynamically linked via the helper class below.
  30. *
  31. * All external unit tests (API tests, test-driven
  32. * development, interface documentation and general
  33. * usability tests) should be implemented as source
  34. * files within the same directory as this file, and
  35. * statically linked together.
  36. *
  37. * CPPUnit will automatically recognise and run them all.
  38. */
  39. void usage()
  40. {
  41. printf("\n"
  42. "Usage:\n"
  43. " unittests <options> <testnames>\n"
  44. "\n"
  45. "Options:\n"
  46. " -a --all Include all tests, including timing and stress tests\n"
  47. " -d --load path Dynamically load a library/all libraries in a directory.\n"
  48. " By default, the HPCCSystems lib directory is loaded.\n"
  49. " -e --exact Match subsequent test names exactly\n"
  50. " -h --help Display this help text\n"
  51. " -l --list List matching tests but do not execute them\n"
  52. " -x --exclude Exclude subsequent test names\n"
  53. "\n");
  54. }
  55. bool matchName(const char *name, const StringArray &patterns)
  56. {
  57. ForEachItemIn(idx, patterns)
  58. {
  59. bool match;
  60. const char *pattern = patterns.item(idx);
  61. if (strchr(pattern, '*'))
  62. {
  63. match = WildMatch(name, pattern, true);
  64. }
  65. else
  66. match = streq(name, pattern);
  67. if (match)
  68. return true;
  69. }
  70. return false;
  71. }
  72. LoadedObject *loadDll(const char *thisDll)
  73. {
  74. try
  75. {
  76. DBGLOG("Loading %s", thisDll);
  77. return new LoadedObject(thisDll);
  78. }
  79. catch (IException *E)
  80. {
  81. E->Release();
  82. }
  83. catch (...)
  84. {
  85. }
  86. return NULL;
  87. }
  88. void loadDlls(IArray &objects, const char * libDirectory)
  89. {
  90. const char * mask = "*" SharedObjectExtension;
  91. Owned<IFile> libDir = createIFile(libDirectory);
  92. Owned<IDirectoryIterator> libFiles = libDir->directoryFiles(mask,false,false);
  93. ForEach(*libFiles)
  94. {
  95. const char *thisDll = libFiles->query().queryFilename();
  96. if (!strstr(thisDll, "javaembed")) // Bit of a hack, but loading this if java not present terminates...
  97. if (!strstr(thisDll, "py2embed")) // These two clash, so ...
  98. if (!strstr(thisDll, "py3embed")) // ... best to load neither...
  99. {
  100. LoadedObject *loaded = loadDll(thisDll);
  101. if (loaded)
  102. objects.append(*loaded);
  103. }
  104. }
  105. }
  106. int main(int argc, char* argv[])
  107. {
  108. InitModuleObjects();
  109. StringArray includeNames;
  110. StringArray excludeNames;
  111. StringArray loadLocations;
  112. bool wildMatch = true;
  113. bool exclude = false;
  114. bool includeAll = false;
  115. bool verbose = false;
  116. bool list = false;
  117. bool useDefaultLocations = true;
  118. for (int argNo = 1; argNo < argc; argNo++)
  119. {
  120. const char *arg = argv[argNo];
  121. if (arg[0]=='-')
  122. {
  123. if (streq(arg, "-x") || streq(arg, "--exclude"))
  124. exclude = true;
  125. else if (streq(arg, "-v") || streq(arg, "--verbose"))
  126. verbose = true;
  127. else if (streq(arg, "-e") || streq(arg, "--exact"))
  128. wildMatch = false;
  129. else if (streq(arg, "-a") || streq(arg, "--all"))
  130. includeAll = true;
  131. else if (streq(arg, "-l") || streq(arg, "--list"))
  132. list = true;
  133. else if (streq(arg, "-d") || streq(arg, "--load"))
  134. {
  135. useDefaultLocations = false;
  136. argNo++;
  137. if (argNo<argc)
  138. loadLocations.append(argv[argNo]);
  139. }
  140. else
  141. {
  142. usage();
  143. exit(streq(arg, "-h") || streq(arg, "--help")?0:4);
  144. }
  145. }
  146. else
  147. {
  148. VStringBuffer pattern("*%s*", arg);
  149. if (wildMatch && !strchr(arg, '*'))
  150. arg = pattern.str();
  151. if (exclude)
  152. excludeNames.append(arg);
  153. else
  154. includeNames.append(arg);
  155. }
  156. }
  157. if (verbose)
  158. queryStderrLogMsgHandler()->setMessageFields(MSGFIELD_time);
  159. else
  160. removeLog();
  161. if (!includeAll && includeNames.empty())
  162. {
  163. excludeNames.append("*stress*");
  164. excludeNames.append("*timing*");
  165. excludeNames.append("*slow*");
  166. }
  167. if (!includeNames.length())
  168. includeNames.append("*");
  169. if (useDefaultLocations)
  170. {
  171. StringBuffer binDir;
  172. makeAbsolutePath(argv[0], binDir, true);
  173. // Default library location depends on the executable location...
  174. StringBuffer dir;
  175. splitFilename(binDir.str(), &dir, &dir, NULL, NULL);
  176. dir.replaceString(PATHSEPSTR "bin" PATHSEPSTR, PATHSEPSTR "lib" PATHSEPSTR);
  177. if (verbose)
  178. DBGLOG("Adding default library location %s", dir.str());
  179. loadLocations.append(dir);
  180. #ifdef _DEBUG
  181. dir.replaceString(PATHSEPSTR "lib" PATHSEPSTR, PATHSEPSTR "libs" PATHSEPSTR);
  182. loadLocations.append(dir);
  183. if (verbose)
  184. DBGLOG("Adding default library location %s", dir.str());
  185. #endif
  186. }
  187. IArray objects;
  188. ForEachItemIn(idx, loadLocations)
  189. {
  190. const char *location = loadLocations.item(idx);
  191. Owned<IFile> file = createIFile(location);
  192. switch (file->isDirectory())
  193. {
  194. case notFound:
  195. if (verbose && !useDefaultLocations)
  196. DBGLOG("Specified library location %s not found", location);
  197. break;
  198. case foundYes:
  199. loadDlls(objects, location);
  200. break;
  201. case foundNo:
  202. LoadedObject *loaded = loadDll(location);
  203. if (loaded)
  204. objects.append(*loaded);
  205. break;
  206. }
  207. }
  208. bool wasSuccessful = false;
  209. {
  210. // New scope as we need the TestRunner to be destroyed before unloading the dlls...
  211. CppUnit::TestFactoryRegistry &registry = CppUnit::TestFactoryRegistry::getRegistry();
  212. CppUnit::TextUi::TestRunner runner;
  213. CppUnit::Test *all = registry.makeTest();
  214. int numTests = all->getChildTestCount();
  215. for (int i = 0; i < numTests; i++)
  216. {
  217. CppUnit::Test *sub = all->getChildTestAt(i);
  218. std::string name = sub->getName();
  219. if (matchName(name.c_str(), includeNames))
  220. {
  221. if (matchName(name.c_str(), excludeNames))
  222. {
  223. if (verbose)
  224. DBGLOG("Excluding test %s", name.c_str());
  225. }
  226. else if (list)
  227. printf("%s\n", name.c_str());
  228. else
  229. {
  230. if (verbose)
  231. DBGLOG("Including test %s", name.c_str());
  232. runner.addTest(sub);
  233. }
  234. }
  235. }
  236. wasSuccessful = list || runner.run( "", false );
  237. }
  238. releaseAtoms();
  239. ClearTypeCache(); // Clear this cache before the file hooks are unloaded
  240. removeFileHooks();
  241. objects.kill();
  242. ExitModuleObjects();
  243. return wasSuccessful;
  244. }
  245. //MORE: This can't be included in jlib because of the dll dependency
  246. class InternalStatisticsTest : public CppUnit::TestFixture
  247. {
  248. CPPUNIT_TEST_SUITE( InternalStatisticsTest );
  249. CPPUNIT_TEST(testMappings);
  250. CPPUNIT_TEST_SUITE_END();
  251. void testMappings()
  252. {
  253. try
  254. {
  255. verifyStatisticFunctions();
  256. }
  257. catch (IException * e)
  258. {
  259. StringBuffer msg;
  260. fprintf(stderr, "Failure: %s", e->errorMessage(msg).str());
  261. e->Release();
  262. ASSERT(false);
  263. }
  264. }
  265. };
  266. CPPUNIT_TEST_SUITE_REGISTRATION( InternalStatisticsTest );
  267. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( InternalStatisticsTest, "StatisticsTest" );
  268. class PtreeThreadingStressTest : public CppUnit::TestFixture
  269. {
  270. CPPUNIT_TEST_SUITE( PtreeThreadingStressTest );
  271. CPPUNIT_TEST(testContention);
  272. CPPUNIT_TEST_SUITE_END();
  273. void testContention()
  274. {
  275. _testContention(ipt_lowmem);
  276. _testContention(ipt_fast);
  277. }
  278. void _testContention(byte flags)
  279. {
  280. enum ContentionMode { max_contention, some_contention, min_contention, some_control, min_control };
  281. class casyncfor: public CAsyncFor
  282. {
  283. volatile int v = 0;
  284. void donothing()
  285. {
  286. v++;
  287. }
  288. byte flags = ipt_none;
  289. ContentionMode mode = max_contention;
  290. int iterations = 0;
  291. const char *desc = nullptr;
  292. public:
  293. casyncfor(const char *_desc, byte _flags, ContentionMode _mode, int _iter)
  294. : flags(_flags), mode(_mode), iterations(_iter), desc(_desc)
  295. {
  296. };
  297. double For(unsigned num, unsigned maxatonce, double overhead = 0.0)
  298. {
  299. unsigned start = msTick();
  300. CAsyncFor::For(num, maxatonce);
  301. unsigned elapsed = msTick()-start;
  302. double looptime = (elapsed * 1.0) / (iterations*num);
  303. if (mode < 3)
  304. DBGLOG("%s (%s) test completed in %u ms (%f ms/iter)", desc, flags & ipt_fast ? "fast" : "lowmem", elapsed, looptime-overhead);
  305. return looptime;
  306. }
  307. void Do(unsigned i)
  308. {
  309. for (unsigned i = 0; i < iterations; i++)
  310. {
  311. Owned<IPropertyTree> p = mode >= some_control ? nullptr : createPTreeFromXMLString(
  312. "<W_LOCAL buildVersion='community_6.0.0-trunk0Debug[heads/cass-wu-part3-0-g10b954-dirty]'"
  313. " cloneable='1'"
  314. " clusterName=''"
  315. " codeVersion='158'"
  316. " eclVersion='6.0.0'"
  317. " hash='2796091347'"
  318. " state='completed'"
  319. " xmlns:xsi='http://www.w3.org/1999/XMLSchema-instance'>"
  320. " <Debug>"
  321. " <debugquery>1</debugquery>"
  322. " <expandpersistinputdependencies>1</expandpersistinputdependencies>"
  323. " <savecpptempfiles>1</savecpptempfiles>"
  324. " <saveecltempfiles>1</saveecltempfiles>"
  325. " <spanmultiplecpp>0</spanmultiplecpp>"
  326. " <standaloneexe>1</standaloneexe>"
  327. " <targetclustertype>hthor</targetclustertype>"
  328. " </Debug>"
  329. " <FilesRead>"
  330. " <File name='myfile' useCount='2' cluster = 'mycluster'/>"
  331. " <File name='mysuperfile' useCount='2' cluster = 'mycluster'>"
  332. " <Subfile name='myfile'/>"
  333. " </File>"
  334. "</FilesRead>"
  335. " <Graphs>"
  336. " <Graph name='graph1' type='activities'>"
  337. " <xgmml>"
  338. " <graph wfid='2'>"
  339. " <node id='1'>"
  340. " <att>"
  341. " <graph>"
  342. " <att name='rootGraph' value='1'/>"
  343. " <edge id='2_0' source='2' target='3'/>"
  344. " <edge id='3_0' source='3' target='4'/>"
  345. " <edge id='4_0' source='4' target='5'/>"
  346. " <node id='2' label='Inline Row&#10;{1}'>"
  347. " <att name='definition' value='./sets.ecl(2,13)'/>"
  348. " <att name='_kind' value='148'/>"
  349. " <att name='ecl' value='ROW(TRANSFORM({ integer8 v },SELF.v := 1;));&#10;'/>"
  350. " <att name='recordSize' value='8'/>"
  351. " <att name='predictedCount' value='1'/>"
  352. " </node>"
  353. " <node id='3' label='Filter'>"
  354. " <att name='definition' value='./sets.ecl(3,15)'/>"
  355. " <att name='_kind' value='5'/>"
  356. " <att name='ecl' value='FILTER(v = STORED(&apos;one&apos;));&#10;'/>"
  357. " <att name='recordSize' value='8'/>"
  358. " <att name='predictedCount' value='0..?[disk]'/>"
  359. " </node>"
  360. " <node id='4' label='Count'>"
  361. " <att name='_kind' value='125'/>"
  362. " <att name='ecl' value='TABLE({ integer8 value := COUNT(group) });&#10;'/>"
  363. " <att name='recordSize' value='8'/>"
  364. " <att name='predictedCount' value='1'/>"
  365. " </node>"
  366. " <node id='5' label='Store&#10;Internal(&apos;wf2&apos;)'>"
  367. " <att name='_kind' value='22'/>"
  368. " <att name='ecl' value='extractresult(value, named(&apos;wf2&apos;));&#10;'/>"
  369. " <att name='recordSize' value='8'/>"
  370. " </node>"
  371. " </graph>"
  372. " </att>"
  373. " </node>"
  374. " </graph>"
  375. " </xgmml>"
  376. " </Graph>"
  377. " <Graph name='graph2' type='activities'>"
  378. " <xgmml>"
  379. " <graph wfid='3'>"
  380. " <node id='6'>"
  381. " <att>"
  382. " <graph>"
  383. " <att name='rootGraph' value='1'/>"
  384. " <edge id='7_0' source='7' target='8'/>"
  385. " <edge id='8_0' source='8' target='9'/>"
  386. " <node id='7' label='Inline Row&#10;{1}'>"
  387. " <att name='definition' value='./sets.ecl(2,13)'/>"
  388. " <att name='_kind' value='148'/>"
  389. " <att name='ecl' value='ROW(TRANSFORM({ integer8 v },SELF.v := 1;));&#10;'/>"
  390. " <att name='recordSize' value='8'/>"
  391. " <att name='predictedCount' value='1'/>"
  392. " </node>"
  393. " <node id='8' label='Filter'>"
  394. " <att name='definition' value='./sets.ecl(5,1)'/>"
  395. " <att name='_kind' value='5'/>"
  396. " <att name='ecl' value='FILTER(v = INTERNAL(&apos;wf2&apos;));&#10;'/>"
  397. " <att name='recordSize' value='8'/>"
  398. " <att name='predictedCount' value='0..?[disk]'/>"
  399. " </node>"
  400. " <node id='9' label='Output&#10;Result #1'>"
  401. " <att name='definition' value='./sets.ecl(1,1)'/>"
  402. " <att name='name' value='sets'/>"
  403. " <att name='definition' value='./sets.ecl(5,1)'/>"
  404. " <att name='_kind' value='16'/>"
  405. " <att name='ecl' value='OUTPUT(..., workunit);&#10;'/>"
  406. " <att name='recordSize' value='8'/>"
  407. " </node>"
  408. " </graph>"
  409. " </att>"
  410. " </node>"
  411. " </graph>"
  412. " </xgmml>"
  413. " </Graph>"
  414. " </Graphs>"
  415. " <Query fetchEntire='1'>"
  416. " <Associated>"
  417. " <File desc='a.out.cpp'"
  418. " filename='/Users/rchapman/HPCC-Platform/ossd/a.out.cpp'"
  419. " ip='192.168.2.203'"
  420. " type='cpp'/>"
  421. " </Associated>"
  422. " </Query>"
  423. " <Results>"
  424. " <Result isScalar='0'"
  425. " name='Result 1'"
  426. " recordSizeEntry='mf1'"
  427. " rowLimit='-1'"
  428. " sequence='0'"
  429. " status='calculated'>"
  430. " <rowCount>1</rowCount>"
  431. " <SchemaRaw xsi:type='SOAP-ENC:base64'>"
  432. " dgABCAEAGBAAAAB7IGludGVnZXI4IHYgfTsK </SchemaRaw>"
  433. " <totalRowCount>1</totalRowCount>"
  434. " <Value xsi:type='SOAP-ENC:base64'>"
  435. " AQAAAAAAAAA= </Value>"
  436. " </Result>"
  437. " </Results>"
  438. " <State>completed</State>"
  439. " <Statistics>"
  440. " <Statistic c='eclcc'"
  441. " count='1'"
  442. " creator='eclcc'"
  443. " kind='TimeElapsed'"
  444. " s='compile'"
  445. " scope='compile:parseTime'"
  446. " ts='1431603789722535'"
  447. " unit='ns'"
  448. " value='805622'/>"
  449. " <Statistic c='unknown'"
  450. " count='1'"
  451. " creator='unknownRichards-iMac.local'"
  452. " kind='WhenQueryStarted'"
  453. " s='global'"
  454. " scope='workunit'"
  455. " ts='1431603790007020'"
  456. " unit='ts'"
  457. " value='1431603790007001'/>"
  458. " <Statistic c='unknown'"
  459. " count='1'"
  460. " creator='unknownRichards-iMac.local'"
  461. " desc='Graph graph1'"
  462. " kind='TimeElapsed'"
  463. " s='graph'"
  464. " scope='graph1'"
  465. " ts='1431603790007912'"
  466. " unit='ns'"
  467. " value='0'/>"
  468. " </Statistics>"
  469. " <Temporaries>"
  470. " <Variable name='wf2' status='calculated'>"
  471. " <rowCount>1</rowCount>"
  472. " <totalRowCount>1</totalRowCount>"
  473. " <Value xsi:type='SOAP-ENC:base64'>"
  474. " AQAAAAAAAAA= </Value>"
  475. " </Variable>"
  476. " </Temporaries>"
  477. " <Tracing>"
  478. " <EclAgentBuild>community_6.0.0-trunk0Debug[heads/cass-wu-part3-0-g10b954-dirty]</EclAgentBuild>"
  479. " </Tracing>"
  480. " <Variables>"
  481. " <Variable name='one' sequence='-1' status='calculated'>"
  482. " <rowCount>1</rowCount>"
  483. " <SchemaRaw xsi:type='SOAP-ENC:base64'>"
  484. " b25lAAEIAQAYAAAAAA== </SchemaRaw>"
  485. " <totalRowCount>1</totalRowCount>"
  486. " <Value xsi:type='SOAP-ENC:base64'>"
  487. " AQAAAAAAAAA= </Value>"
  488. " </Variable>"
  489. " </Variables>"
  490. " <Workflow>"
  491. " <Item mode='normal'"
  492. " state='done'"
  493. " type='normal'"
  494. " wfid='1'/>"
  495. " <Item mode='normal'"
  496. " state='done'"
  497. " type='normal'"
  498. " wfid='2'>"
  499. " <Dependency wfid='1'/>"
  500. " </Item>"
  501. " <Item mode='normal'"
  502. " state='done'"
  503. " type='normal'"
  504. " wfid='3'>"
  505. " <Dependency wfid='2'/>"
  506. " <Schedule/>"
  507. " </Item>"
  508. " </Workflow>"
  509. "</W_LOCAL>"
  510. , flags);
  511. switch(mode)
  512. {
  513. case some_contention: case some_control: for (int j = 0; j < 100000; j++) donothing(); break;
  514. case min_contention: case min_control: for (int j = 0; j < 1000000; j++) donothing(); break;
  515. }
  516. }
  517. }
  518. } max("maxContention",flags,max_contention,1000),
  519. some("someContention",flags,some_contention,200),
  520. min("minContention",flags,min_contention,200),
  521. csome("control some",flags,some_control,200),
  522. cmin("control min",flags,min_control,200),
  523. seq("single",flags,max_contention,1000);
  524. max.For(8,8);
  525. some.For(8,8,csome.For(8,8));
  526. min.For(8,8,cmin.For(8,8));
  527. seq.For(8,1);
  528. }
  529. };
  530. CPPUNIT_TEST_SUITE_REGISTRATION( PtreeThreadingStressTest );
  531. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( PtreeThreadingStressTest, "PtreeThreadingStressTest" );
  532. //MORE: This can't be included in jlib because of the dll dependency
  533. class StringBufferTest : public CppUnit::TestFixture
  534. {
  535. CPPUNIT_TEST_SUITE( StringBufferTest );
  536. CPPUNIT_TEST(testReplace);
  537. CPPUNIT_TEST_SUITE_END();
  538. void testReplace()
  539. {
  540. StringBuffer r ("1 bb c");
  541. r.replaceString(" ", "x");
  542. ASSERT(streq(r, "1xbbxc"));
  543. }
  544. };
  545. CPPUNIT_TEST_SUITE_REGISTRATION( StringBufferTest );
  546. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( StringBufferTest, "StringBufferTest" );
  547. StringBuffer &mbToBase58(StringBuffer &s, const MemoryBuffer &data)
  548. {
  549. size_t b58Length = data.length() * 2 + 1;
  550. ASSERT(b58enc(s.clear().reserve(b58Length), &b58Length, data.toByteArray(), data.length()));
  551. s.setLength(b58Length);
  552. return s;
  553. }
  554. StringBuffer &base64ToBase58(StringBuffer &s, const char *b64)
  555. {
  556. MemoryBuffer mb;
  557. JBASE64_Decode(b64, mb);
  558. return mbToBase58(s, mb);
  559. }
  560. StringBuffer &textToBase58(StringBuffer &s, const char *text)
  561. {
  562. MemoryBuffer mb;
  563. mb.append((size_t)strlen(text), text);
  564. return mbToBase58(s, mb);
  565. }
  566. MemoryBuffer &base58ToMb(MemoryBuffer &data, const char *b58)
  567. {
  568. size_t len = strlen(b58);
  569. size_t offset = len;
  570. b58tobin(data.clear().reserveTruncate(len), &len, b58, 0);
  571. offset -= len;
  572. if (offset) //if we ever start using b58tobin we should fix this weird behavior
  573. {
  574. MemoryBuffer weird;
  575. weird.append(len, data.toByteArray()+offset);
  576. data.swapWith(weird);
  577. }
  578. return data;
  579. }
  580. StringBuffer &base58ToBase64(StringBuffer &s, const char *b58)
  581. {
  582. MemoryBuffer mb;
  583. base58ToMb(mb, b58);
  584. JBASE64_Encode(mb.toByteArray(), mb.length(), s.clear(),true);
  585. return s;
  586. }
  587. StringBuffer &base58ToText(StringBuffer &s, const char *b58)
  588. {
  589. MemoryBuffer mb;
  590. base58ToMb(mb, b58);
  591. return s.clear().append(mb.length(), mb.toByteArray());
  592. }
  593. class Base58Test : public CppUnit::TestFixture
  594. {
  595. CPPUNIT_TEST_SUITE( Base58Test );
  596. CPPUNIT_TEST(testEncodeDecode);
  597. CPPUNIT_TEST_SUITE_END();
  598. void doTestEncodeDecodeText(const char *text, const char *b58)
  599. {
  600. StringBuffer s;
  601. ASSERT(streq(textToBase58(s, text), b58));
  602. ASSERT(streq(base58ToText(s, b58), text));
  603. }
  604. void doTestEncodeDecodeBase64(const char *b64, const char *b58)
  605. {
  606. StringBuffer s;
  607. ASSERT(streq(base64ToBase58(s, b64), b58));
  608. ASSERT(streq(base58ToBase64(s, b58), b64));
  609. }
  610. void testEncodeDecode()
  611. {
  612. StringBuffer s;
  613. //short string
  614. doTestEncodeDecodeText("1", "r");
  615. //text string
  616. doTestEncodeDecodeText("Fifty-eight is the sum of the first seven prime numbers.", "2ubdTkzo5vaWL4FKQGro88zp8v6Q5EftVBq2fbZsWCDRzQxGDb1heKFsMReJNhsRsK6TfvrgqVeRB");
  617. //hex 005A1FC5DD9E6F03819FCA94A2D89669469667F9A074655946
  618. doTestEncodeDecodeBase64("AFofxd2ebwOBn8qUotiWaUaWZ/mgdGVZRg==", "19DXstMaV43WpYg4ceREiiTv2UntmoiA9j");
  619. //hex FEEFAEF022FA
  620. doTestEncodeDecodeBase64("/u+u8CL6", "3Bx9Y4pUR");
  621. //hex FFFEEFAEF022FA
  622. doTestEncodeDecodeBase64("//7vrvAi+g==", "AhfV5sjWb3");
  623. //This input causes the loop iteration counter to go negative
  624. //hex 00CEF022FA
  625. doTestEncodeDecodeBase64("AM7wIvo=", "16Ho7Hs");
  626. //empty input
  627. MemoryBuffer mb;
  628. ASSERT(streq(mbToBase58(s, mb), ""));
  629. }
  630. };
  631. CPPUNIT_TEST_SUITE_REGISTRATION( Base58Test );
  632. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( Base58Test, "Base58Test" );
  633. thread_local unsigned temp = 0; // Avoids clever compilers optimizing everything away
  634. static unsigned skip(unsigned j)
  635. {
  636. temp += j;
  637. return j+1;
  638. }
  639. static unsigned call_from_thread(unsigned count)
  640. {
  641. unsigned tot = count;
  642. for (int j = 0; j < count; j++)
  643. tot += skip(j);
  644. return tot;
  645. }
  646. class ThreadedPersistStressTest : public CppUnit::TestFixture
  647. {
  648. CPPUNIT_TEST_SUITE( ThreadedPersistStressTest );
  649. CPPUNIT_TEST(testThreads);
  650. CPPUNIT_TEST_SUITE_END();
  651. void testThreads()
  652. {
  653. testThreadsX(0);
  654. testThreadsX(1);
  655. testThreadsX(2);
  656. testThreadsX(3);
  657. testThreadsX(4);
  658. }
  659. void testThreadsX(unsigned mode)
  660. {
  661. unsigned iters = 10000;
  662. testThreadsXX(mode, 10, iters);
  663. testThreadsXX(mode, 1000, iters);
  664. testThreadsXX(mode, 2000, iters);
  665. testThreadsXX(mode, 4000, iters);
  666. testThreadsXX(mode, 8000, iters);
  667. testThreadsXX(mode, 16000, iters);
  668. testThreadsXX(mode, 32000, iters);
  669. testThreadsXX(mode, 64000, iters);
  670. }
  671. void testThreadsXX(unsigned mode, unsigned count, unsigned iters)
  672. {
  673. unsigned start = msTick();
  674. class Thread : public IThreaded
  675. {
  676. public:
  677. Thread(unsigned _count) : count(_count) {}
  678. virtual void threadmain() override
  679. {
  680. ret = call_from_thread(count);
  681. }
  682. unsigned count;
  683. unsigned ret = 0;
  684. } t1(count), t2(count), t3(count);
  685. switch (mode)
  686. {
  687. case 0:
  688. {
  689. unsigned ret = 0;
  690. CThreadedPersistent thread1("1", &t1), thread2("2", &t2), thread3("3", &t3);
  691. for (unsigned i = 0; i < iters; i++)
  692. {
  693. thread1.start();
  694. thread2.start();
  695. thread3.start();
  696. ret = call_from_thread(count);
  697. thread1.join(INFINITE);
  698. thread2.join(INFINITE);
  699. thread3.join(INFINITE);
  700. }
  701. ret += t1.ret + t2.ret + t3.ret;
  702. DBGLOG("ThreadedPersistant %d , %d, %d", count, msTick() - start, ret);
  703. break;
  704. }
  705. case 1:
  706. {
  707. unsigned ret = 0;
  708. for (unsigned i = 0; i < iters; i++)
  709. {
  710. t1.threadmain();
  711. t2.threadmain();
  712. t3.threadmain();
  713. ret = call_from_thread(count);
  714. }
  715. ret += t1.ret + t2.ret + t3.ret;
  716. DBGLOG("Sequential %d , %d, %d", count, msTick() - start, ret);
  717. break;
  718. }
  719. case 2:
  720. {
  721. unsigned ret = 0;
  722. CThreaded tthread1("1", &t1), tthread2("2", &t2), tthread3("3", &t3);
  723. for (unsigned i = 0; i < iters; i++)
  724. {
  725. tthread1.start();
  726. tthread2.start();
  727. tthread3.start();
  728. ret = call_from_thread(count);
  729. tthread1.join();
  730. tthread2.join();
  731. tthread3.join();
  732. }
  733. ret += t1.ret + t2.ret + t3.ret;
  734. DBGLOG("CThreaded %d , %d, %d", count, msTick() - start, ret);
  735. break;
  736. }
  737. case 3:
  738. {
  739. unsigned ret = 0;
  740. for (unsigned i = 0; i < iters; i++)
  741. {
  742. class casyncfor: public CAsyncFor
  743. {
  744. public:
  745. casyncfor(unsigned _count) :count(_count), ret(0) {}
  746. void Do(unsigned i)
  747. {
  748. ret += call_from_thread(count);
  749. }
  750. unsigned count;
  751. unsigned ret;
  752. } afor(count);
  753. afor.For(4, 4);
  754. ret = afor.ret;
  755. }
  756. DBGLOG("AsyncFor %d , %d, %d", count, msTick() - start, ret);
  757. break;
  758. }
  759. case 4:
  760. {
  761. CPersistentTask task1("1", &t1), task2("2", &t2), task3("3", &t3);
  762. unsigned ret = 0;
  763. for (unsigned i = 0; i < iters; i++)
  764. {
  765. task1.start();
  766. task2.start();
  767. task3.start();
  768. ret = call_from_thread(count);
  769. task1.join(INFINITE);
  770. task2.join(INFINITE);
  771. task3.join(INFINITE);
  772. }
  773. ret += t1.ret + t2.ret + t3.ret;
  774. DBGLOG("PersistantTask %d , %d, %d", count, msTick() - start, ret);
  775. break;
  776. }
  777. }
  778. }
  779. };
  780. CPPUNIT_TEST_SUITE_REGISTRATION( ThreadedPersistStressTest );
  781. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( ThreadedPersistStressTest, "ThreadedPersistStressTest" );
  782. #ifndef _WIN32
  783. class PipeRunTest : public CppUnit::TestFixture
  784. {
  785. CPPUNIT_TEST_SUITE( PipeRunTest );
  786. CPPUNIT_TEST(testRun);
  787. CPPUNIT_TEST_SUITE_END();
  788. void testRun()
  789. {
  790. Owned<IPipeProcess> pipe = createPipeProcess();
  791. setenv("OLDVAR", "old", 1);
  792. setenv("TESTVAR", "oldtest", 1);
  793. pipe->setenv("TESTVAR", "well");
  794. pipe->setenv("TESTVAR", "hello");
  795. pipe->setenv("AX", "ax");
  796. pipe->setenv("BCD", "bcd");
  797. pipe->setenv("ABCD", "abcd");
  798. ASSERT(pipe->run("/bin/bash", "/bin/bash -c 'echo $TESTVAR $OLDVAR $AX $BCD $ABCD'", ".", false, true, false));
  799. byte buf[4096];
  800. size32_t read = pipe->read(sizeof(buf),buf);
  801. ASSERT(read==22);
  802. ASSERT(memcmp(buf, "hello old ax bcd abcd\n", 22)==0);
  803. ASSERT(pipe->wait()==0);
  804. }
  805. };
  806. CPPUNIT_TEST_SUITE_REGISTRATION( PipeRunTest );
  807. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( PipeRunTest, "PipeRunTest" );
  808. #endif
  809. #endif // _USE_CPPUNIT