jlibtests.cpp 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288
  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. /*
  14. * Jlib regression tests
  15. *
  16. */
  17. #ifdef _USE_CPPUNIT
  18. #include <memory>
  19. #include "jsem.hpp"
  20. #include "jfile.hpp"
  21. #include "jdebug.hpp"
  22. #include "jset.hpp"
  23. #include "rmtfile.hpp"
  24. #include "jqueue.hpp"
  25. #include "jregexp.hpp"
  26. #include "unittests.hpp"
  27. static const unsigned oneMinute = 60000; // msec
  28. class JlibSemTest : public CppUnit::TestFixture
  29. {
  30. public:
  31. CPPUNIT_TEST_SUITE(JlibSemTest);
  32. CPPUNIT_TEST(testSimple);
  33. CPPUNIT_TEST_SUITE_END();
  34. protected:
  35. void testTimedAvailable(Semaphore & sem)
  36. {
  37. //Shouldn't cause a reschedule, definitely shouldn't wait for 100s
  38. if(!sem.wait(100))
  39. ASSERT(false);
  40. }
  41. void testTimedElapsed(Semaphore & sem, unsigned time)
  42. {
  43. unsigned now = msTick();
  44. sem.wait(time);
  45. unsigned taken = msTick() - now;
  46. VStringBuffer errMsg("values: time: %u, taken: %u", time, taken);
  47. CPPUNIT_ASSERT_MESSAGE(errMsg.str(), taken >= time && taken < time + oneMinute);
  48. PROGLOG("%s", errMsg.str());
  49. }
  50. void testSimple()
  51. {
  52. //Some very basic semaphore tests.
  53. Semaphore sem;
  54. sem.signal();
  55. sem.wait();
  56. testTimedElapsed(sem, 100);
  57. sem.signal();
  58. testTimedAvailable(sem);
  59. sem.reinit(2);
  60. sem.wait();
  61. testTimedAvailable(sem);
  62. testTimedElapsed(sem, 5);
  63. }
  64. };
  65. CPPUNIT_TEST_SUITE_REGISTRATION( JlibSemTest );
  66. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( JlibSemTest, "JlibSemTest" );
  67. class JlibSemTestStress : public CppUnit::TestFixture
  68. {
  69. public:
  70. CPPUNIT_TEST_SUITE(JlibSemTestStress);
  71. CPPUNIT_TEST(testSimple);
  72. CPPUNIT_TEST_SUITE_END();
  73. protected:
  74. void testTimedElapsed(Semaphore & sem, unsigned time, unsigned loopCount)
  75. {
  76. unsigned __int64 sumTaken = 0;
  77. unsigned maxTaken = 0;
  78. unsigned timeLimit = time + oneMinute;
  79. unsigned numberOfOut = 0;
  80. bool isSignaled = false;
  81. PROGLOG("Start loop");
  82. for (int i = 0 ; i <= loopCount; i++)
  83. {
  84. unsigned now = msTick();
  85. if (sem.wait(time))
  86. {
  87. isSignaled = true;
  88. break;
  89. }
  90. unsigned taken = msTick() - now;
  91. sumTaken += taken;
  92. maxTaken = (taken > maxTaken ? taken : maxTaken);
  93. numberOfOut += (taken > timeLimit ? 1 : 0);
  94. }
  95. VStringBuffer errMsg("values: time: %d, loop: %d, sum taken: %llu, average taken: %llu, max taken: %d, out of limit: %d times, signaled: %s",
  96. time, loopCount, sumTaken, sumTaken/loopCount, maxTaken, numberOfOut, (isSignaled ? "yes" : "no"));
  97. CPPUNIT_ASSERT_MESSAGE(errMsg.str(), 0 == numberOfOut && !isSignaled );
  98. PROGLOG("%s", errMsg.str());
  99. }
  100. void testSimple()
  101. {
  102. //Very basic semaphore stress tests.
  103. Semaphore sem;
  104. sem.signal();
  105. if (!sem.wait(1000))
  106. {
  107. VStringBuffer errMsg("Semaphore stalled (%s:%d)", sanitizeSourceFile(__FILE__), __LINE__);
  108. CPPUNIT_FAIL(errMsg.str());
  109. }
  110. testTimedElapsed(sem, 5, 1000);
  111. }
  112. };
  113. CPPUNIT_TEST_SUITE_REGISTRATION( JlibSemTestStress );
  114. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( JlibSemTestStress, "JlibSemTestStress" );
  115. /* =========================================================== */
  116. class JlibSetTest : public CppUnit::TestFixture
  117. {
  118. protected:
  119. void testBitsetHelpers()
  120. {
  121. CPPUNIT_ASSERT_EQUAL(0U, countTrailingUnsetBits(1U));
  122. CPPUNIT_ASSERT_EQUAL(31U, countLeadingUnsetBits(1U));
  123. CPPUNIT_ASSERT_EQUAL(1U, getMostSignificantBit(1U));
  124. CPPUNIT_ASSERT_EQUAL(4U, countTrailingUnsetBits(0x110U));
  125. CPPUNIT_ASSERT_EQUAL(23U, countLeadingUnsetBits(0x110U));
  126. CPPUNIT_ASSERT_EQUAL(9U, getMostSignificantBit(0x110U));
  127. CPPUNIT_ASSERT_EQUAL(0U, countTrailingUnsetBits(0xFFFFFFFFU));
  128. CPPUNIT_ASSERT_EQUAL(0U, countLeadingUnsetBits(0xFFFFFFFFU));
  129. CPPUNIT_ASSERT_EQUAL(32U, getMostSignificantBit(0xFFFFFFFFU));
  130. CPPUNIT_ASSERT_EQUAL(52U, countTrailingUnsetBits(I64C(0x1010000000000000U)));
  131. }
  132. void testSet1(bool initial, IBitSet *bs, unsigned start, unsigned numBits, bool setValue, bool clearValue)
  133. {
  134. unsigned end = start+numBits;
  135. if (initial)
  136. bs->incl(start, end-1);
  137. for (unsigned i=start; i < end; i++)
  138. {
  139. ASSERT(bs->test(i) == clearValue);
  140. bs->set(i, setValue);
  141. ASSERT(bs->test(i) == setValue);
  142. bs->set(i+5, setValue);
  143. ASSERT(bs->scan(0, setValue) == i);
  144. ASSERT(bs->scan(i+1, setValue) == i+5);
  145. bs->set(i, clearValue);
  146. bs->set(i+5, clearValue);
  147. //Clearing i+5 above may extend the set - so need to calculate the end carefully
  148. unsigned last = i+5 < end ? end : i + 6;
  149. unsigned match1 = bs->scan(0, setValue);
  150. CPPUNIT_ASSERT_EQUAL((unsigned)(initial ? last : -1), match1);
  151. bs->invert(i);
  152. ASSERT(bs->test(i) == setValue);
  153. bs->invert(i);
  154. ASSERT(bs->test(i) == clearValue);
  155. bool wasSet = bs->testSet(i, setValue);
  156. ASSERT(wasSet == clearValue);
  157. bool wasSet2 = bs->testSet(i, clearValue);
  158. ASSERT(wasSet2 == setValue);
  159. ASSERT(bs->test(i) == clearValue);
  160. bs->set(i, setValue);
  161. unsigned match = bs->scanInvert(0, setValue);
  162. ASSERT(match == i);
  163. ASSERT(bs->test(i) == clearValue);
  164. }
  165. bs->reset();
  166. if (initial)
  167. {
  168. bs->incl(start, end);
  169. bs->excl(start+5, end-5);
  170. }
  171. else
  172. bs->incl(start+5, end-5);
  173. unsigned inclStart = bs->scan(start, setValue);
  174. ASSERT((start+5) == inclStart);
  175. unsigned inclEnd = bs->scan(start+5, clearValue);
  176. ASSERT((end-5) == (inclEnd-1));
  177. }
  178. void testSet(bool initial, unsigned passes, bool timed)
  179. {
  180. unsigned now = msTick();
  181. bool setValue = !initial;
  182. bool clearValue = initial;
  183. const unsigned numBits = 400;
  184. for (unsigned pass=0; pass < passes; pass++)
  185. {
  186. Owned<IBitSet> bs = createThreadSafeBitSet();
  187. testSet1(initial, bs, 0, numBits, setValue, clearValue);
  188. }
  189. if (timed)
  190. {
  191. unsigned elapsed = msTick()-now;
  192. DBGLOG("Bit test (%u) %d passes time taken = %dms", initial, passes, elapsed);
  193. }
  194. now = msTick();
  195. for (unsigned pass=0; pass < passes; pass++)
  196. {
  197. Owned<IBitSet> bs = createBitSet();
  198. testSet1(initial, bs, 0, numBits, setValue, clearValue);
  199. }
  200. if (timed)
  201. {
  202. unsigned elapsed = msTick()-now;
  203. DBGLOG("Bit test [thread-unsafe version] (%u) %d passes time taken = %dms", initial, passes, elapsed);
  204. }
  205. now = msTick();
  206. size32_t bitSetMemSz = getBitSetMemoryRequirement(numBits+5);
  207. MemoryBuffer mb;
  208. void *mem = mb.reserveTruncate(bitSetMemSz);
  209. for (unsigned pass=0; pass < passes; pass++)
  210. {
  211. Owned<IBitSet> bs = createBitSet(bitSetMemSz, mem);
  212. testSet1(initial, bs, 0, numBits, setValue, clearValue);
  213. }
  214. if (timed)
  215. {
  216. unsigned elapsed = msTick()-now;
  217. DBGLOG("Bit test [thread-unsafe version, fixed memory] (%u) %d passes time taken = %dms\n", initial, passes, elapsed);
  218. }
  219. }
  220. };
  221. class JlibSetTestQuick : public JlibSetTest
  222. {
  223. public:
  224. CPPUNIT_TEST_SUITE(JlibSetTestQuick);
  225. CPPUNIT_TEST(testBitsetHelpers);
  226. CPPUNIT_TEST(testSimple);
  227. CPPUNIT_TEST_SUITE_END();
  228. void testSimple()
  229. {
  230. testSet(false, 100, false);
  231. testSet(true, 100, false);
  232. }
  233. };
  234. class JlibSetTestStress : public JlibSetTest
  235. {
  236. public:
  237. CPPUNIT_TEST_SUITE(JlibSetTestStress);
  238. CPPUNIT_TEST(testParallel);
  239. CPPUNIT_TEST(testSimple);
  240. CPPUNIT_TEST_SUITE_END();
  241. void testSimple()
  242. {
  243. testSet(false, 10000, true);
  244. testSet(true, 10000, true);
  245. }
  246. protected:
  247. class CBitThread : public CSimpleInterfaceOf<IInterface>, implements IThreaded
  248. {
  249. IBitSet &bitSet;
  250. unsigned startBit, numBits;
  251. bool initial, setValue, clearValue;
  252. CThreaded threaded;
  253. Owned<IException> exception;
  254. CppUnit::Exception *cppunitException;
  255. public:
  256. CBitThread(IBitSet &_bitSet, unsigned _startBit, unsigned _numBits, bool _initial)
  257. : threaded("CBitThread", this), bitSet(_bitSet), startBit(_startBit), numBits(_numBits), initial(_initial)
  258. {
  259. cppunitException = NULL;
  260. setValue = !initial;
  261. clearValue = initial;
  262. }
  263. void start() { threaded.start(); }
  264. void join()
  265. {
  266. threaded.join();
  267. if (exception)
  268. throw exception.getClear();
  269. else if (cppunitException)
  270. throw cppunitException;
  271. }
  272. virtual void threadmain() override
  273. {
  274. try
  275. {
  276. unsigned endBit = startBit+numBits-1;
  277. if (initial)
  278. bitSet.incl(startBit, endBit);
  279. for (unsigned i=startBit; i < endBit; i++)
  280. {
  281. ASSERT(bitSet.test(i) == clearValue);
  282. bitSet.set(i, setValue);
  283. ASSERT(bitSet.test(i) == setValue);
  284. if (i < (endBit-1))
  285. ASSERT(bitSet.scan(i, clearValue) == i+1); // find next unset (should be i+1)
  286. bitSet.set(i, clearValue);
  287. bitSet.invert(i);
  288. ASSERT(bitSet.test(i) == setValue);
  289. bitSet.invert(i);
  290. ASSERT(bitSet.test(i) == clearValue);
  291. bool wasSet = bitSet.testSet(i, setValue);
  292. ASSERT(wasSet == clearValue);
  293. bool wasSet2 = bitSet.testSet(i, clearValue);
  294. ASSERT(wasSet2 == setValue);
  295. ASSERT(bitSet.test(i) == clearValue);
  296. bitSet.set(i, setValue);
  297. unsigned match = bitSet.scanInvert(startBit, setValue);
  298. ASSERT(match == i);
  299. ASSERT(bitSet.test(i) == clearValue);
  300. }
  301. }
  302. catch (IException *e)
  303. {
  304. exception.setown(e);
  305. }
  306. catch (CppUnit::Exception &e)
  307. {
  308. cppunitException = e.clone();
  309. }
  310. }
  311. };
  312. unsigned testParallelRun(IBitSet &bitSet, unsigned nThreads, unsigned bitsPerThread, bool initial)
  313. {
  314. IArrayOf<CBitThread> bitThreads;
  315. unsigned bitStart = 0;
  316. unsigned bitEnd = 0;
  317. for (unsigned t=0; t<nThreads; t++)
  318. {
  319. bitThreads.append(* new CBitThread(bitSet, bitStart, bitsPerThread, initial));
  320. bitStart += bitsPerThread;
  321. }
  322. unsigned now = msTick();
  323. for (unsigned t=0; t<nThreads; t++)
  324. bitThreads.item(t).start();
  325. Owned<IException> exception;
  326. CppUnit::Exception *cppunitException = NULL;
  327. for (unsigned t=0; t<nThreads; t++)
  328. {
  329. try
  330. {
  331. bitThreads.item(t).join();
  332. }
  333. catch (IException *e)
  334. {
  335. EXCLOG(e, NULL);
  336. if (!exception)
  337. exception.setown(e);
  338. else
  339. e->Release();
  340. }
  341. catch (CppUnit::Exception *e)
  342. {
  343. cppunitException = e;
  344. }
  345. }
  346. if (exception)
  347. throw exception.getClear();
  348. else if (cppunitException)
  349. throw *cppunitException;
  350. return msTick()-now;
  351. }
  352. void testSetParallel(bool initial)
  353. {
  354. unsigned numBits = 1000000; // 10M
  355. unsigned nThreads = getAffinityCpus();
  356. unsigned bitsPerThread = numBits/nThreads;
  357. bitsPerThread = ((bitsPerThread + (BitsPerItem-1)) / BitsPerItem) * BitsPerItem; // round up to multiple of BitsPerItem
  358. numBits = bitsPerThread*nThreads; // round
  359. fprintf(stdout, "testSetParallel, testing bit set of size : %d, nThreads=%d\n", numBits, nThreads);
  360. Owned<IBitSet> bitSet = createThreadSafeBitSet();
  361. unsigned took = testParallelRun(*bitSet, nThreads, bitsPerThread, initial);
  362. fprintf(stdout, "Thread safe parallel bit set test (%u) time taken = %dms\n", initial, took);
  363. size32_t bitSetMemSz = getBitSetMemoryRequirement(numBits);
  364. MemoryBuffer mb;
  365. void *mem = mb.reserveTruncate(bitSetMemSz);
  366. bitSet.setown(createBitSet(bitSetMemSz, mem));
  367. took = testParallelRun(*bitSet, nThreads, bitsPerThread, initial);
  368. fprintf(stdout, "Thread unsafe parallel bit set test (%u) time taken = %dms\n", initial, took);
  369. }
  370. void testParallel()
  371. {
  372. testSetParallel(false);
  373. testSetParallel(true);
  374. }
  375. };
  376. CPPUNIT_TEST_SUITE_REGISTRATION( JlibSetTestQuick );
  377. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( JlibSetTestQuick, "JlibSetTestQuick" );
  378. CPPUNIT_TEST_SUITE_REGISTRATION( JlibSetTestStress );
  379. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( JlibSetTestStress, "JlibSetTestStress" );
  380. /* =========================================================== */
  381. class JlibFileIOTestTiming : public CppUnit::TestFixture
  382. {
  383. protected:
  384. unsigned rs, nr10pct, nr150pct;
  385. char *record;
  386. StringBuffer tmpfile;
  387. CPPUNIT_TEST_SUITE( JlibFileIOTestTiming );
  388. CPPUNIT_TEST(testIOSmall);
  389. CPPUNIT_TEST(testIOLarge);
  390. CPPUNIT_TEST_SUITE_END();
  391. public:
  392. JlibFileIOTestTiming()
  393. {
  394. HardwareInfo hdwInfo;
  395. getHardwareInfo(hdwInfo);
  396. rs = 65536;
  397. unsigned nr = (unsigned)(1024.0 * (1024.0 * (double)hdwInfo.totalMemory / (double)rs));
  398. nr10pct = nr / 10;
  399. nr150pct = (unsigned)((double)nr * 1.5);
  400. record = (char *)malloc(rs);
  401. for (unsigned i=0;i<rs;i++)
  402. record[i] = 'a';
  403. record[rs-1] = '\n';
  404. tmpfile.set("JlibFileIOTest.txt");
  405. }
  406. ~JlibFileIOTestTiming()
  407. {
  408. free(record);
  409. }
  410. protected:
  411. void testIO(unsigned nr, const char *server)
  412. {
  413. IFile *ifile;
  414. IFileIO *ifileio;
  415. unsigned fsize = (unsigned)(((double)nr * (double)rs) / (1024.0 * 1024.0));
  416. fflush(NULL);
  417. fprintf(stdout,"\n");
  418. fflush(NULL);
  419. for(int j=0; j<2; j++)
  420. {
  421. if (j==0)
  422. fprintf(stdout, "File size: %d (MB) Cache, ", fsize);
  423. else
  424. fprintf(stdout, "\nFile size: %d (MB) Nocache, ", fsize);
  425. if (server != NULL)
  426. {
  427. SocketEndpoint ep;
  428. ep.set(server, 7100);
  429. ifile = createRemoteFile(ep, tmpfile);
  430. fprintf(stdout, "Remote: (%s)\n", server);
  431. }
  432. else
  433. {
  434. ifile = createIFile(tmpfile);
  435. fprintf(stdout, "Local:\n");
  436. }
  437. ifile->remove();
  438. unsigned st = msTick();
  439. IFEflags extraFlags = IFEcache;
  440. if (j==1)
  441. extraFlags = IFEnocache;
  442. ifileio = ifile->open(IFOcreate, extraFlags);
  443. #if 0 // for testing default and explicitly set share mode to Windows dafilesrv
  444. if (server != NULL)
  445. ifile->setShareMode((IFSHmode)IFSHread);
  446. #endif
  447. try
  448. {
  449. ifile->setFilePermissions(0666);
  450. }
  451. catch (...)
  452. {
  453. fprintf(stdout, "ifile->setFilePermissions() exception\n");
  454. }
  455. unsigned iter = nr / 40;
  456. if (iter < 1)
  457. iter = 1;
  458. __int64 pos = 0;
  459. for (unsigned i=0;i<nr;i++)
  460. {
  461. ifileio->write(pos, rs, record);
  462. pos += rs;
  463. if ((i % iter) == 0)
  464. {
  465. fprintf(stdout,".");
  466. fflush(NULL);
  467. }
  468. }
  469. ifileio->close();
  470. double rsec = (double)(msTick() - st)/1000.0;
  471. unsigned iorate = (unsigned)((double)fsize / rsec);
  472. fprintf(stdout, "\nwrite - elapsed time = %6.2f (s) iorate = %4d (MB/s)\n", rsec, iorate);
  473. st = msTick();
  474. extraFlags = IFEcache;
  475. if (j==1)
  476. extraFlags = IFEnocache;
  477. ifileio = ifile->open(IFOread, extraFlags);
  478. pos = 0;
  479. for (unsigned i=0;i<nr;i++)
  480. {
  481. ifileio->read(pos, rs, record);
  482. pos += rs;
  483. if ((i % iter) == 0)
  484. {
  485. fprintf(stdout,".");
  486. fflush(NULL);
  487. }
  488. }
  489. ifileio->close();
  490. rsec = (double)(msTick() - st)/1000.0;
  491. iorate = (unsigned)((double)fsize / rsec);
  492. fprintf(stdout, "\nread -- elapsed time = %6.2f (s) iorate = %4d (MB/s)\n", rsec, iorate);
  493. ifileio->Release();
  494. ifile->remove();
  495. ifile->Release();
  496. }
  497. }
  498. void testIOSmall()
  499. {
  500. testIO(nr10pct, NULL);
  501. }
  502. void testIOLarge()
  503. {
  504. testIO(nr150pct, NULL);
  505. }
  506. };
  507. class JlibFileIOTestStress : public JlibFileIOTestTiming
  508. {
  509. protected:
  510. CPPUNIT_TEST_SUITE( JlibFileIOTestStress );
  511. CPPUNIT_TEST(testIORemote);
  512. CPPUNIT_TEST_SUITE_END();
  513. void testIORemote()
  514. {
  515. const char * server = ".";
  516. testIO(nr10pct, server);
  517. }
  518. };
  519. CPPUNIT_TEST_SUITE_REGISTRATION( JlibFileIOTestTiming );
  520. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( JlibFileIOTestTiming, "JlibFileIOTestTiming" );
  521. CPPUNIT_TEST_SUITE_REGISTRATION( JlibFileIOTestStress );
  522. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( JlibFileIOTestTiming, "JlibFileIOTestStress" );
  523. /* =========================================================== */
  524. class JlibStringBufferTiming : public CppUnit::TestFixture
  525. {
  526. CPPUNIT_TEST_SUITE( JlibStringBufferTiming );
  527. CPPUNIT_TEST(testSwap);
  528. CPPUNIT_TEST_SUITE_END();
  529. public:
  530. void testSwap()
  531. {
  532. StringBuffer l;
  533. StringBuffer r;
  534. for (unsigned len=0; len<40; len++)
  535. {
  536. const unsigned numIter = 100000000;
  537. cycle_t start = get_cycles_now();
  538. for (unsigned pass=0; pass < numIter; pass++)
  539. {
  540. l.swapWith(r);
  541. }
  542. cycle_t elapsed = get_cycles_now() - start;
  543. DBGLOG("Each iteration of size %u took %.2f nanoseconds", len, (double)cycle_to_nanosec(elapsed) / numIter);
  544. l.append("a");
  545. r.append("b");
  546. }
  547. }
  548. };
  549. CPPUNIT_TEST_SUITE_REGISTRATION( JlibStringBufferTiming );
  550. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( JlibStringBufferTiming, "JlibStringBufferTiming" );
  551. /* =========================================================== */
  552. static const unsigned split4_2[] = {0, 2, 4 };
  553. static const unsigned split100_2[] = {0, 50, 100 };
  554. static const unsigned split100_10[] = {0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };
  555. static const unsigned split7_10[] = {0,1,1,2,3,3,4,5,6,6,7 };
  556. static const unsigned split10_3[] = {0,3,7,10 };
  557. static const unsigned split58_10[] = {0,6,12,17,23,29,35,41,46,52,58 };
  558. static const unsigned split9_2T[] = { 0,5,9 };
  559. static const unsigned split9_2F[] = { 0,4,9 };
  560. static const unsigned split15_3[] = { 0,5,10,15 };
  561. class JlibQuantileTest : public CppUnit::TestFixture
  562. {
  563. CPPUNIT_TEST_SUITE( JlibQuantileTest );
  564. CPPUNIT_TEST(testQuantile);
  565. CPPUNIT_TEST(testRandom);
  566. CPPUNIT_TEST_SUITE_END();
  567. public:
  568. JlibQuantileTest()
  569. {
  570. }
  571. void testQuantilePos(unsigned numItems, unsigned numDivisions, bool roundUp, const unsigned * expected)
  572. {
  573. if (numDivisions == 0)
  574. return;
  575. QuantilePositionIterator iter(numItems, numDivisions, roundUp);
  576. QuantileFilterIterator filter(numItems, numDivisions, roundUp);
  577. unsigned prevPos = 0;
  578. iter.first();
  579. for (unsigned i=0; i <= numDivisions; i++)
  580. {
  581. //Check the values from the quantile iterator match those that are expected
  582. unsigned pos = (unsigned)iter.get();
  583. #if 0
  584. printf("(%d,%d) %d=%d\n", numItems, numDivisions, i, pos);
  585. #endif
  586. if (expected)
  587. CPPUNIT_ASSERT_EQUAL(expected[i], pos);
  588. //Check that the quantile filter correctly returns true and false for subsequent calls.
  589. while (prevPos < pos)
  590. {
  591. CPPUNIT_ASSERT(!filter.get());
  592. filter.next();
  593. prevPos++;
  594. }
  595. if (prevPos == pos)
  596. {
  597. CPPUNIT_ASSERT(filter.get());
  598. filter.next();
  599. prevPos++;
  600. }
  601. iter.next();
  602. }
  603. }
  604. void testQuantile()
  605. {
  606. testQuantilePos(4, 2, false, split4_2);
  607. testQuantilePos(100, 2, false, split100_2);
  608. testQuantilePos(100, 10, false, split100_10);
  609. testQuantilePos(7, 10, false, split7_10);
  610. testQuantilePos(10, 3, false, split10_3);
  611. testQuantilePos(10, 3, true, split10_3);
  612. testQuantilePos(58, 10, false, split58_10);
  613. //testQuantilePos(9, 2, true, split9_2T);
  614. testQuantilePos(9, 2, false, split9_2F);
  615. testQuantilePos(15, 3, false, split15_3);
  616. testQuantilePos(1231, 57, false, NULL);
  617. testQuantilePos(1, 63, false, NULL);
  618. testQuantilePos(10001, 17, false, NULL);
  619. }
  620. void testRandom()
  621. {
  622. //test various random combinations to ensure the results are consistent.
  623. for (unsigned i=0; i < 10; i++)
  624. testQuantilePos(random() % 1000000, random() % 10000, true, NULL);
  625. }
  626. };
  627. CPPUNIT_TEST_SUITE_REGISTRATION( JlibQuantileTest );
  628. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( JlibQuantileTest, "JlibQuantileTest" );
  629. /* =========================================================== */
  630. class JlibReaderWriterTestTiming : public CppUnit::TestFixture
  631. {
  632. CPPUNIT_TEST_SUITE(JlibReaderWriterTestTiming);
  633. CPPUNIT_TEST(testCombinations);
  634. CPPUNIT_TEST_SUITE_END();
  635. const static unsigned spinScaling = 1000;
  636. static unsigned spinCalculation(unsigned prev, unsigned scale)
  637. {
  638. unsigned value = prev;
  639. for (unsigned i = 0; i < scale*spinScaling; i++)
  640. {
  641. value = (value * 0x1234FEDB + 0x87654321);
  642. }
  643. return value;
  644. }
  645. class Reader : public Thread
  646. {
  647. public:
  648. Reader(IRowQueue & _source, Semaphore & _doneSem, unsigned _workScale)
  649. : Thread("Reader"), source(_source), doneSem(_doneSem), workScale(_workScale), work(0)
  650. {
  651. }
  652. virtual int run()
  653. {
  654. for (;;)
  655. {
  656. const void * next;
  657. if (!source.dequeue(next))
  658. break;
  659. if (!next)
  660. break;
  661. std::atomic<byte> * value = (std::atomic<byte> *)next;
  662. (*value)++;
  663. if (workScale)
  664. work = spinCalculation(work, workScale);
  665. }
  666. doneSem.signal();
  667. return 0;
  668. }
  669. private:
  670. IRowQueue & source;
  671. Semaphore & doneSem;
  672. volatile unsigned work;
  673. unsigned workScale;
  674. };
  675. class WriterBase : public Thread
  676. {
  677. public:
  678. WriterBase(IRowQueue & _target, size_t _len, byte * _buffer, Semaphore & _startSem, Semaphore & _doneSem, unsigned _workScale)
  679. : Thread("Writer"), target(_target), len(_len), buffer(_buffer), startSem(_startSem), doneSem(_doneSem), workScale(_workScale), work(0)
  680. {
  681. }
  682. protected:
  683. size_t len;
  684. byte * buffer;
  685. IRowQueue & target;
  686. Semaphore & startSem;
  687. Semaphore & doneSem;
  688. volatile unsigned work;
  689. unsigned workScale;
  690. };
  691. class Writer : public WriterBase
  692. {
  693. public:
  694. Writer(IRowQueue & _target, size_t _len, byte * _buffer, Semaphore & _startSem, Semaphore & _doneSem, unsigned _workScale)
  695. : WriterBase(_target, _len, _buffer, _startSem, _doneSem, _workScale)
  696. {
  697. }
  698. virtual int run()
  699. {
  700. startSem.wait();
  701. for (size_t i = 0; i < len; i++)
  702. {
  703. if (workScale)
  704. work = spinCalculation(work, workScale);
  705. target.enqueue(buffer + i);
  706. }
  707. target.noteWriterStopped();
  708. doneSem.signal();
  709. return 0;
  710. }
  711. };
  712. public:
  713. const static size_t bufferSize = 0x100000;//0x100000*64;
  714. void testQueue(IRowQueue & queue, unsigned numProducers, unsigned numConsumers, unsigned queueElements, unsigned readerWork, unsigned writerWork)
  715. {
  716. const size_t sizePerProducer = bufferSize / numProducers;
  717. const size_t testSize = sizePerProducer * numProducers;
  718. OwnedMalloc<byte> buffer(bufferSize, true);
  719. Semaphore startSem;
  720. Semaphore writerDoneSem;
  721. Semaphore stopSem;
  722. Reader * * consumers = new Reader *[numConsumers];
  723. for (unsigned i2 = 0; i2 < numConsumers; i2++)
  724. {
  725. consumers[i2] = new Reader(queue, stopSem, readerWork);
  726. consumers[i2]->start();
  727. }
  728. WriterBase * * producers = new WriterBase *[numProducers];
  729. for (unsigned i1 = 0; i1 < numProducers; i1++)
  730. {
  731. producers[i1] = new Writer(queue, sizePerProducer, buffer + i1 * sizePerProducer, startSem, writerDoneSem, writerWork);
  732. producers[i1]->start();
  733. }
  734. cycle_t startTime = get_cycles_now();
  735. //Start the writers
  736. startSem.signal(numProducers);
  737. //Wait for the writers to complete
  738. for (unsigned i7 = 0; i7 < numProducers; i7++)
  739. writerDoneSem.wait();
  740. //Wait for the readers to complete
  741. for (unsigned i3 = 0; i3 < numConsumers; i3++)
  742. stopSem.wait();
  743. cycle_t stopTime = get_cycles_now();
  744. //All bytes should have been changed to 1, if not a queue item got lost.
  745. unsigned failures = 0;
  746. unsigned numClear = 0;
  747. size_t failPos = ~(size_t)0;
  748. byte failValue = 0;
  749. for (size_t pos = 0; pos < testSize; pos++)
  750. {
  751. if (buffer[pos] != 1)
  752. {
  753. failures++;
  754. if (failPos == ~(size_t)0)
  755. {
  756. failPos = pos;
  757. failValue = buffer[pos];
  758. }
  759. }
  760. if (buffer[pos] == 0)
  761. numClear++;
  762. }
  763. unsigned timeMs = cycle_to_nanosec(stopTime - startTime) / 1000000;
  764. unsigned expectedReadWorkTime = (unsigned)(((double)unitWorkTimeMs * readerWork) / numConsumers);
  765. unsigned expectedWriteWorkTime = (unsigned)(((double)unitWorkTimeMs * writerWork) / numProducers);
  766. unsigned expectedWorkTime = std::max(expectedReadWorkTime, expectedWriteWorkTime);
  767. if (failures)
  768. {
  769. printf("Fail: Test %u producers %u consumers %u queueItems %u(%u) mismatches fail(@%u=%u)\n", numProducers, numConsumers, queueElements, failures, numClear, (unsigned)failPos, failValue);
  770. ASSERT(failures == 0);
  771. }
  772. else
  773. printf("Pass: Test %u(@%u) producers %u(@%u) consumers %u queueItems in %ums [%dms]\n", numProducers, writerWork, numConsumers, readerWork, queueElements, timeMs, timeMs-expectedWorkTime);
  774. for (unsigned i4 = 0; i4 < numConsumers; i4++)
  775. {
  776. consumers[i4]->join();
  777. consumers[i4]->Release();
  778. }
  779. delete[] consumers;
  780. for (unsigned i5 = 0; i5 < numProducers; i5++)
  781. {
  782. producers[i5]->join();
  783. producers[i5]->Release();
  784. }
  785. delete[] producers;
  786. }
  787. void testQueue(unsigned numProducers, unsigned numConsumers, unsigned numElements = 0, unsigned readWork = 0, unsigned writeWork = 0)
  788. {
  789. unsigned queueElements = (numElements != 0) ? numElements : (numProducers + numConsumers) * 2;
  790. Owned<IRowQueue> queue = createRowQueue(numConsumers, numProducers, queueElements, 0);
  791. testQueue(*queue, numProducers, numConsumers, queueElements, readWork, writeWork);
  792. }
  793. void testWorkQueue(unsigned numProducers, unsigned numConsumers, unsigned numElements)
  794. {
  795. for (unsigned readWork = 1; readWork <= 8; readWork = readWork * 2)
  796. {
  797. for (unsigned writeWork = 1; writeWork <= 8; writeWork = writeWork * 2)
  798. {
  799. testQueue(numProducers, numConsumers, numElements, readWork, writeWork);
  800. }
  801. }
  802. }
  803. void testCombinations()
  804. {
  805. // 1:1
  806. for (unsigned i=0; i < 10; i++)
  807. testQueue(1, 1, 10);
  808. //One to Many
  809. testQueue(1, 10, 5);
  810. testQueue(1, 5, 5);
  811. testQueue(1, 5, 10);
  812. testQueue(1, 127, 10);
  813. testQueue(1, 127, 127);
  814. //Many to One
  815. testQueue(10, 1, 5);
  816. testQueue(5, 1, 5);
  817. testQueue(5, 1, 10);
  818. testQueue(127, 1, 127);
  819. cycle_t startTime = get_cycles_now();
  820. volatile unsigned value = 0;
  821. for (unsigned pass = 0; pass < 10; pass++)
  822. {
  823. for (unsigned i2 = 0; i2 < bufferSize; i2++)
  824. value = spinCalculation(value, 1);
  825. }
  826. cycle_t stopTime = get_cycles_now();
  827. unitWorkTimeMs = cycle_to_nanosec(stopTime - startTime) / (1000000 * 10);
  828. printf("Work(1) takes %ums\n", unitWorkTimeMs);
  829. //How does it scale with number of queue elements?
  830. for (unsigned elem = 16; elem < 256; elem *= 2)
  831. {
  832. testQueue(16, 1, elem, 1, 1);
  833. }
  834. #if 1
  835. //Many to Many
  836. for (unsigned readWork = 1; readWork <= 8; readWork = readWork * 2)
  837. {
  838. for (unsigned writeWork = 1; writeWork <= 8; writeWork = writeWork * 2)
  839. {
  840. testQueue(1, 1, 63, readWork, writeWork);
  841. testQueue(1, 2, 63, readWork, writeWork);
  842. testQueue(1, 4, 63, readWork, writeWork);
  843. testQueue(1, 8, 63, readWork, writeWork);
  844. testQueue(1, 16, 63, readWork, writeWork);
  845. testQueue(2, 1, 63, readWork, writeWork);
  846. testQueue(4, 1, 63, readWork, writeWork);
  847. testQueue(8, 1, 63, readWork, writeWork);
  848. testQueue(16, 1, 63, readWork, writeWork);
  849. testQueue(2, 2, 63, readWork, writeWork);
  850. testQueue(4, 4, 63, readWork, writeWork);
  851. testQueue(8, 8, 63, readWork, writeWork);
  852. testQueue(16, 8, 63, readWork, writeWork);
  853. testQueue(16, 16, 63, readWork, writeWork);
  854. testQueue(32, 1, 63, readWork, writeWork);
  855. testQueue(64, 1, 63, readWork, writeWork);
  856. testQueue(1, 32, 63, readWork, writeWork);
  857. testQueue(1, 64, 63, readWork, writeWork);
  858. }
  859. }
  860. #else
  861. //Many to Many
  862. testWorkQueue(1, 1, 63);
  863. testWorkQueue(1, 2, 63);
  864. testWorkQueue(1, 4, 63);
  865. testWorkQueue(1, 8, 63);
  866. testWorkQueue(1, 16, 63);
  867. testWorkQueue(2, 1, 63);
  868. testWorkQueue(4, 1, 63);
  869. testWorkQueue(8, 1, 63);
  870. testWorkQueue(16, 1, 63);
  871. testWorkQueue(2, 2, 63);
  872. testWorkQueue(4, 4, 63);
  873. testWorkQueue(8, 8, 63);
  874. #endif
  875. testQueue(2, 2, 4);
  876. testQueue(2, 2, 8);
  877. testQueue(2, 2, 16);
  878. testQueue(2, 2, 32);
  879. testQueue(2, 2, 100);
  880. }
  881. protected:
  882. unsigned unitWorkTimeMs;
  883. };
  884. CPPUNIT_TEST_SUITE_REGISTRATION(JlibReaderWriterTestTiming);
  885. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(JlibReaderWriterTestTiming, "JlibReaderWriterTestTiming");
  886. /* =========================================================== */
  887. class JlibWildMatchBase : public CppUnit::TestFixture
  888. {
  889. protected:
  890. void testSet(unsigned length, const char * const * patterns, bool reportTiming)
  891. {
  892. std::unique_ptr<char[]> search(generateSearchString(length));
  893. CCycleTimer timer;
  894. testPatterns(search.get(), patterns);
  895. if (reportTiming)
  896. printf("%u: %u ms\n", length, timer.elapsedMs());
  897. }
  898. char * generateSearchString(size_t len)
  899. {
  900. char * target = new char[len+1];
  901. fillSearchString(target, len);
  902. target[len] = 0;
  903. return target;
  904. }
  905. void fillSearchString(char * target, size_t len)
  906. {
  907. for (unsigned repeat=0; ; repeat++)
  908. {
  909. for (unsigned char fill = 'a'; fill <= 'z'; fill++)
  910. {
  911. for (unsigned i=0; i < repeat; i++)
  912. {
  913. *target++ = fill;
  914. if (--len == 0)
  915. return;
  916. }
  917. }
  918. }
  919. }
  920. void testPatterns(const char * search, const char * const * patterns)
  921. {
  922. for (const char * const * cur = patterns; *cur; cur++)
  923. {
  924. const char * pattern = *cur;
  925. bool expected = true;
  926. bool nocase = false;
  927. if (*pattern == '!')
  928. {
  929. expected = false;
  930. pattern++;
  931. }
  932. if (*pattern == '~')
  933. {
  934. nocase = true;
  935. pattern++;
  936. }
  937. bool evaluated = WildMatch(search, pattern, nocase);
  938. CPPUNIT_ASSERT_EQUAL_MESSAGE(pattern, expected, evaluated);
  939. }
  940. }
  941. };
  942. const char * const patterns10 [] = {
  943. "!a",
  944. "abcdefghij",
  945. "??????????",
  946. "?*c?*e*",
  947. "!??*b?*h*",
  948. "a*",
  949. "*j",
  950. "a*j",
  951. "a**j",
  952. "a***************j",
  953. "abcde*fghij",
  954. "!abcde*?*fghij",
  955. "*a*j*",
  956. "*a*c*e*g*j*",
  957. "a?c?e?g??j",
  958. "a?c?e?g?*?j",
  959. "!~A",
  960. "!A*",
  961. "~A*",
  962. "~*J",
  963. "~A*J",
  964. "~A**J",
  965. "~A***************J",
  966. "~*A*J*",
  967. "~*A*C*E*G*J*",
  968. "~*A*B*C*D*E*F*G*H*I*J*",
  969. "~*A*?*?*?*J*",
  970. "~*A*?C*?E*?*J*",
  971. "~*A*C?*E?*?*J*",
  972. "!~*A*.B*C*D*E*F*G*H*I*J*",
  973. nullptr
  974. };
  975. const char * const patterns100 [] = {
  976. "a*",
  977. "*h",
  978. "a*h",
  979. "a**h",
  980. "a***************h",
  981. "*a*j*",
  982. "*a*c*e*g*j*",
  983. "!a*jj*fff",
  984. "!a*jj*zzz",
  985. "a*jj*fff*",
  986. "*aa*jj*fff*",
  987. "!a*jj*zy*",
  988. nullptr
  989. };
  990. const char * const patternsLarge [] = {
  991. "!*a*zy*",
  992. "a*",
  993. "a*h*",
  994. "!a*jj*ab",
  995. "!a*jj*zy",
  996. "a*jj*fff*",
  997. "!a*jj*zy*",
  998. /* "!a*c*e*g*i*k*zy*", will completely destroy the performance*/
  999. nullptr
  1000. };
  1001. class JlibWildMatchCore : public JlibWildMatchBase
  1002. {
  1003. CPPUNIT_TEST_SUITE(JlibWildMatchCore);
  1004. CPPUNIT_TEST(testWildMatch);
  1005. CPPUNIT_TEST_SUITE_END();
  1006. public:
  1007. void testWildMatch()
  1008. {
  1009. testSet(10, patterns10, false);
  1010. testSet(100, patterns100, false);
  1011. testSet(1000, patternsLarge, false);
  1012. }
  1013. };
  1014. CPPUNIT_TEST_SUITE_REGISTRATION(JlibWildMatchCore);
  1015. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(JlibWildMatchCore, "JlibWildMatchCore");
  1016. class JlibWildMatchTiming : public JlibWildMatchBase
  1017. {
  1018. CPPUNIT_TEST_SUITE(JlibWildMatchTiming);
  1019. CPPUNIT_TEST(testWildMatch);
  1020. CPPUNIT_TEST_SUITE_END();
  1021. public:
  1022. void testWildMatch()
  1023. {
  1024. testSet(10000, patternsLarge, true);
  1025. testSet(100000, patternsLarge, true);
  1026. testSet(1000000, patternsLarge, true);
  1027. }
  1028. };
  1029. CPPUNIT_TEST_SUITE_REGISTRATION(JlibWildMatchTiming);
  1030. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(JlibWildMatchTiming, "JlibWildMatchTiming");
  1031. const EnumMapping mapping[] = {
  1032. { 1, "one" },
  1033. { 3, "three" },
  1034. { 5, "five" },
  1035. {0, nullptr }
  1036. };
  1037. const char * strings[] = { "zero", "one", "two", "three", "four", nullptr };
  1038. class JlibMapping : public CppUnit::TestFixture
  1039. {
  1040. CPPUNIT_TEST_SUITE(JlibMapping);
  1041. CPPUNIT_TEST(testEnum);
  1042. CPPUNIT_TEST(testMatch);
  1043. CPPUNIT_TEST_SUITE_END();
  1044. public:
  1045. void testEnum()
  1046. {
  1047. CPPUNIT_ASSERT(streq("one", getEnumText(1, mapping)));
  1048. CPPUNIT_ASSERT(streq("three", getEnumText(3, mapping)));
  1049. CPPUNIT_ASSERT(streq("five", getEnumText(5, mapping)));
  1050. CPPUNIT_ASSERT(streq("two", getEnumText(2, mapping, "two")));
  1051. CPPUNIT_ASSERT(!getEnumText(2, mapping, nullptr));
  1052. CPPUNIT_ASSERT_EQUAL(1, getEnum("one", mapping));
  1053. CPPUNIT_ASSERT_EQUAL(3, getEnum("three", mapping));
  1054. CPPUNIT_ASSERT_EQUAL(5, getEnum("five", mapping));
  1055. CPPUNIT_ASSERT_EQUAL(99, getEnum("seven", mapping, 99));
  1056. }
  1057. void testMatch()
  1058. {
  1059. CPPUNIT_ASSERT_EQUAL(0U, matchString("zero", strings));
  1060. CPPUNIT_ASSERT_EQUAL(1U, matchString("one", strings));
  1061. CPPUNIT_ASSERT_EQUAL(4U, matchString("four", strings));
  1062. CPPUNIT_ASSERT_EQUAL(UINT_MAX, matchString("ten", strings));
  1063. }
  1064. };
  1065. CPPUNIT_TEST_SUITE_REGISTRATION(JlibMapping);
  1066. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(JlibMapping, "JlibMapping");
  1067. class JlibIPTTest : public CppUnit::TestFixture
  1068. {
  1069. CPPUNIT_TEST_SUITE(JlibIPTTest);
  1070. CPPUNIT_TEST(test);
  1071. CPPUNIT_TEST(testMarkup);
  1072. CPPUNIT_TEST(testRootArrayMarkup);
  1073. CPPUNIT_TEST(testArrayMarkup);
  1074. CPPUNIT_TEST(testMergeConfig);
  1075. CPPUNIT_TEST_SUITE_END();
  1076. public:
  1077. void testArrayMarkup()
  1078. {
  1079. static constexpr const char * yamlFlowMarkup = R"!!({a: {
  1080. b: valb,
  1081. c: [valc],
  1082. d: [vald1,vald2],
  1083. e: [{x: valex1, y: valey1}],
  1084. f: {x: valfx1, y: valfy1},
  1085. g: [{x: valgx1, y: valgy1},{x: valgx2, y: valgy2}],
  1086. h: !el valh,
  1087. i: {
  1088. j: {
  1089. b: valb,
  1090. c: [valc],
  1091. d: [vald1,vald2],
  1092. e: [{x: valex1, y: valey1}],
  1093. f: {x: valfx1, y: valfy1},
  1094. g: [{x: valgx1, y: valgy1},{x: valgx2, y: valgy2}],
  1095. h: !el valh,
  1096. },
  1097. k: [{
  1098. b: valb,
  1099. c: [valc],
  1100. d: [vald1,vald2],
  1101. e: [{x: valex1, y: valey1}],
  1102. f: {x: valfx1, y: valfy1},
  1103. g: [{x: valgx1, y: valgy1},{x: valgx2, y: valgy2}],
  1104. h: !el valh,
  1105. }],
  1106. l: [{
  1107. b: valb,
  1108. c: [valc],
  1109. d: [vald1,vald2],
  1110. e: [{x: valex1, y: valey1}],
  1111. f: {x: valfx1, y: valfy1},
  1112. g: [{x: valgx1, y: valgy1},{x: valgx2, y: valgy2}],
  1113. h: !el valh,
  1114. },
  1115. {
  1116. b: valb,
  1117. c: [valc],
  1118. d: [vald1,vald2],
  1119. e: [{x: valex1, y: valey1}],
  1120. f: {x: valfx1, y: valfy1},
  1121. g: [{x: valgx1, y: valgy1},{x: valgx2, y: valgy2}],
  1122. h: !el valh,
  1123. }],
  1124. }
  1125. }
  1126. }
  1127. )!!";
  1128. static constexpr const char * yamlBlockMarkup = R"!!(a:
  1129. b: valb
  1130. c:
  1131. - valc
  1132. d:
  1133. - vald1
  1134. - vald2
  1135. e:
  1136. - x: valex1
  1137. y: valey1
  1138. f:
  1139. x: valfx1
  1140. y: valfy1
  1141. g:
  1142. - x: valgx1
  1143. y: valgy1
  1144. - x: valgx2
  1145. y: valgy2
  1146. h: !el valh
  1147. i:
  1148. j:
  1149. b: valb
  1150. c:
  1151. - valc
  1152. d:
  1153. - vald1
  1154. - vald2
  1155. e:
  1156. - x: valex1
  1157. y: valey1
  1158. f:
  1159. x: valfx1
  1160. y: valfy1
  1161. g:
  1162. - x: valgx1
  1163. y: valgy1
  1164. - x: valgx2
  1165. y: valgy2
  1166. h: !el valh
  1167. k:
  1168. - b: valb
  1169. c:
  1170. - valc
  1171. d:
  1172. - vald1
  1173. - vald2
  1174. e:
  1175. - x: valex1
  1176. y: valey1
  1177. f:
  1178. x: valfx1
  1179. y: valfy1
  1180. g:
  1181. - x: valgx1
  1182. y: valgy1
  1183. - x: valgx2
  1184. y: valgy2
  1185. h: !el valh
  1186. l:
  1187. - b: valb
  1188. c:
  1189. - valc
  1190. d:
  1191. - vald1
  1192. - vald2
  1193. e:
  1194. - x: valex1
  1195. y: valey1
  1196. f:
  1197. x: valfx1
  1198. y: valfy1
  1199. g:
  1200. - x: valgx1
  1201. y: valgy1
  1202. - x: valgx2
  1203. y: valgy2
  1204. h: !el valh
  1205. - b: valb
  1206. c:
  1207. - valc
  1208. d:
  1209. - vald1
  1210. - vald2
  1211. e:
  1212. - x: valex1
  1213. y: valey1
  1214. f:
  1215. x: valfx1
  1216. y: valfy1
  1217. g:
  1218. - x: valgx1
  1219. y: valgy1
  1220. - x: valgx2
  1221. y: valgy2
  1222. h: !el valh
  1223. )!!";
  1224. StringBuffer ml;
  1225. Owned<IPropertyTree> yamlFlow = createPTreeFromYAMLString(yamlFlowMarkup, ipt_none, ptr_ignoreWhiteSpace, nullptr);
  1226. toYAML(yamlFlow, ml.clear(), 0, YAML_SortTags|YAML_HideRootArrayObject);
  1227. CPPUNIT_ASSERT(streq(ml, yamlBlockMarkup));
  1228. Owned<IPropertyTree> yamlBlock = createPTreeFromYAMLString(yamlBlockMarkup, ipt_none, ptr_ignoreWhiteSpace, nullptr);
  1229. toYAML(yamlBlock, ml.clear(), 0, YAML_SortTags|YAML_HideRootArrayObject);
  1230. CPPUNIT_ASSERT(streq(ml, yamlBlockMarkup));
  1231. }
  1232. void testMergeConfig()
  1233. {
  1234. static constexpr const char * yamlLeft = R"!!({a: {
  1235. b: gone,
  1236. bk: kept,
  1237. c: [gone],
  1238. ck: [kept],
  1239. d: [gone1,gone2],
  1240. dk: [kept1,kept2],
  1241. e: [{name: merged, x: gone, z: kept},{altname: merged, x: gone, z: kept},{name: kept, x: kept, y: kept}, {unnamed: kept, x: kept, y: kept}],
  1242. ek: [{name: kept, x: kept, y: kept}, {unnamed: kept, x: kept, y: kept}],
  1243. f: [{unnamed: gone, x: gone, y: gone}, {unnamed: gone2, x: gone2, y: gone2}],
  1244. kept: {x: kept, y: kept},
  1245. merged: {x: gone, z: kept}
  1246. }
  1247. }
  1248. )!!";
  1249. static constexpr const char * yamlBlockLeft = R"!!(a:
  1250. b: gone
  1251. bk: kept
  1252. c:
  1253. - gone
  1254. ck:
  1255. - kept
  1256. d:
  1257. - gone1
  1258. - gone2
  1259. dk:
  1260. - kept1
  1261. - kept2
  1262. e:
  1263. - name: merged
  1264. x: gone
  1265. z: kept
  1266. - altname: merged
  1267. x: gone
  1268. z: kept
  1269. - name: kept
  1270. x: kept
  1271. y: kept
  1272. - unnamed: kept
  1273. x: kept
  1274. y: kept
  1275. ek:
  1276. - name: kept
  1277. x: kept
  1278. y: kept
  1279. - unnamed: kept
  1280. x: kept
  1281. y: kept
  1282. f:
  1283. - unnamed: gone
  1284. x: gone
  1285. y: gone
  1286. - unnamed: gone2
  1287. x: gone2
  1288. y: gone2
  1289. kept:
  1290. x: kept
  1291. y: kept
  1292. merged:
  1293. x: gone
  1294. z: kept
  1295. )!!";
  1296. static constexpr const char * yamlRight = R"!!({a: {
  1297. b: updated,
  1298. c: [added],
  1299. d: [added1,added2],
  1300. e: [{name: merged, x: updated, y: added},{altname: merged, x: updated, y: added},{name: added, x: added, y: added}, {unnamed: added, x: added, y: added}],
  1301. f: [{unnamed: kept, x: kept, y: kept}, {unnamed: kept2, x: kept2, y: kept2}],
  1302. added: {x: added, y: added},
  1303. merged: {x: updated, y: added}
  1304. }
  1305. }
  1306. )!!";
  1307. static constexpr const char * yamlBlockRight = R"!!(a:
  1308. b: updated
  1309. c:
  1310. - added
  1311. d:
  1312. - added1
  1313. - added2
  1314. e:
  1315. - name: merged
  1316. x: updated
  1317. y: added
  1318. - altname: merged
  1319. x: updated
  1320. y: added
  1321. - name: added
  1322. x: added
  1323. y: added
  1324. - unnamed: added
  1325. x: added
  1326. y: added
  1327. f:
  1328. - unnamed: kept
  1329. x: kept
  1330. y: kept
  1331. - unnamed: kept2
  1332. x: kept2
  1333. y: kept2
  1334. added:
  1335. x: added
  1336. y: added
  1337. merged:
  1338. x: updated
  1339. y: added
  1340. )!!";
  1341. static constexpr const char * yamlMerged = R"!!(a:
  1342. b: updated
  1343. bk: kept
  1344. added:
  1345. x: added
  1346. y: added
  1347. c:
  1348. - added
  1349. ck:
  1350. - kept
  1351. d:
  1352. - added1
  1353. - added2
  1354. dk:
  1355. - kept1
  1356. - kept2
  1357. e:
  1358. - name: merged
  1359. x: updated
  1360. y: added
  1361. z: kept
  1362. - altname: merged
  1363. x: updated
  1364. y: added
  1365. z: kept
  1366. - name: kept
  1367. x: kept
  1368. y: kept
  1369. - unnamed: kept
  1370. x: kept
  1371. y: kept
  1372. - name: added
  1373. x: added
  1374. y: added
  1375. - unnamed: added
  1376. x: added
  1377. y: added
  1378. ek:
  1379. - name: kept
  1380. x: kept
  1381. y: kept
  1382. - unnamed: kept
  1383. x: kept
  1384. y: kept
  1385. f:
  1386. - unnamed: kept
  1387. x: kept
  1388. y: kept
  1389. - unnamed: kept2
  1390. x: kept2
  1391. y: kept2
  1392. kept:
  1393. x: kept
  1394. y: kept
  1395. merged:
  1396. x: updated
  1397. y: added
  1398. z: kept
  1399. )!!";
  1400. StringBuffer ml;
  1401. Owned<IPropertyTree> treeLeft = createPTreeFromYAMLString(yamlLeft, ipt_none, ptr_ignoreWhiteSpace, nullptr);
  1402. Owned<IPropertyTree> treeRight = createPTreeFromYAMLString(yamlRight, ipt_none, ptr_ignoreWhiteSpace, nullptr);
  1403. mergeConfiguration(*treeLeft, *treeRight, "@altname");
  1404. toYAML(treeLeft, ml.clear(), 0, YAML_SortTags|YAML_HideRootArrayObject);
  1405. CPPUNIT_ASSERT(streq(ml, yamlMerged));
  1406. Owned<IPropertyTree> treeBlockLeft = createPTreeFromYAMLString(yamlBlockLeft, ipt_none, ptr_ignoreWhiteSpace, nullptr);
  1407. Owned<IPropertyTree> treeBlockRight = createPTreeFromYAMLString(yamlBlockRight, ipt_none, ptr_ignoreWhiteSpace, nullptr);
  1408. mergeConfiguration(*treeBlockLeft, *treeBlockRight, "@altname");
  1409. toYAML(treeBlockLeft, ml.clear(), 0, YAML_SortTags|YAML_HideRootArrayObject);
  1410. CPPUNIT_ASSERT(streq(ml, yamlMerged));
  1411. }
  1412. void testRootArrayMarkup()
  1413. {
  1414. static constexpr const char * xmlMarkup = R"!!(<__array__>
  1415. <__item__ a="val1a" b="val2a"/>
  1416. <__item__ a="val1b" b="val2b"/>
  1417. <__item__ a="val1c" b="val2c"/>
  1418. </__array__>
  1419. )!!";
  1420. static constexpr const char * jsonMarkup = R"!!([
  1421. {
  1422. "@a": "val1a",
  1423. "@b": "val2a"
  1424. },
  1425. {
  1426. "@a": "val1b",
  1427. "@b": "val2b"
  1428. },
  1429. {
  1430. "@a": "val1c",
  1431. "@b": "val2c"
  1432. }
  1433. ])!!";
  1434. static constexpr const char * yamlMarkup = R"!!(- a: val1a
  1435. b: val2a
  1436. - a: val1b
  1437. b: val2b
  1438. - a: val1c
  1439. b: val2c
  1440. )!!";
  1441. Owned<IPropertyTree> xml = createPTreeFromXMLString(xmlMarkup, ipt_none, ptr_ignoreWhiteSpace, nullptr);
  1442. Owned<IPropertyTree> yaml = createPTreeFromYAMLString(yamlMarkup, ipt_none, ptr_ignoreWhiteSpace, nullptr);
  1443. Owned<IPropertyTree> json = createPTreeFromJSONString(jsonMarkup, ipt_none, ptr_ignoreWhiteSpace, nullptr);
  1444. CPPUNIT_ASSERT(areMatchingPTrees(xml, json));
  1445. CPPUNIT_ASSERT(areMatchingPTrees(xml, yaml));
  1446. StringBuffer ml;
  1447. toXML(xml, ml, 0, XML_Format|XML_SortTags);
  1448. CPPUNIT_ASSERT(streq(ml, xmlMarkup));
  1449. toYAML(xml, ml.clear(), 0, YAML_SortTags|YAML_HideRootArrayObject);
  1450. CPPUNIT_ASSERT(streq(ml, yamlMarkup));
  1451. toJSON(xml, ml.clear(), 0, JSON_Format|JSON_SortTags|JSON_HideRootArrayObject);
  1452. CPPUNIT_ASSERT(streq(ml, jsonMarkup));
  1453. }
  1454. void testMarkup()
  1455. {
  1456. static constexpr const char * xmlMarkup = R"!!( <__object__ attr1="attrval1" attr2="attrval2">
  1457. <binmixed bin="1" xsi:type="SOAP-ENC:base64">
  1458. CwAAAA== </binmixed>
  1459. <binsimple xsi:type="SOAP-ENC:base64">
  1460. CwAAAA== </binsimple>
  1461. <element1>scalarvalue</element1>
  1462. <item a="1"
  1463. b="2"
  1464. c="3"
  1465. d="4"/>
  1466. <item a="2"/>
  1467. <item a="3"/>
  1468. <scalars>
  1469. <valX>x</valX>
  1470. <valX>x</valX>
  1471. <valY>y</valY>
  1472. <valY>y</valY>
  1473. <valZ>z</valZ>
  1474. </scalars>
  1475. <sub1 subattr1="sav1">
  1476. sub1val
  1477. </sub1>
  1478. <sub2 subattr2="sav2">
  1479. sub2val
  1480. </sub2>
  1481. <subX subattr3="sav3">
  1482. subXval
  1483. </subX>
  1484. cpptestval
  1485. </__object__>
  1486. )!!";
  1487. static constexpr const char * yamlMarkup = R"!!(attr1: attrval1
  1488. attr2: attrval2
  1489. binmixed:
  1490. bin: 1
  1491. ^: !binary |-
  1492. CwAAAA==
  1493. binsimple: !binary |-
  1494. CwAAAA==
  1495. element1: !el scalarvalue
  1496. item:
  1497. - a: 1
  1498. b: 2
  1499. c: 3
  1500. d: 4
  1501. - a: 2
  1502. - a: 3
  1503. scalars:
  1504. valX:
  1505. - x
  1506. - x
  1507. valY:
  1508. - y
  1509. - y
  1510. valZ: !el z
  1511. sub1:
  1512. subattr1: sav1
  1513. ^: !el sub1val
  1514. sub2:
  1515. subattr2: sav2
  1516. ^: !el sub2val
  1517. subX:
  1518. subattr3: sav3
  1519. ^: !el subXval
  1520. ^: !el cpptestval
  1521. )!!";
  1522. static constexpr const char * jsonMarkup = R"!!({
  1523. "@attr1": "attrval1",
  1524. "@attr2": "attrval2",
  1525. "binmixed": {
  1526. "@bin": "1",
  1527. "#valuebin": "CwAAAA=="
  1528. },
  1529. "binsimple": {
  1530. "#valuebin": "CwAAAA=="
  1531. },
  1532. "element1": "scalarvalue",
  1533. "item": [
  1534. {
  1535. "@a": "1",
  1536. "@b": "2",
  1537. "@c": "3",
  1538. "@d": "4"
  1539. },
  1540. {
  1541. "@a": "2"
  1542. },
  1543. {
  1544. "@a": "3"
  1545. }
  1546. ],
  1547. "scalars": {
  1548. "valX": [
  1549. "x",
  1550. "x"
  1551. ],
  1552. "valY": [
  1553. "y",
  1554. "y"
  1555. ],
  1556. "valZ": "z"
  1557. },
  1558. "sub1": {
  1559. "@subattr1": "sav1",
  1560. "#value": "sub1val"
  1561. },
  1562. "sub2": {
  1563. "@subattr2": "sav2",
  1564. "#value": "sub2val"
  1565. },
  1566. "subX": {
  1567. "@subattr3": "sav3",
  1568. "#value": "subXval"
  1569. },
  1570. "#value": "cpptestval"
  1571. })!!";
  1572. Owned<IPropertyTree> xml = createPTreeFromXMLString(xmlMarkup, ipt_none, ptr_ignoreWhiteSpace, nullptr);
  1573. Owned<IPropertyTree> yaml = createPTreeFromYAMLString(yamlMarkup, ipt_none, ptr_ignoreWhiteSpace, nullptr);
  1574. Owned<IPropertyTree> json = createPTreeFromJSONString(jsonMarkup, ipt_none, ptr_ignoreWhiteSpace, nullptr);
  1575. CPPUNIT_ASSERT(areMatchingPTrees(xml, yaml));
  1576. CPPUNIT_ASSERT(areMatchingPTrees(xml, json));
  1577. //if we want the final compares to be less fragile (test will have to be updated if formatting changes) we could reparse and compare trees again
  1578. StringBuffer ml;
  1579. toXML(xml, ml, 2, XML_Format|XML_SortTags);
  1580. CPPUNIT_ASSERT(streq(ml, xmlMarkup));
  1581. toYAML(yaml, ml.clear(), 2, YAML_SortTags|YAML_HideRootArrayObject);
  1582. CPPUNIT_ASSERT(streq(ml, yamlMarkup));
  1583. toJSON(json, ml.clear(), 2, JSON_Format|JSON_SortTags|JSON_HideRootArrayObject);
  1584. CPPUNIT_ASSERT(streq(ml, jsonMarkup));
  1585. }
  1586. void test()
  1587. {
  1588. Owned<IPropertyTree> testTree = createPTreeFromXMLString(
  1589. "<cpptest attr1='attrval1' attr2='attrval2'>"
  1590. " <sub1 subattr1='sav1'>sub1val</sub1>"
  1591. " <sub2 subattr2='sav2'>sub2val</sub2>"
  1592. " <subX subattr3='sav3'>subXval</subX>"
  1593. " <item a='1' b='2' c='3' d='4'/>"
  1594. " <item a='2'/>"
  1595. " <item a='3'/>"
  1596. " <array>"
  1597. " <valX>x</valX>"
  1598. " <valX>x</valX>"
  1599. " <valY>y</valY>"
  1600. " <valY>y</valY>"
  1601. " <valZ>z</valZ>"
  1602. " </array>"
  1603. " <binprop bin='1' xsi:type='SOAP-ENC:base64'>CwAAAA==</binprop>"
  1604. "cpptestval"
  1605. "</cpptest>");
  1606. MemoryBuffer mb;
  1607. mb.reserveTruncate(4*1024+1); // Must be > PTREE_COMPRESS_THRESHOLD (see top of jptree.cpp)
  1608. testTree->addProp("binprop/subbinprop", "nonbinval1");
  1609. testTree->addPropBin("binprop/subbinprop", mb.length(), mb.toByteArray());
  1610. testTree->addProp("binprop/subbinprop", "nonbinval2");
  1611. testTree->addPropBin("binprop/subbinprop", mb.length(), mb.toByteArray());
  1612. // test some sets in prep. for 'get' tests
  1613. CPPUNIT_ASSERT(testTree->renameProp("subX", "subY"));
  1614. IPropertyTree *subY = testTree->queryPropTree("subY");
  1615. CPPUNIT_ASSERT(testTree->renameTree(subY, "sub3"));
  1616. IPropertyTree *subtest = testTree->setPropTree("subtest");
  1617. subtest = testTree->addPropTree("subtest", createPTree());
  1618. CPPUNIT_ASSERT(subtest != nullptr);
  1619. subtest = testTree->queryPropTree("subtest[2]");
  1620. CPPUNIT_ASSERT(subtest != nullptr);
  1621. subtest->setProp("str", "str1");
  1622. subtest->addProp("str", "str2");
  1623. subtest->appendProp("str[2]", "-more");
  1624. subtest->setPropBool("bool", true);
  1625. subtest->addPropBool("bool", false);
  1626. subtest->setPropInt("int", 1);
  1627. subtest->addPropInt("int", 2);
  1628. subtest->setPropInt64("int64", 1);
  1629. subtest->addPropInt64("int64", 2);
  1630. mb.clear().append("binstr1");
  1631. subtest->setPropBin("bin", mb.length(), mb.toByteArray());
  1632. mb.clear().append("binstr2");
  1633. subtest->addPropBin("bin", mb.length(), mb.toByteArray());
  1634. mb.clear().append("-more");
  1635. subtest->appendPropBin("bin[1]", mb.length(), mb.toByteArray());
  1636. // position insertion.
  1637. testTree->addProp("newprop", "v1");
  1638. testTree->addProp("newprop", "v2");
  1639. testTree->addProp("newprop[2]", "v3");
  1640. CPPUNIT_ASSERT(streq("v3", testTree->queryProp("newprop[2]")));
  1641. CPPUNIT_ASSERT(testTree->hasProp("sub1"));
  1642. CPPUNIT_ASSERT(testTree->hasProp("sub1/@subattr1"));
  1643. CPPUNIT_ASSERT(testTree->hasProp("sub2/@subattr2"));
  1644. CPPUNIT_ASSERT(testTree->hasProp("@attr1"));
  1645. CPPUNIT_ASSERT(!testTree->isBinary("@attr1"));
  1646. CPPUNIT_ASSERT(!testTree->isBinary("sub1"));
  1647. CPPUNIT_ASSERT(testTree->isBinary("binprop"));
  1648. CPPUNIT_ASSERT(!testTree->isCompressed("binprop"));
  1649. CPPUNIT_ASSERT(!testTree->isBinary("binprop/subbinprop[1]"));
  1650. CPPUNIT_ASSERT(testTree->isBinary("binprop/subbinprop[2]"));
  1651. CPPUNIT_ASSERT(!testTree->isCompressed("binprop/subbinprop[3]"));
  1652. CPPUNIT_ASSERT(testTree->isCompressed("binprop/subbinprop[4]"));
  1653. // testing if subX was renamed correctly
  1654. CPPUNIT_ASSERT(!testTree->hasProp("subX"));
  1655. CPPUNIT_ASSERT(!testTree->hasProp("subY"));
  1656. CPPUNIT_ASSERT(testTree->hasProp("sub3"));
  1657. StringBuffer astr;
  1658. CPPUNIT_ASSERT(testTree->getProp("sub1", astr));
  1659. CPPUNIT_ASSERT(streq("sub1val", astr.str()));
  1660. CPPUNIT_ASSERT(streq("sub2val", testTree->queryProp("sub2")));
  1661. subtest = testTree->queryPropTree("subtest[2]");
  1662. CPPUNIT_ASSERT(subtest != nullptr);
  1663. CPPUNIT_ASSERT(subtest->getPropBool("bool[1]"));
  1664. CPPUNIT_ASSERT(!subtest->getPropBool("bool[2]"));
  1665. CPPUNIT_ASSERT(1 == subtest->getPropInt("int[1]"));
  1666. CPPUNIT_ASSERT(2 == subtest->getPropInt("int[2]"));
  1667. CPPUNIT_ASSERT(1 == subtest->getPropInt64("int64[1]"));
  1668. CPPUNIT_ASSERT(2 == subtest->getPropInt64("int64[2]"));
  1669. subtest->getPropBin("bin[1]", mb.clear());
  1670. const char *ptr = (const char *)mb.toByteArray();
  1671. CPPUNIT_ASSERT(streq("binstr1", ptr)); // NB: null terminator was added at set time.
  1672. CPPUNIT_ASSERT(streq("-more", ptr+strlen("binstr1")+1)); // NB: null terminator was added at set time.
  1673. subtest->getPropBin("bin[2]", mb.clear());
  1674. CPPUNIT_ASSERT(streq("binstr2", mb.toByteArray())); // NB: null terminator was added at set time.
  1675. CPPUNIT_ASSERT(testTree->hasProp("subtest/bin[2]"));
  1676. CPPUNIT_ASSERT(testTree->removeProp("subtest/bin[2]"));
  1677. CPPUNIT_ASSERT(!testTree->hasProp("subtest/bin[2]"));
  1678. CPPUNIT_ASSERT(testTree->hasProp("subtest"));
  1679. CPPUNIT_ASSERT(testTree->removeTree(subtest)); // this is subtest[2]
  1680. subtest = testTree->queryPropTree("subtest"); // now just 1
  1681. CPPUNIT_ASSERT(testTree->removeTree(subtest));
  1682. CPPUNIT_ASSERT(!testTree->hasProp("subtest"));
  1683. IPropertyTree *item3 = testTree->queryPropTree("item[@a='3']");
  1684. CPPUNIT_ASSERT(nullptr != item3);
  1685. CPPUNIT_ASSERT(2 == testTree->queryChildIndex(item3));
  1686. CPPUNIT_ASSERT(streq("item", item3->queryName()));
  1687. Owned<IPropertyTreeIterator> iter = testTree->getElements("item");
  1688. unsigned a=1;
  1689. ForEach(*iter)
  1690. {
  1691. CPPUNIT_ASSERT(a == iter->query().getPropInt("@a"));
  1692. ++a;
  1693. }
  1694. Owned<IAttributeIterator> attrIter = testTree->queryPropTree("item[1]")->getAttributes();
  1695. CPPUNIT_ASSERT(4 == attrIter->count());
  1696. unsigned i = 0;
  1697. ForEach(*attrIter)
  1698. {
  1699. const char *name = attrIter->queryName();
  1700. const char *val = attrIter->queryValue();
  1701. CPPUNIT_ASSERT('a'+i == *(name+1));
  1702. CPPUNIT_ASSERT('1'+i == *val);
  1703. ++i;
  1704. }
  1705. IPropertyTree *array = testTree->queryPropTree("array");
  1706. CPPUNIT_ASSERT(array != nullptr);
  1707. CPPUNIT_ASSERT(array->hasChildren());
  1708. CPPUNIT_ASSERT(3 == array->numUniq());
  1709. CPPUNIT_ASSERT(5 == array->numChildren());
  1710. CPPUNIT_ASSERT(!testTree->isCaseInsensitive());
  1711. CPPUNIT_ASSERT(3 == testTree->getCount("sub*"));
  1712. testTree->addPropInt("newitem", 1);
  1713. testTree->addPropInt("newitem", 2);
  1714. testTree->addPropInt("./newitem", 3);
  1715. testTree->addPropInt("././newitem", 4);
  1716. Owned<IPropertyTreeIterator> xIter = testTree->getElements("./newitem");
  1717. unsigned match=1;
  1718. ForEach(*xIter)
  1719. {
  1720. CPPUNIT_ASSERT(match == xIter->query().getPropInt(nullptr));
  1721. ++match;
  1722. }
  1723. }
  1724. };
  1725. CPPUNIT_TEST_SUITE_REGISTRATION(JlibIPTTest);
  1726. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(JlibIPTTest, "JlibIPTTest");
  1727. #include "jdebug.hpp"
  1728. #include "jmutex.hpp"
  1729. class AtomicTimingTest : public CppUnit::TestFixture
  1730. {
  1731. CPPUNIT_TEST_SUITE(AtomicTimingTest);
  1732. CPPUNIT_TEST(runAllTests);
  1733. CPPUNIT_TEST_SUITE_END();
  1734. public:
  1735. class CasCounter
  1736. {
  1737. public:
  1738. CasCounter() = default;
  1739. CasCounter(unsigned __int64 _value) : value{_value} {}
  1740. operator unsigned __int64() { return value; }
  1741. unsigned __int64 operator = (unsigned __int64 _value)
  1742. {
  1743. value = _value;
  1744. return _value;
  1745. }
  1746. unsigned __int64 operator ++(int)
  1747. {
  1748. unsigned __int64 expected = value.load();
  1749. while (!value.compare_exchange_weak(expected, expected + 1))
  1750. {
  1751. }
  1752. return expected+1;
  1753. }
  1754. std::atomic<unsigned __int64> value = { 0 };
  1755. };
  1756. template <typename LOCK, typename BLOCK, typename COUNTER, unsigned NUMVALUES, unsigned NUMLOCKS>
  1757. class LockTester
  1758. {
  1759. public:
  1760. LockTester()
  1761. {
  1762. value1 = 0;
  1763. }
  1764. class LockTestThread : public Thread
  1765. {
  1766. public:
  1767. LockTestThread(Semaphore & _startSem, Semaphore & _endSem, LOCK & _lock1, COUNTER & _value1, LOCK & _lock2, COUNTER * _extraValues, unsigned _numIterations)
  1768. : startSem(_startSem), endSem(_endSem),
  1769. lock1(_lock1), value1(_value1),
  1770. lock2(_lock2), extraValues(_extraValues),
  1771. numIterations(_numIterations)
  1772. {
  1773. }
  1774. virtual void execute()
  1775. {
  1776. {
  1777. BLOCK block(lock1);
  1778. value1++;
  1779. if (NUMVALUES >= 2)
  1780. extraValues[1]++;
  1781. if (NUMVALUES >= 3)
  1782. extraValues[2]++;
  1783. if (NUMVALUES >= 4)
  1784. extraValues[3]++;
  1785. if (NUMVALUES >= 5)
  1786. extraValues[4]++;
  1787. }
  1788. if (NUMLOCKS == 2)
  1789. {
  1790. BLOCK block(lock2);
  1791. extraValues[1]++;
  1792. }
  1793. }
  1794. virtual int run()
  1795. {
  1796. startSem.wait();
  1797. for (unsigned i = 0; i < numIterations; i++)
  1798. execute();
  1799. endSem.signal();
  1800. return 0;
  1801. }
  1802. protected:
  1803. Semaphore & startSem;
  1804. Semaphore & endSem;
  1805. LOCK & lock1;
  1806. LOCK & lock2;
  1807. COUNTER & value1;
  1808. COUNTER * extraValues;
  1809. const unsigned numIterations;
  1810. };
  1811. unsigned __int64 run(const char * title, unsigned numThreads, unsigned numIterations)
  1812. {
  1813. value1 = 0;
  1814. for (unsigned ix = 1; ix < NUMVALUES; ix++)
  1815. extraValues[ix] = 0;
  1816. for (unsigned i = 0; i < numThreads; i++)
  1817. {
  1818. LockTestThread * next = new LockTestThread(startSem, endSem, lock, value1, lock, extraValues, numIterations);
  1819. threads.append(*next);
  1820. next->start();
  1821. }
  1822. cycle_t startCycles = get_cycles_now();
  1823. startSem.signal(numThreads);
  1824. for (unsigned i2 = 0; i2 < numThreads; i2++)
  1825. endSem.wait();
  1826. cycle_t endCycles = get_cycles_now();
  1827. unsigned __int64 expected = (unsigned __int64)numIterations * numThreads;
  1828. unsigned __int64 averageTime = cycle_to_nanosec(endCycles - startCycles) / (numIterations * numThreads);
  1829. printf("%s@%u/%u threads(%u) %" I64F "uns/iteration lost(%" I64F "d)\n", title, NUMVALUES, NUMLOCKS, numThreads, averageTime, expected - value1);
  1830. for (unsigned i3 = 0; i3 < numThreads; i3++)
  1831. threads.item(i3).join();
  1832. return averageTime;
  1833. }
  1834. protected:
  1835. CIArrayOf<LockTestThread> threads;
  1836. Semaphore startSem;
  1837. Semaphore endSem;
  1838. LOCK lock;
  1839. COUNTER value1;
  1840. COUNTER extraValues[NUMVALUES];
  1841. };
  1842. #define DO_TEST(LOCK, CLOCK, COUNTER, NUMVALUES, NUMLOCKS) \
  1843. { \
  1844. const char * title = #LOCK "," #COUNTER;\
  1845. LockTester<LOCK, CLOCK, COUNTER, NUMVALUES, NUMLOCKS> tester;\
  1846. uncontendedTimes.append(tester.run(title, 1, numIterations));\
  1847. minorTimes.append(tester.run(title, 2, numIterations));\
  1848. typicalTimes.append(tester.run(title, numCores / 2, numIterations));\
  1849. tester.run(title, numCores, numIterations);\
  1850. tester.run(title, numCores + 1, numIterations);\
  1851. contendedTimes.append(tester.run(title, numCores * 2, numIterations));\
  1852. }
  1853. //Use to common out a test
  1854. #define XDO_TEST(LOCK, CLOCK, COUNTER, NUMVALUES, NUMLOCKS) \
  1855. { \
  1856. uncontendedTimes.append(0);\
  1857. minorTimes.append(0);\
  1858. typicalTimes.append(0);\
  1859. contendedTimes.append(0);\
  1860. }
  1861. class Null
  1862. {};
  1863. const unsigned numIterations = 1000000;
  1864. const unsigned numCores = getAffinityCpus();
  1865. void runAllTests()
  1866. {
  1867. DO_TEST(CriticalSection, CriticalBlock, unsigned __int64, 1, 1);
  1868. DO_TEST(CriticalSection, CriticalBlock, unsigned __int64, 2, 1);
  1869. DO_TEST(CriticalSection, CriticalBlock, unsigned __int64, 5, 1);
  1870. DO_TEST(CriticalSection, CriticalBlock, unsigned __int64, 1, 2);
  1871. DO_TEST(SpinLock, SpinBlock, unsigned __int64, 1, 1);
  1872. DO_TEST(SpinLock, SpinBlock, unsigned __int64, 2, 1);
  1873. DO_TEST(SpinLock, SpinBlock, unsigned __int64, 5, 1);
  1874. DO_TEST(SpinLock, SpinBlock, unsigned __int64, 1, 2);
  1875. DO_TEST(Null, Null, std::atomic<unsigned __int64>, 1, 1);
  1876. DO_TEST(Null, Null, std::atomic<unsigned __int64>, 2, 1);
  1877. DO_TEST(Null, Null, std::atomic<unsigned __int64>, 5, 1);
  1878. DO_TEST(Null, Null, std::atomic<unsigned __int64>, 1, 2);
  1879. DO_TEST(Null, Null, RelaxedAtomic<unsigned __int64>, 1, 1);
  1880. DO_TEST(Null, Null, RelaxedAtomic<unsigned __int64>, 5, 1);
  1881. DO_TEST(Null, Null, CasCounter, 1, 1);
  1882. DO_TEST(Null, Null, CasCounter, 5, 1);
  1883. DO_TEST(Null, Null, unsigned __int64, 1, 1);
  1884. DO_TEST(Null, Null, unsigned __int64, 2, 1);
  1885. DO_TEST(Null, Null, unsigned __int64, 5, 1);
  1886. //Read locks will fail to prevent values being lost, but the timings are useful in comparison with CriticalSection
  1887. DO_TEST(ReadWriteLock, ReadLockBlock, unsigned __int64, 1, 1);
  1888. DO_TEST(ReadWriteLock, ReadLockBlock, unsigned __int64, 2, 1);
  1889. DO_TEST(ReadWriteLock, ReadLockBlock, unsigned __int64, 5, 1);
  1890. DO_TEST(ReadWriteLock, ReadLockBlock, unsigned __int64, 1, 2);
  1891. DO_TEST(ReadWriteLock, WriteLockBlock, unsigned __int64, 1, 1);
  1892. DO_TEST(ReadWriteLock, WriteLockBlock, unsigned __int64, 2, 1);
  1893. DO_TEST(ReadWriteLock, WriteLockBlock, unsigned __int64, 5, 1);
  1894. DO_TEST(ReadWriteLock, WriteLockBlock, unsigned __int64, 1, 2);
  1895. printf("Summary\n");
  1896. summariseTimings("Uncontended", uncontendedTimes);
  1897. summariseTimings("Minor", minorTimes);
  1898. summariseTimings("Typical", typicalTimes);
  1899. summariseTimings("Over", contendedTimes);
  1900. }
  1901. void summariseTimings(const char * option, UInt64Array & times)
  1902. {
  1903. printf("%11s 1x: cs(%3" I64F "u) spin(%3" I64F "u) atomic(%3" I64F "u) ratomic(%3" I64F "u) cas(%3" I64F "u) rd(%3" I64F "u) wr(%3" I64F "u) "
  1904. "5x: cs(%3" I64F "u) spin(%3" I64F "u) atomic(%3" I64F "u) ratomic(%3" I64F "u) cas(%3" I64F "u) rd(%3" I64F "u) wr(%3" I64F "u)\n", option,
  1905. times.item(0), times.item(4), times.item(8), times.item(12), times.item(14), times.item(19), times.item(23),
  1906. times.item(2), times.item(6), times.item(10), times.item(13), times.item(15), times.item(21), times.item(25));
  1907. }
  1908. private:
  1909. UInt64Array uncontendedTimes;
  1910. UInt64Array minorTimes;
  1911. UInt64Array typicalTimes;
  1912. UInt64Array contendedTimes;
  1913. };
  1914. CPPUNIT_TEST_SUITE_REGISTRATION(AtomicTimingTest);
  1915. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(AtomicTimingTest, "AtomicTimingTest");
  1916. //=====================================================================================================================
  1917. class MachineInfoTimingTest : public CppUnit::TestFixture
  1918. {
  1919. CPPUNIT_TEST_SUITE(MachineInfoTimingTest);
  1920. CPPUNIT_TEST(runAllTests);
  1921. CPPUNIT_TEST_SUITE_END();
  1922. public:
  1923. void getSystemTiming()
  1924. {
  1925. const unsigned num = 10000;
  1926. CpuInfo temp;
  1927. CCycleTimer timer;
  1928. for (unsigned i=0; i < num; i++)
  1929. temp.getSystemTimes();
  1930. printf("Time to get system cpu activity = %" I64F "uns\n", timer.elapsedNs()/num);
  1931. }
  1932. void getProcessTiming()
  1933. {
  1934. const unsigned num = 10000;
  1935. CpuInfo temp;
  1936. CCycleTimer timer;
  1937. for (unsigned i=0; i < num; i++)
  1938. temp.getProcessTimes();
  1939. printf("Time to get process cpu activity = %" I64F "uns\n", timer.elapsedNs()/num);
  1940. }
  1941. void runAllTests()
  1942. {
  1943. getSystemTiming();
  1944. getSystemTiming(); // Second call seems to be faster - so more representative
  1945. getProcessTiming();
  1946. getProcessTiming(); // Second call seems to be faster - so more representative
  1947. CpuInfo prevSystem;
  1948. CpuInfo prevProcess;
  1949. CpuInfo curProcess(true, false);
  1950. CpuInfo curSystem(false, true);
  1951. volatile unsigned x = 0;
  1952. for (unsigned i=0; i < 10; i++)
  1953. {
  1954. prevProcess = curProcess;
  1955. prevSystem = curSystem;
  1956. curProcess.getProcessTimes();
  1957. curSystem.getSystemTimes();
  1958. CpuInfo deltaProcess = curProcess - prevProcess;
  1959. CpuInfo deltaSystem = curSystem - prevSystem;
  1960. if (deltaSystem.getTotalNs())
  1961. {
  1962. printf(" System: User(%u) System(%u) Total(%u) %u%% Ctx(%" I64F "u) ",
  1963. (unsigned)(deltaSystem.getUserNs() / 1000000), (unsigned)(deltaSystem.getSystemNs() / 1000000), (unsigned)(deltaSystem.getTotalNs() / 1000000),
  1964. (unsigned)((deltaSystem.getUserNs() * 100) / deltaSystem.getTotalNs()), deltaSystem.getNumContextSwitches());
  1965. printf(" Process: User(%u) System(%u) Total(%u) %u%% Ctx(%" I64F "u)\n",
  1966. (unsigned)(deltaProcess.getUserNs() / 1000000), (unsigned)(deltaProcess.getSystemNs() / 1000000), (unsigned)(deltaProcess.getTotalNs() / 1000000),
  1967. (unsigned)((deltaProcess.getUserNs() * 100) / deltaSystem.getTotalNs()), deltaProcess.getNumContextSwitches());
  1968. }
  1969. for (unsigned j=0; j < i*100000000; j++)
  1970. x += j*j;
  1971. Sleep(1000);
  1972. }
  1973. }
  1974. };
  1975. CPPUNIT_TEST_SUITE_REGISTRATION(MachineInfoTimingTest);
  1976. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(MachineInfoTimingTest, "MachineInfoTimingTest");
  1977. class JlibIOTest : public CppUnit::TestFixture
  1978. {
  1979. CPPUNIT_TEST_SUITE(JlibIOTest);
  1980. CPPUNIT_TEST(test);
  1981. CPPUNIT_TEST_SUITE_END();
  1982. public:
  1983. void test()
  1984. {
  1985. unsigned numTestLines = 1000;
  1986. const char *newlines[] = { "\n", "\r\n" };
  1987. for (unsigned pEol=0; pEol<2; pEol++) // twice, once for preserveEols=false, once for preserveEols=true
  1988. {
  1989. for (unsigned nl=0; nl<2; nl++) // twice, once for each type of newline
  1990. {
  1991. const char *testTxt = " : Some random text for test line";
  1992. OwnedIFile iFile = createIFile("JlibIOTest.txt");
  1993. CRC32 writeCrc, readCrc;
  1994. {
  1995. OwnedIFileIO iFileIO = iFile->open(IFOcreate);
  1996. OwnedIFileIOStream stream = createIOStream(iFileIO);
  1997. for (unsigned l=0; l<numTestLines; l++)
  1998. {
  1999. VStringBuffer line("%u%s%s", l+1, testTxt, newlines[nl]);
  2000. stream->write(line.length(), line.str());
  2001. writeCrc.tally(line.length(), line.str());
  2002. }
  2003. }
  2004. {
  2005. OwnedIFileIO iFileIO = iFile->open(IFOread);
  2006. OwnedIFileIOStream stream = createIOStream(iFileIO); // NB: unbuffered
  2007. Owned<IStreamLineReader> lineReader = createLineReader(stream, 0==pEol, strlen(testTxt)); // NB: deliberately make chunkSize small so will end up having to read more
  2008. while (true)
  2009. {
  2010. StringBuffer line;
  2011. if (!lineReader->readLine(line))
  2012. {
  2013. if (pEol==1)
  2014. line.append(newlines[nl]);
  2015. readCrc.tally(line.length(), line.str());
  2016. }
  2017. else
  2018. break;
  2019. }
  2020. }
  2021. CPPUNIT_ASSERT(writeCrc.get() == readCrc.get());
  2022. }
  2023. }
  2024. }
  2025. };
  2026. CPPUNIT_TEST_SUITE_REGISTRATION(JlibIOTest);
  2027. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(JlibIOTest, "JlibIOTest");
  2028. #endif // _USE_CPPUNIT