unittests.cpp 27 KB

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