test_more.py 190 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735
  1. import warnings
  2. from collections import Counter, abc
  3. from collections.abc import Set
  4. from datetime import datetime, timedelta
  5. from decimal import Decimal
  6. from doctest import DocTestSuite
  7. from fractions import Fraction
  8. from functools import partial, reduce
  9. from io import StringIO
  10. from itertools import (
  11. accumulate,
  12. chain,
  13. combinations,
  14. combinations_with_replacement,
  15. count,
  16. cycle,
  17. groupby,
  18. islice,
  19. permutations,
  20. product,
  21. repeat,
  22. )
  23. from operator import add, mul, itemgetter
  24. from pickle import loads, dumps
  25. from random import seed, Random
  26. from statistics import mean
  27. from string import ascii_letters
  28. from sys import version_info
  29. from time import sleep
  30. from traceback import format_exc
  31. from unittest import skipIf, TestCase
  32. import more_itertools as mi
  33. def load_tests(loader, tests, ignore):
  34. # Add the doctests
  35. tests.addTests(DocTestSuite('more_itertools.more'))
  36. return tests
  37. class ChunkedTests(TestCase):
  38. """Tests for ``chunked()``"""
  39. def test_even(self):
  40. """Test when ``n`` divides evenly into the length of the iterable."""
  41. self.assertEqual(
  42. list(mi.chunked('ABCDEF', 3)), [['A', 'B', 'C'], ['D', 'E', 'F']]
  43. )
  44. def test_odd(self):
  45. """Test when ``n`` does not divide evenly into the length of the
  46. iterable.
  47. """
  48. self.assertEqual(
  49. list(mi.chunked('ABCDE', 3)), [['A', 'B', 'C'], ['D', 'E']]
  50. )
  51. def test_none(self):
  52. """Test when ``n`` has the value ``None``."""
  53. self.assertEqual(
  54. list(mi.chunked('ABCDE', None)), [['A', 'B', 'C', 'D', 'E']]
  55. )
  56. def test_strict_false(self):
  57. """Test when ``n`` does not divide evenly into the length of the
  58. iterable and strict is false.
  59. """
  60. self.assertEqual(
  61. list(mi.chunked('ABCDE', 3, strict=False)),
  62. [['A', 'B', 'C'], ['D', 'E']],
  63. )
  64. def test_strict_being_true(self):
  65. """Test when ``n`` does not divide evenly into the length of the
  66. iterable and strict is True (raising an exception).
  67. """
  68. def f():
  69. return list(mi.chunked('ABCDE', 3, strict=True))
  70. self.assertRaisesRegex(ValueError, "iterable is not divisible by n", f)
  71. self.assertEqual(
  72. list(mi.chunked('ABCDEF', 3, strict=True)),
  73. [['A', 'B', 'C'], ['D', 'E', 'F']],
  74. )
  75. def test_strict_being_true_with_size_none(self):
  76. """Test when ``n`` has value ``None`` and the keyword strict is True
  77. (raising an exception).
  78. """
  79. def f():
  80. return list(mi.chunked('ABCDE', None, strict=True))
  81. self.assertRaisesRegex(
  82. ValueError, "n must not be None when using strict mode.", f
  83. )
  84. class FirstTests(TestCase):
  85. def test_many(self):
  86. # Also try it on a generator expression to make sure it works on
  87. # whatever those return, across Python versions.
  88. self.assertEqual(mi.first(x for x in range(4)), 0)
  89. def test_one(self):
  90. self.assertEqual(mi.first([3]), 3)
  91. def test_empty(self):
  92. with self.assertRaises(ValueError):
  93. mi.first([])
  94. def test_default(self):
  95. self.assertEqual(mi.first([], 'boo'), 'boo')
  96. class IterOnlyRange:
  97. """User-defined iterable class which only support __iter__.
  98. >>> r = IterOnlyRange(5)
  99. >>> r[0] # doctest: +SKIP
  100. AttributeError: IterOnlyRange instance has no attribute '__getitem__'
  101. Note: In Python 3, ``TypeError`` will be raised because ``object`` is
  102. inherited implicitly by default.
  103. >>> r[0] # doctest: +SKIP
  104. TypeError: 'IterOnlyRange' object does not support indexing
  105. """
  106. def __init__(self, n):
  107. """Set the length of the range."""
  108. self.n = n
  109. def __iter__(self):
  110. """Works same as range()."""
  111. return iter(range(self.n))
  112. class LastTests(TestCase):
  113. def test_basic(self):
  114. cases = [
  115. (range(4), 3),
  116. (iter(range(4)), 3),
  117. (range(1), 0),
  118. (iter(range(1)), 0),
  119. (IterOnlyRange(5), 4),
  120. ({n: str(n) for n in range(5)}, 4),
  121. ({0: '0', -1: '-1', 2: '-2'}, 2),
  122. ]
  123. for iterable, expected in cases:
  124. with self.subTest(iterable=iterable):
  125. self.assertEqual(mi.last(iterable), expected)
  126. def test_default(self):
  127. for iterable, default, expected in [
  128. (range(1), None, 0),
  129. ([], None, None),
  130. ({}, None, None),
  131. (iter([]), None, None),
  132. ]:
  133. with self.subTest(args=(iterable, default)):
  134. self.assertEqual(mi.last(iterable, default=default), expected)
  135. def test_empty(self):
  136. for iterable in ([], iter(range(0))):
  137. with self.subTest(iterable=iterable):
  138. with self.assertRaises(ValueError):
  139. mi.last(iterable)
  140. class NthOrLastTests(TestCase):
  141. """Tests for ``nth_or_last()``"""
  142. def test_basic(self):
  143. self.assertEqual(mi.nth_or_last(range(3), 1), 1)
  144. self.assertEqual(mi.nth_or_last(range(3), 3), 2)
  145. def test_default_value(self):
  146. default = 42
  147. self.assertEqual(mi.nth_or_last(range(0), 3, default), default)
  148. def test_empty_iterable_no_default(self):
  149. self.assertRaises(ValueError, lambda: mi.nth_or_last(range(0), 0))
  150. class PeekableMixinTests:
  151. """Common tests for ``peekable()`` and ``seekable()`` behavior"""
  152. cls = None
  153. def test_passthrough(self):
  154. """Iterating a peekable without using ``peek()`` or ``prepend()``
  155. should just give the underlying iterable's elements (a trivial test but
  156. useful to set a baseline in case something goes wrong)"""
  157. expected = [1, 2, 3, 4, 5]
  158. actual = list(self.cls(expected))
  159. self.assertEqual(actual, expected)
  160. def test_peek_default(self):
  161. """Make sure passing a default into ``peek()`` works."""
  162. p = self.cls([])
  163. self.assertEqual(p.peek(7), 7)
  164. def test_truthiness(self):
  165. """Make sure a ``peekable`` tests true iff there are items remaining in
  166. the iterable.
  167. """
  168. p = self.cls([])
  169. self.assertFalse(p)
  170. p = self.cls(range(3))
  171. self.assertTrue(p)
  172. def test_simple_peeking(self):
  173. """Make sure ``next`` and ``peek`` advance and don't advance the
  174. iterator, respectively.
  175. """
  176. p = self.cls(range(10))
  177. self.assertEqual(next(p), 0)
  178. self.assertEqual(p.peek(), 1)
  179. self.assertEqual(p.peek(), 1)
  180. self.assertEqual(next(p), 1)
  181. class PeekableTests(PeekableMixinTests, TestCase):
  182. cls = mi.peekable
  183. def test_indexing(self):
  184. """
  185. Indexing into the peekable shouldn't advance the iterator.
  186. """
  187. p = mi.peekable('abcdefghijkl')
  188. # The 0th index is what ``next()`` will return
  189. self.assertEqual(p[0], 'a')
  190. self.assertEqual(next(p), 'a')
  191. # Indexing further into the peekable shouldn't advance the iterator
  192. self.assertEqual(p[2], 'd')
  193. self.assertEqual(next(p), 'b')
  194. # The 0th index moves up with the iterator; the last index follows
  195. self.assertEqual(p[0], 'c')
  196. self.assertEqual(p[9], 'l')
  197. self.assertEqual(next(p), 'c')
  198. self.assertEqual(p[8], 'l')
  199. # Negative indexing should work too
  200. self.assertEqual(p[-2], 'k')
  201. self.assertEqual(p[-9], 'd')
  202. self.assertRaises(IndexError, lambda: p[-10])
  203. def test_slicing(self):
  204. """Slicing the peekable shouldn't advance the iterator."""
  205. seq = list('abcdefghijkl')
  206. p = mi.peekable(seq)
  207. # Slicing the peekable should just be like slicing a re-iterable
  208. self.assertEqual(p[1:4], seq[1:4])
  209. # Advancing the iterator moves the slices up also
  210. self.assertEqual(next(p), 'a')
  211. self.assertEqual(p[1:4], seq[1:][1:4])
  212. # Implicit starts and stop should work
  213. self.assertEqual(p[:5], seq[1:][:5])
  214. self.assertEqual(p[:], seq[1:][:])
  215. # Indexing past the end should work
  216. self.assertEqual(p[:100], seq[1:][:100])
  217. # Steps should work, including negative
  218. self.assertEqual(p[::2], seq[1:][::2])
  219. self.assertEqual(p[::-1], seq[1:][::-1])
  220. def test_slicing_reset(self):
  221. """Test slicing on a fresh iterable each time"""
  222. iterable = ['0', '1', '2', '3', '4', '5']
  223. indexes = list(range(-4, len(iterable) + 4)) + [None]
  224. steps = [1, 2, 3, 4, -1, -2, -3, 4]
  225. for slice_args in product(indexes, indexes, steps):
  226. it = iter(iterable)
  227. p = mi.peekable(it)
  228. next(p)
  229. index = slice(*slice_args)
  230. actual = p[index]
  231. expected = iterable[1:][index]
  232. self.assertEqual(actual, expected, slice_args)
  233. def test_slicing_error(self):
  234. iterable = '01234567'
  235. p = mi.peekable(iter(iterable))
  236. # Prime the cache
  237. p.peek()
  238. old_cache = list(p._cache)
  239. # Illegal slice
  240. with self.assertRaises(ValueError):
  241. p[1:-1:0]
  242. # Neither the cache nor the iteration should be affected
  243. self.assertEqual(old_cache, list(p._cache))
  244. self.assertEqual(list(p), list(iterable))
  245. # prepend() behavior tests
  246. def test_prepend(self):
  247. """Tests interspersed ``prepend()`` and ``next()`` calls"""
  248. it = mi.peekable(range(2))
  249. actual = []
  250. # Test prepend() before next()
  251. it.prepend(10)
  252. actual += [next(it), next(it)]
  253. # Test prepend() between next()s
  254. it.prepend(11)
  255. actual += [next(it), next(it)]
  256. # Test prepend() after source iterable is consumed
  257. it.prepend(12)
  258. actual += [next(it)]
  259. expected = [10, 0, 11, 1, 12]
  260. self.assertEqual(actual, expected)
  261. def test_multi_prepend(self):
  262. """Tests prepending multiple items and getting them in proper order"""
  263. it = mi.peekable(range(5))
  264. actual = [next(it), next(it)]
  265. it.prepend(10, 11, 12)
  266. it.prepend(20, 21)
  267. actual += list(it)
  268. expected = [0, 1, 20, 21, 10, 11, 12, 2, 3, 4]
  269. self.assertEqual(actual, expected)
  270. def test_empty(self):
  271. """Tests prepending in front of an empty iterable"""
  272. it = mi.peekable([])
  273. it.prepend(10)
  274. actual = list(it)
  275. expected = [10]
  276. self.assertEqual(actual, expected)
  277. def test_prepend_truthiness(self):
  278. """Tests that ``__bool__()`` or ``__nonzero__()`` works properly
  279. with ``prepend()``"""
  280. it = mi.peekable(range(5))
  281. self.assertTrue(it)
  282. actual = list(it)
  283. self.assertFalse(it)
  284. it.prepend(10)
  285. self.assertTrue(it)
  286. actual += [next(it)]
  287. self.assertFalse(it)
  288. expected = [0, 1, 2, 3, 4, 10]
  289. self.assertEqual(actual, expected)
  290. def test_multi_prepend_peek(self):
  291. """Tests prepending multiple elements and getting them in reverse order
  292. while peeking"""
  293. it = mi.peekable(range(5))
  294. actual = [next(it), next(it)]
  295. self.assertEqual(it.peek(), 2)
  296. it.prepend(10, 11, 12)
  297. self.assertEqual(it.peek(), 10)
  298. it.prepend(20, 21)
  299. self.assertEqual(it.peek(), 20)
  300. actual += list(it)
  301. self.assertFalse(it)
  302. expected = [0, 1, 20, 21, 10, 11, 12, 2, 3, 4]
  303. self.assertEqual(actual, expected)
  304. def test_prepend_after_stop(self):
  305. """Test resuming iteration after a previous exhaustion"""
  306. it = mi.peekable(range(3))
  307. self.assertEqual(list(it), [0, 1, 2])
  308. self.assertRaises(StopIteration, lambda: next(it))
  309. it.prepend(10)
  310. self.assertEqual(next(it), 10)
  311. self.assertRaises(StopIteration, lambda: next(it))
  312. def test_prepend_slicing(self):
  313. """Tests interaction between prepending and slicing"""
  314. seq = list(range(20))
  315. p = mi.peekable(seq)
  316. p.prepend(30, 40, 50)
  317. pseq = [30, 40, 50] + seq # pseq for prepended_seq
  318. # adapt the specific tests from test_slicing
  319. self.assertEqual(p[0], 30)
  320. self.assertEqual(p[1:8], pseq[1:8])
  321. self.assertEqual(p[1:], pseq[1:])
  322. self.assertEqual(p[:5], pseq[:5])
  323. self.assertEqual(p[:], pseq[:])
  324. self.assertEqual(p[:100], pseq[:100])
  325. self.assertEqual(p[::2], pseq[::2])
  326. self.assertEqual(p[::-1], pseq[::-1])
  327. def test_prepend_indexing(self):
  328. """Tests interaction between prepending and indexing"""
  329. seq = list(range(20))
  330. p = mi.peekable(seq)
  331. p.prepend(30, 40, 50)
  332. self.assertEqual(p[0], 30)
  333. self.assertEqual(next(p), 30)
  334. self.assertEqual(p[2], 0)
  335. self.assertEqual(next(p), 40)
  336. self.assertEqual(p[0], 50)
  337. self.assertEqual(p[9], 8)
  338. self.assertEqual(next(p), 50)
  339. self.assertEqual(p[8], 8)
  340. self.assertEqual(p[-2], 18)
  341. self.assertEqual(p[-9], 11)
  342. self.assertRaises(IndexError, lambda: p[-21])
  343. def test_prepend_iterable(self):
  344. """Tests prepending from an iterable"""
  345. it = mi.peekable(range(5))
  346. # Don't directly use the range() object to avoid any range-specific
  347. # optimizations
  348. it.prepend(*(x for x in range(5)))
  349. actual = list(it)
  350. expected = list(chain(range(5), range(5)))
  351. self.assertEqual(actual, expected)
  352. def test_prepend_many(self):
  353. """Tests that prepending a huge number of elements works"""
  354. it = mi.peekable(range(5))
  355. # Don't directly use the range() object to avoid any range-specific
  356. # optimizations
  357. it.prepend(*(x for x in range(20000)))
  358. actual = list(it)
  359. expected = list(chain(range(20000), range(5)))
  360. self.assertEqual(actual, expected)
  361. def test_prepend_reversed(self):
  362. """Tests prepending from a reversed iterable"""
  363. it = mi.peekable(range(3))
  364. it.prepend(*reversed((10, 11, 12)))
  365. actual = list(it)
  366. expected = [12, 11, 10, 0, 1, 2]
  367. self.assertEqual(actual, expected)
  368. class ConsumerTests(TestCase):
  369. """Tests for ``consumer()``"""
  370. def test_consumer(self):
  371. @mi.consumer
  372. def eater():
  373. while True:
  374. x = yield # noqa
  375. e = eater()
  376. e.send('hi') # without @consumer, would raise TypeError
  377. class DistinctPermutationsTests(TestCase):
  378. def test_distinct_permutations(self):
  379. """Make sure the output for ``distinct_permutations()`` is the same as
  380. set(permutations(it)).
  381. """
  382. iterable = ['z', 'a', 'a', 'q', 'q', 'q', 'y']
  383. test_output = sorted(mi.distinct_permutations(iterable))
  384. ref_output = sorted(set(permutations(iterable)))
  385. self.assertEqual(test_output, ref_output)
  386. def test_other_iterables(self):
  387. """Make sure ``distinct_permutations()`` accepts a different type of
  388. iterables.
  389. """
  390. # a generator
  391. iterable = (c for c in ['z', 'a', 'a', 'q', 'q', 'q', 'y'])
  392. test_output = sorted(mi.distinct_permutations(iterable))
  393. # "reload" it
  394. iterable = (c for c in ['z', 'a', 'a', 'q', 'q', 'q', 'y'])
  395. ref_output = sorted(set(permutations(iterable)))
  396. self.assertEqual(test_output, ref_output)
  397. # an iterator
  398. iterable = iter(['z', 'a', 'a', 'q', 'q', 'q', 'y'])
  399. test_output = sorted(mi.distinct_permutations(iterable))
  400. # "reload" it
  401. iterable = iter(['z', 'a', 'a', 'q', 'q', 'q', 'y'])
  402. ref_output = sorted(set(permutations(iterable)))
  403. self.assertEqual(test_output, ref_output)
  404. def test_r(self):
  405. for iterable, r in (
  406. ('mississippi', 0),
  407. ('mississippi', 1),
  408. ('mississippi', 6),
  409. ('mississippi', 7),
  410. ('mississippi', 12),
  411. ([0, 1, 1, 0], 0),
  412. ([0, 1, 1, 0], 1),
  413. ([0, 1, 1, 0], 2),
  414. ([0, 1, 1, 0], 3),
  415. ([0, 1, 1, 0], 4),
  416. (['a'], 0),
  417. (['a'], 1),
  418. (['a'], 5),
  419. ([], 0),
  420. ([], 1),
  421. ([], 4),
  422. ):
  423. with self.subTest(iterable=iterable, r=r):
  424. expected = sorted(set(permutations(iterable, r)))
  425. actual = sorted(mi.distinct_permutations(iter(iterable), r))
  426. self.assertEqual(actual, expected)
  427. class IlenTests(TestCase):
  428. def test_ilen(self):
  429. """Sanity-checks for ``ilen()``."""
  430. # Non-empty
  431. self.assertEqual(
  432. mi.ilen(filter(lambda x: x % 10 == 0, range(101))), 11
  433. )
  434. # Empty
  435. self.assertEqual(mi.ilen(x for x in range(0)), 0)
  436. # Iterable with __len__
  437. self.assertEqual(mi.ilen(list(range(6))), 6)
  438. class MinMaxTests(TestCase):
  439. def test_basic(self):
  440. for iterable, expected in (
  441. # easy case
  442. ([0, 1, 2, 3], (0, 3)),
  443. # min and max are not in the extremes + we have `int`s and `float`s
  444. ([3, 5.5, -1, 2], (-1, 5.5)),
  445. # unordered collection
  446. ({3, 5.5, -1, 2}, (-1, 5.5)),
  447. # with repetitions
  448. ([3, 5.5, float('-Inf'), 5.5], (float('-Inf'), 5.5)),
  449. # other collections
  450. ('banana', ('a', 'n')),
  451. ({0: 1, 2: 100, 1: 10}, (0, 2)),
  452. (range(3, 14), (3, 13)),
  453. ):
  454. with self.subTest(iterable=iterable, expected=expected):
  455. # check for expected results
  456. self.assertTupleEqual(mi.minmax(iterable), expected)
  457. # check for equality with built-in `min` and `max`
  458. self.assertTupleEqual(
  459. mi.minmax(iterable), (min(iterable), max(iterable))
  460. )
  461. def test_unpacked(self):
  462. self.assertTupleEqual(mi.minmax(2, 3, 1), (1, 3))
  463. self.assertTupleEqual(mi.minmax(12, 3, 4, key=str), (12, 4))
  464. def test_iterables(self):
  465. self.assertTupleEqual(mi.minmax(x for x in [0, 1, 2, 3]), (0, 3))
  466. self.assertTupleEqual(
  467. mi.minmax(map(str, [3, 5.5, 'a', 2])), ('2', 'a')
  468. )
  469. self.assertTupleEqual(
  470. mi.minmax(filter(None, [0, 3, '', None, 10])), (3, 10)
  471. )
  472. def test_key(self):
  473. self.assertTupleEqual(
  474. mi.minmax({(), (1, 4, 2), 'abcde', range(4)}, key=len),
  475. ((), 'abcde'),
  476. )
  477. self.assertTupleEqual(
  478. mi.minmax((x for x in [10, 3, 25]), key=str), (10, 3)
  479. )
  480. def test_default(self):
  481. with self.assertRaises(ValueError):
  482. mi.minmax([])
  483. self.assertIs(mi.minmax([], default=None), None)
  484. self.assertListEqual(mi.minmax([], default=[1, 'a']), [1, 'a'])
  485. class WithIterTests(TestCase):
  486. def test_with_iter(self):
  487. s = StringIO('One fish\nTwo fish')
  488. initial_words = [line.split()[0] for line in mi.with_iter(s)]
  489. # Iterable's items should be faithfully represented
  490. self.assertEqual(initial_words, ['One', 'Two'])
  491. # The file object should be closed
  492. self.assertTrue(s.closed)
  493. class OneTests(TestCase):
  494. def test_basic(self):
  495. it = iter(['item'])
  496. self.assertEqual(mi.one(it), 'item')
  497. def test_too_short(self):
  498. it = iter([])
  499. for too_short, exc_type in [
  500. (None, ValueError),
  501. (IndexError, IndexError),
  502. ]:
  503. with self.subTest(too_short=too_short):
  504. try:
  505. mi.one(it, too_short=too_short)
  506. except exc_type:
  507. formatted_exc = format_exc()
  508. self.assertIn('StopIteration', formatted_exc)
  509. self.assertIn(
  510. 'The above exception was the direct cause',
  511. formatted_exc,
  512. )
  513. else:
  514. self.fail()
  515. def test_too_long(self):
  516. it = count()
  517. self.assertRaises(ValueError, lambda: mi.one(it)) # burn 0 and 1
  518. self.assertEqual(next(it), 2)
  519. self.assertRaises(
  520. OverflowError, lambda: mi.one(it, too_long=OverflowError)
  521. )
  522. def test_too_long_default_message(self):
  523. it = count()
  524. self.assertRaisesRegex(
  525. ValueError,
  526. "Expected exactly one item in "
  527. "iterable, but got 0, 1, and "
  528. "perhaps more.",
  529. lambda: mi.one(it),
  530. )
  531. class IntersperseTest(TestCase):
  532. """Tests for intersperse()"""
  533. def test_even(self):
  534. iterable = (x for x in '01')
  535. self.assertEqual(
  536. list(mi.intersperse(None, iterable)), ['0', None, '1']
  537. )
  538. def test_odd(self):
  539. iterable = (x for x in '012')
  540. self.assertEqual(
  541. list(mi.intersperse(None, iterable)), ['0', None, '1', None, '2']
  542. )
  543. def test_nested(self):
  544. element = ('a', 'b')
  545. iterable = (x for x in '012')
  546. actual = list(mi.intersperse(element, iterable))
  547. expected = ['0', ('a', 'b'), '1', ('a', 'b'), '2']
  548. self.assertEqual(actual, expected)
  549. def test_not_iterable(self):
  550. self.assertRaises(TypeError, lambda: mi.intersperse('x', 1))
  551. def test_n(self):
  552. for n, element, expected in [
  553. (1, '_', ['0', '_', '1', '_', '2', '_', '3', '_', '4', '_', '5']),
  554. (2, '_', ['0', '1', '_', '2', '3', '_', '4', '5']),
  555. (3, '_', ['0', '1', '2', '_', '3', '4', '5']),
  556. (4, '_', ['0', '1', '2', '3', '_', '4', '5']),
  557. (5, '_', ['0', '1', '2', '3', '4', '_', '5']),
  558. (6, '_', ['0', '1', '2', '3', '4', '5']),
  559. (7, '_', ['0', '1', '2', '3', '4', '5']),
  560. (3, ['a', 'b'], ['0', '1', '2', ['a', 'b'], '3', '4', '5']),
  561. ]:
  562. iterable = (x for x in '012345')
  563. actual = list(mi.intersperse(element, iterable, n=n))
  564. self.assertEqual(actual, expected)
  565. def test_n_zero(self):
  566. self.assertRaises(
  567. ValueError, lambda: list(mi.intersperse('x', '012', n=0))
  568. )
  569. class UniqueToEachTests(TestCase):
  570. """Tests for ``unique_to_each()``"""
  571. def test_all_unique(self):
  572. """When all the input iterables are unique the output should match
  573. the input."""
  574. iterables = [[1, 2], [3, 4, 5], [6, 7, 8]]
  575. self.assertEqual(mi.unique_to_each(*iterables), iterables)
  576. def test_duplicates(self):
  577. """When there are duplicates in any of the input iterables that aren't
  578. in the rest, those duplicates should be emitted."""
  579. iterables = ["mississippi", "missouri"]
  580. self.assertEqual(
  581. mi.unique_to_each(*iterables), [['p', 'p'], ['o', 'u', 'r']]
  582. )
  583. def test_mixed(self):
  584. """When the input iterables contain different types the function should
  585. still behave properly"""
  586. iterables = ['x', (i for i in range(3)), [1, 2, 3], tuple()]
  587. self.assertEqual(mi.unique_to_each(*iterables), [['x'], [0], [3], []])
  588. class WindowedTests(TestCase):
  589. def test_basic(self):
  590. iterable = [1, 2, 3, 4, 5]
  591. for n, expected in (
  592. (6, [(1, 2, 3, 4, 5, None)]),
  593. (5, [(1, 2, 3, 4, 5)]),
  594. (4, [(1, 2, 3, 4), (2, 3, 4, 5)]),
  595. (3, [(1, 2, 3), (2, 3, 4), (3, 4, 5)]),
  596. (2, [(1, 2), (2, 3), (3, 4), (4, 5)]),
  597. (1, [(1,), (2,), (3,), (4,), (5,)]),
  598. (0, [()]),
  599. ):
  600. with self.subTest(n=n):
  601. actual = list(mi.windowed(iterable, n))
  602. self.assertEqual(actual, expected)
  603. def test_fillvalue(self):
  604. actual = list(mi.windowed([1, 2, 3, 4, 5], 6, fillvalue='!'))
  605. expected = [(1, 2, 3, 4, 5, '!')]
  606. self.assertEqual(actual, expected)
  607. def test_step(self):
  608. iterable = [1, 2, 3, 4, 5, 6, 7]
  609. for n, step, expected in [
  610. (3, 2, [(1, 2, 3), (3, 4, 5), (5, 6, 7)]), # n > step
  611. (3, 3, [(1, 2, 3), (4, 5, 6), (7, None, None)]), # n == step
  612. (3, 4, [(1, 2, 3), (5, 6, 7)]), # lines up nicely
  613. (3, 5, [(1, 2, 3), (6, 7, None)]), # off by one
  614. (3, 6, [(1, 2, 3), (7, None, None)]), # off by two
  615. (3, 7, [(1, 2, 3)]), # step past the end
  616. (7, 8, [(1, 2, 3, 4, 5, 6, 7)]), # step > len(iterable)
  617. ]:
  618. with self.subTest(n=n, step=step):
  619. actual = list(mi.windowed(iterable, n, step=step))
  620. self.assertEqual(actual, expected)
  621. def test_invalid_step(self):
  622. # Step must be greater than or equal to 1
  623. with self.assertRaises(ValueError):
  624. list(mi.windowed([1, 2, 3, 4, 5], 3, step=0))
  625. def test_fillvalue_step(self):
  626. actual = list(mi.windowed([1, 2, 3, 4, 5], 3, fillvalue='!', step=3))
  627. expected = [(1, 2, 3), (4, 5, '!')]
  628. self.assertEqual(actual, expected)
  629. def test_negative(self):
  630. with self.assertRaises(ValueError):
  631. list(mi.windowed([1, 2, 3, 4, 5], -1))
  632. class SubstringsTests(TestCase):
  633. def test_basic(self):
  634. iterable = (x for x in range(4))
  635. actual = list(mi.substrings(iterable))
  636. expected = [
  637. (0,),
  638. (1,),
  639. (2,),
  640. (3,),
  641. (0, 1),
  642. (1, 2),
  643. (2, 3),
  644. (0, 1, 2),
  645. (1, 2, 3),
  646. (0, 1, 2, 3),
  647. ]
  648. self.assertEqual(actual, expected)
  649. def test_strings(self):
  650. iterable = 'abc'
  651. actual = list(mi.substrings(iterable))
  652. expected = [
  653. ('a',),
  654. ('b',),
  655. ('c',),
  656. ('a', 'b'),
  657. ('b', 'c'),
  658. ('a', 'b', 'c'),
  659. ]
  660. self.assertEqual(actual, expected)
  661. def test_empty(self):
  662. iterable = iter([])
  663. actual = list(mi.substrings(iterable))
  664. expected = []
  665. self.assertEqual(actual, expected)
  666. def test_order(self):
  667. iterable = [2, 0, 1]
  668. actual = list(mi.substrings(iterable))
  669. expected = [(2,), (0,), (1,), (2, 0), (0, 1), (2, 0, 1)]
  670. self.assertEqual(actual, expected)
  671. class SubstringsIndexesTests(TestCase):
  672. def test_basic(self):
  673. sequence = [x for x in range(4)]
  674. actual = list(mi.substrings_indexes(sequence))
  675. expected = [
  676. ([0], 0, 1),
  677. ([1], 1, 2),
  678. ([2], 2, 3),
  679. ([3], 3, 4),
  680. ([0, 1], 0, 2),
  681. ([1, 2], 1, 3),
  682. ([2, 3], 2, 4),
  683. ([0, 1, 2], 0, 3),
  684. ([1, 2, 3], 1, 4),
  685. ([0, 1, 2, 3], 0, 4),
  686. ]
  687. self.assertEqual(actual, expected)
  688. def test_strings(self):
  689. sequence = 'abc'
  690. actual = list(mi.substrings_indexes(sequence))
  691. expected = [
  692. ('a', 0, 1),
  693. ('b', 1, 2),
  694. ('c', 2, 3),
  695. ('ab', 0, 2),
  696. ('bc', 1, 3),
  697. ('abc', 0, 3),
  698. ]
  699. self.assertEqual(actual, expected)
  700. def test_empty(self):
  701. sequence = []
  702. actual = list(mi.substrings_indexes(sequence))
  703. expected = []
  704. self.assertEqual(actual, expected)
  705. def test_order(self):
  706. sequence = [2, 0, 1]
  707. actual = list(mi.substrings_indexes(sequence))
  708. expected = [
  709. ([2], 0, 1),
  710. ([0], 1, 2),
  711. ([1], 2, 3),
  712. ([2, 0], 0, 2),
  713. ([0, 1], 1, 3),
  714. ([2, 0, 1], 0, 3),
  715. ]
  716. self.assertEqual(actual, expected)
  717. def test_reverse(self):
  718. sequence = [2, 0, 1]
  719. actual = list(mi.substrings_indexes(sequence, reverse=True))
  720. expected = [
  721. ([2, 0, 1], 0, 3),
  722. ([2, 0], 0, 2),
  723. ([0, 1], 1, 3),
  724. ([2], 0, 1),
  725. ([0], 1, 2),
  726. ([1], 2, 3),
  727. ]
  728. self.assertEqual(actual, expected)
  729. class BucketTests(TestCase):
  730. def test_basic(self):
  731. iterable = [10, 20, 30, 11, 21, 31, 12, 22, 23, 33]
  732. D = mi.bucket(iterable, key=lambda x: 10 * (x // 10))
  733. # In-order access
  734. self.assertEqual(list(D[10]), [10, 11, 12])
  735. # Out of order access
  736. self.assertEqual(list(D[30]), [30, 31, 33])
  737. self.assertEqual(list(D[20]), [20, 21, 22, 23])
  738. self.assertEqual(list(D[40]), []) # Nothing in here!
  739. def test_in(self):
  740. iterable = [10, 20, 30, 11, 21, 31, 12, 22, 23, 33]
  741. D = mi.bucket(iterable, key=lambda x: 10 * (x // 10))
  742. self.assertIn(10, D)
  743. self.assertNotIn(40, D)
  744. self.assertIn(20, D)
  745. self.assertNotIn(21, D)
  746. # Checking in-ness shouldn't advance the iterator
  747. self.assertEqual(next(D[10]), 10)
  748. def test_validator(self):
  749. iterable = count(0)
  750. key = lambda x: int(str(x)[0]) # First digit of each number
  751. validator = lambda x: 0 < x < 10 # No leading zeros
  752. D = mi.bucket(iterable, key, validator=validator)
  753. self.assertEqual(mi.take(3, D[1]), [1, 10, 11])
  754. self.assertNotIn(0, D) # Non-valid entries don't return True
  755. self.assertNotIn(0, D._cache) # Don't store non-valid entries
  756. self.assertEqual(list(D[0]), [])
  757. def test_list(self):
  758. iterable = [10, 20, 30, 11, 21, 31, 12, 22, 23, 33]
  759. D = mi.bucket(iterable, key=lambda x: 10 * (x // 10))
  760. self.assertEqual(list(D[10]), [10, 11, 12])
  761. self.assertEqual(list(D[20]), [20, 21, 22, 23])
  762. self.assertEqual(list(D[30]), [30, 31, 33])
  763. self.assertEqual(set(D), {10, 20, 30})
  764. def test_list_validator(self):
  765. iterable = [10, 20, 30, 11, 21, 31, 12, 22, 23, 33]
  766. key = lambda x: 10 * (x // 10)
  767. validator = lambda x: x != 20
  768. D = mi.bucket(iterable, key, validator=validator)
  769. self.assertEqual(set(D), {10, 30})
  770. self.assertEqual(list(D[10]), [10, 11, 12])
  771. self.assertEqual(list(D[20]), [])
  772. self.assertEqual(list(D[30]), [30, 31, 33])
  773. class SpyTests(TestCase):
  774. """Tests for ``spy()``"""
  775. def test_basic(self):
  776. original_iterable = iter('abcdefg')
  777. head, new_iterable = mi.spy(original_iterable)
  778. self.assertEqual(head, ['a'])
  779. self.assertEqual(
  780. list(new_iterable), ['a', 'b', 'c', 'd', 'e', 'f', 'g']
  781. )
  782. def test_unpacking(self):
  783. original_iterable = iter('abcdefg')
  784. (first, second, third), new_iterable = mi.spy(original_iterable, 3)
  785. self.assertEqual(first, 'a')
  786. self.assertEqual(second, 'b')
  787. self.assertEqual(third, 'c')
  788. self.assertEqual(
  789. list(new_iterable), ['a', 'b', 'c', 'd', 'e', 'f', 'g']
  790. )
  791. def test_too_many(self):
  792. original_iterable = iter('abc')
  793. head, new_iterable = mi.spy(original_iterable, 4)
  794. self.assertEqual(head, ['a', 'b', 'c'])
  795. self.assertEqual(list(new_iterable), ['a', 'b', 'c'])
  796. def test_zero(self):
  797. original_iterable = iter('abc')
  798. head, new_iterable = mi.spy(original_iterable, 0)
  799. self.assertEqual(head, [])
  800. self.assertEqual(list(new_iterable), ['a', 'b', 'c'])
  801. def test_immutable(self):
  802. original_iterable = iter('abcdefg')
  803. head, new_iterable = mi.spy(original_iterable, 3)
  804. head[0] = 'A'
  805. self.assertEqual(head, ['A', 'b', 'c'])
  806. self.assertEqual(
  807. list(new_iterable), ['a', 'b', 'c', 'd', 'e', 'f', 'g']
  808. )
  809. class InterleaveTests(TestCase):
  810. def test_even(self):
  811. actual = list(mi.interleave([1, 4, 7], [2, 5, 8], [3, 6, 9]))
  812. expected = [1, 2, 3, 4, 5, 6, 7, 8, 9]
  813. self.assertEqual(actual, expected)
  814. def test_short(self):
  815. actual = list(mi.interleave([1, 4], [2, 5, 7], [3, 6, 8]))
  816. expected = [1, 2, 3, 4, 5, 6]
  817. self.assertEqual(actual, expected)
  818. def test_mixed_types(self):
  819. it_list = ['a', 'b', 'c', 'd']
  820. it_str = '12345'
  821. it_inf = count()
  822. actual = list(mi.interleave(it_list, it_str, it_inf))
  823. expected = ['a', '1', 0, 'b', '2', 1, 'c', '3', 2, 'd', '4', 3]
  824. self.assertEqual(actual, expected)
  825. class InterleaveLongestTests(TestCase):
  826. def test_even(self):
  827. actual = list(mi.interleave_longest([1, 4, 7], [2, 5, 8], [3, 6, 9]))
  828. expected = [1, 2, 3, 4, 5, 6, 7, 8, 9]
  829. self.assertEqual(actual, expected)
  830. def test_short(self):
  831. actual = list(mi.interleave_longest([1, 4], [2, 5, 7], [3, 6, 8]))
  832. expected = [1, 2, 3, 4, 5, 6, 7, 8]
  833. self.assertEqual(actual, expected)
  834. def test_mixed_types(self):
  835. it_list = ['a', 'b', 'c', 'd']
  836. it_str = '12345'
  837. it_gen = (x for x in range(3))
  838. actual = list(mi.interleave_longest(it_list, it_str, it_gen))
  839. expected = ['a', '1', 0, 'b', '2', 1, 'c', '3', 2, 'd', '4', '5']
  840. self.assertEqual(actual, expected)
  841. class InterleaveEvenlyTests(TestCase):
  842. def test_equal_lengths(self):
  843. # when lengths are equal, the relative order shouldn't change
  844. a = [1, 2, 3]
  845. b = [5, 6, 7]
  846. actual = list(mi.interleave_evenly([a, b]))
  847. expected = [1, 5, 2, 6, 3, 7]
  848. self.assertEqual(actual, expected)
  849. def test_proportional(self):
  850. # easy case where the iterables have proportional length
  851. a = [1, 2, 3, 4]
  852. b = [5, 6]
  853. actual = list(mi.interleave_evenly([a, b]))
  854. expected = [1, 2, 5, 3, 4, 6]
  855. self.assertEqual(actual, expected)
  856. # swapping a and b should yield the same result
  857. actual_swapped = list(mi.interleave_evenly([b, a]))
  858. self.assertEqual(actual_swapped, expected)
  859. def test_not_proportional(self):
  860. a = [1, 2, 3, 4, 5, 6, 7]
  861. b = [8, 9, 10]
  862. expected = [1, 2, 8, 3, 4, 9, 5, 6, 10, 7]
  863. actual = list(mi.interleave_evenly([a, b]))
  864. self.assertEqual(actual, expected)
  865. def test_degenerate_one(self):
  866. a = [0, 1, 2, 3, 4]
  867. b = [5]
  868. expected = [0, 1, 2, 5, 3, 4]
  869. actual = list(mi.interleave_evenly([a, b]))
  870. self.assertEqual(actual, expected)
  871. def test_degenerate_empty(self):
  872. a = [1, 2, 3]
  873. b = []
  874. expected = [1, 2, 3]
  875. actual = list(mi.interleave_evenly([a, b]))
  876. self.assertEqual(actual, expected)
  877. def test_three_iters(self):
  878. a = ["a1", "a2", "a3", "a4", "a5"]
  879. b = ["b1", "b2", "b3"]
  880. c = ["c1"]
  881. actual = list(mi.interleave_evenly([a, b, c]))
  882. expected = ["a1", "b1", "a2", "c1", "a3", "b2", "a4", "b3", "a5"]
  883. self.assertEqual(actual, expected)
  884. def test_many_iters(self):
  885. # smoke test with many iterables: create iterables with a random
  886. # number of elements starting with a character ("a0", "a1", ...)
  887. rng = Random(0)
  888. iterables = []
  889. for ch in ascii_letters:
  890. length = rng.randint(0, 100)
  891. iterable = [f"{ch}{i}" for i in range(length)]
  892. iterables.append(iterable)
  893. interleaved = list(mi.interleave_evenly(iterables))
  894. # for each iterable, check that the result contains all its items
  895. for iterable, ch_expect in zip(iterables, ascii_letters):
  896. interleaved_actual = [
  897. e for e in interleaved if e.startswith(ch_expect)
  898. ]
  899. assert len(set(interleaved_actual)) == len(iterable)
  900. def test_manual_lengths(self):
  901. a = combinations(range(4), 2)
  902. len_a = 4 * (4 - 1) // 2 # == 6
  903. b = combinations(range(4), 3)
  904. len_b = 4
  905. expected = [
  906. (0, 1),
  907. (0, 1, 2),
  908. (0, 2),
  909. (0, 3),
  910. (0, 1, 3),
  911. (1, 2),
  912. (0, 2, 3),
  913. (1, 3),
  914. (2, 3),
  915. (1, 2, 3),
  916. ]
  917. actual = list(mi.interleave_evenly([a, b], lengths=[len_a, len_b]))
  918. self.assertEqual(expected, actual)
  919. def test_no_length_raises(self):
  920. # combinations doesn't have __len__, should trigger ValueError
  921. iterables = [range(5), combinations(range(5), 2)]
  922. with self.assertRaises(ValueError):
  923. list(mi.interleave_evenly(iterables))
  924. def test_argument_mismatch_raises(self):
  925. # pass mismatching number of iterables and lengths
  926. iterables = [range(3)]
  927. lengths = [3, 4]
  928. with self.assertRaises(ValueError):
  929. list(mi.interleave_evenly(iterables, lengths=lengths))
  930. class TestCollapse(TestCase):
  931. """Tests for ``collapse()``"""
  932. def test_collapse(self):
  933. l = [[1], 2, [[3], 4], [[[5]]]]
  934. self.assertEqual(list(mi.collapse(l)), [1, 2, 3, 4, 5])
  935. def test_collapse_to_string(self):
  936. l = [["s1"], "s2", [["s3"], "s4"], [[["s5"]]]]
  937. self.assertEqual(list(mi.collapse(l)), ["s1", "s2", "s3", "s4", "s5"])
  938. def test_collapse_to_bytes(self):
  939. l = [[b"s1"], b"s2", [[b"s3"], b"s4"], [[[b"s5"]]]]
  940. self.assertEqual(
  941. list(mi.collapse(l)), [b"s1", b"s2", b"s3", b"s4", b"s5"]
  942. )
  943. def test_collapse_flatten(self):
  944. l = [[1], [2], [[3], 4], [[[5]]]]
  945. self.assertEqual(list(mi.collapse(l, levels=1)), list(mi.flatten(l)))
  946. def test_collapse_to_level(self):
  947. l = [[1], 2, [[3], 4], [[[5]]]]
  948. self.assertEqual(list(mi.collapse(l, levels=2)), [1, 2, 3, 4, [5]])
  949. self.assertEqual(
  950. list(mi.collapse(mi.collapse(l, levels=1), levels=1)),
  951. list(mi.collapse(l, levels=2)),
  952. )
  953. def test_collapse_to_list(self):
  954. l = (1, [2], (3, [4, (5,)], 'ab'))
  955. actual = list(mi.collapse(l, base_type=list))
  956. expected = [1, [2], 3, [4, (5,)], 'ab']
  957. self.assertEqual(actual, expected)
  958. class SideEffectTests(TestCase):
  959. """Tests for ``side_effect()``"""
  960. def test_individual(self):
  961. # The function increments the counter for each call
  962. counter = [0]
  963. def func(arg):
  964. counter[0] += 1
  965. result = list(mi.side_effect(func, range(10)))
  966. self.assertEqual(result, list(range(10)))
  967. self.assertEqual(counter[0], 10)
  968. def test_chunked(self):
  969. # The function increments the counter for each call
  970. counter = [0]
  971. def func(arg):
  972. counter[0] += 1
  973. result = list(mi.side_effect(func, range(10), 2))
  974. self.assertEqual(result, list(range(10)))
  975. self.assertEqual(counter[0], 5)
  976. def test_before_after(self):
  977. f = StringIO()
  978. collector = []
  979. def func(item):
  980. print(item, file=f)
  981. collector.append(f.getvalue())
  982. def it():
  983. yield 'a'
  984. yield 'b'
  985. raise RuntimeError('kaboom')
  986. before = lambda: print('HEADER', file=f)
  987. after = f.close
  988. try:
  989. mi.consume(mi.side_effect(func, it(), before=before, after=after))
  990. except RuntimeError:
  991. pass
  992. # The iterable should have been written to the file
  993. self.assertEqual(collector, ['HEADER\na\n', 'HEADER\na\nb\n'])
  994. # The file should be closed even though something bad happened
  995. self.assertTrue(f.closed)
  996. def test_before_fails(self):
  997. f = StringIO()
  998. func = lambda x: print(x, file=f)
  999. def before():
  1000. raise RuntimeError('ouch')
  1001. try:
  1002. mi.consume(
  1003. mi.side_effect(func, 'abc', before=before, after=f.close)
  1004. )
  1005. except RuntimeError:
  1006. pass
  1007. # The file should be closed even though something bad happened in the
  1008. # before function
  1009. self.assertTrue(f.closed)
  1010. class SlicedTests(TestCase):
  1011. """Tests for ``sliced()``"""
  1012. def test_even(self):
  1013. """Test when the length of the sequence is divisible by *n*"""
  1014. seq = 'ABCDEFGHI'
  1015. self.assertEqual(list(mi.sliced(seq, 3)), ['ABC', 'DEF', 'GHI'])
  1016. def test_odd(self):
  1017. """Test when the length of the sequence is not divisible by *n*"""
  1018. seq = 'ABCDEFGHI'
  1019. self.assertEqual(list(mi.sliced(seq, 4)), ['ABCD', 'EFGH', 'I'])
  1020. def test_not_sliceable(self):
  1021. seq = (x for x in 'ABCDEFGHI')
  1022. with self.assertRaises(TypeError):
  1023. list(mi.sliced(seq, 3))
  1024. def test_odd_and_strict(self):
  1025. seq = [x for x in 'ABCDEFGHI']
  1026. with self.assertRaises(ValueError):
  1027. list(mi.sliced(seq, 4, strict=True))
  1028. def test_numpy_like_array(self):
  1029. # Numpy arrays don't behave like Python lists - calling bool()
  1030. # on them doesn't return False for empty lists and True for non-empty
  1031. # ones. Emulate that behavior.
  1032. class FalseList(list):
  1033. def __getitem__(self, key):
  1034. ret = super().__getitem__(key)
  1035. if isinstance(key, slice):
  1036. return FalseList(ret)
  1037. return ret
  1038. def __bool__(self):
  1039. return False
  1040. seq = FalseList(range(9))
  1041. actual = list(mi.sliced(seq, 3))
  1042. expected = [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
  1043. self.assertEqual(actual, expected)
  1044. class SplitAtTests(TestCase):
  1045. def test_basic(self):
  1046. for iterable, separator in [
  1047. ('a,bb,ccc,dddd', ','),
  1048. (',a,bb,ccc,dddd', ','),
  1049. ('a,bb,ccc,dddd,', ','),
  1050. ('a,bb,ccc,,dddd', ','),
  1051. ('', ','),
  1052. (',', ','),
  1053. ('a,bb,ccc,dddd', ';'),
  1054. ]:
  1055. with self.subTest(iterable=iterable, separator=separator):
  1056. it = iter(iterable)
  1057. pred = lambda x: x == separator
  1058. actual = [''.join(x) for x in mi.split_at(it, pred)]
  1059. expected = iterable.split(separator)
  1060. self.assertEqual(actual, expected)
  1061. def test_maxsplit(self):
  1062. iterable = 'a,bb,ccc,dddd'
  1063. separator = ','
  1064. pred = lambda x: x == separator
  1065. for maxsplit in range(-1, 4):
  1066. with self.subTest(maxsplit=maxsplit):
  1067. it = iter(iterable)
  1068. result = mi.split_at(it, pred, maxsplit=maxsplit)
  1069. actual = [''.join(x) for x in result]
  1070. expected = iterable.split(separator, maxsplit)
  1071. self.assertEqual(actual, expected)
  1072. def test_keep_separator(self):
  1073. separator = ','
  1074. pred = lambda x: x == separator
  1075. for iterable, expected in [
  1076. ('a,bb,ccc', ['a', ',', 'bb', ',', 'ccc']),
  1077. (',a,bb,ccc', ['', ',', 'a', ',', 'bb', ',', 'ccc']),
  1078. ('a,bb,ccc,', ['a', ',', 'bb', ',', 'ccc', ',', '']),
  1079. ]:
  1080. with self.subTest(iterable=iterable):
  1081. it = iter(iterable)
  1082. result = mi.split_at(it, pred, keep_separator=True)
  1083. actual = [''.join(x) for x in result]
  1084. self.assertEqual(actual, expected)
  1085. def test_combination(self):
  1086. iterable = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  1087. pred = lambda x: x % 3 == 0
  1088. actual = list(
  1089. mi.split_at(iterable, pred, maxsplit=2, keep_separator=True)
  1090. )
  1091. expected = [[1, 2], [3], [4, 5], [6], [7, 8, 9, 10]]
  1092. self.assertEqual(actual, expected)
  1093. class SplitBeforeTest(TestCase):
  1094. """Tests for ``split_before()``"""
  1095. def test_starts_with_sep(self):
  1096. actual = list(mi.split_before('xooxoo', lambda c: c == 'x'))
  1097. expected = [['x', 'o', 'o'], ['x', 'o', 'o']]
  1098. self.assertEqual(actual, expected)
  1099. def test_ends_with_sep(self):
  1100. actual = list(mi.split_before('ooxoox', lambda c: c == 'x'))
  1101. expected = [['o', 'o'], ['x', 'o', 'o'], ['x']]
  1102. self.assertEqual(actual, expected)
  1103. def test_no_sep(self):
  1104. actual = list(mi.split_before('ooo', lambda c: c == 'x'))
  1105. expected = [['o', 'o', 'o']]
  1106. self.assertEqual(actual, expected)
  1107. def test_empty_collection(self):
  1108. actual = list(mi.split_before([], lambda c: bool(c)))
  1109. expected = []
  1110. self.assertEqual(actual, expected)
  1111. def test_max_split(self):
  1112. for args, expected in [
  1113. (
  1114. ('a,b,c,d', lambda c: c == ',', -1),
  1115. [['a'], [',', 'b'], [',', 'c'], [',', 'd']],
  1116. ),
  1117. (
  1118. ('a,b,c,d', lambda c: c == ',', 0),
  1119. [['a', ',', 'b', ',', 'c', ',', 'd']],
  1120. ),
  1121. (
  1122. ('a,b,c,d', lambda c: c == ',', 1),
  1123. [['a'], [',', 'b', ',', 'c', ',', 'd']],
  1124. ),
  1125. (
  1126. ('a,b,c,d', lambda c: c == ',', 2),
  1127. [['a'], [',', 'b'], [',', 'c', ',', 'd']],
  1128. ),
  1129. (
  1130. ('a,b,c,d', lambda c: c == ',', 10),
  1131. [['a'], [',', 'b'], [',', 'c'], [',', 'd']],
  1132. ),
  1133. (
  1134. ('a,b,c,d', lambda c: c == '@', 2),
  1135. [['a', ',', 'b', ',', 'c', ',', 'd']],
  1136. ),
  1137. (
  1138. ('a,b,c,d', lambda c: c != ',', 2),
  1139. [['a', ','], ['b', ','], ['c', ',', 'd']],
  1140. ),
  1141. ]:
  1142. actual = list(mi.split_before(*args))
  1143. self.assertEqual(actual, expected)
  1144. class SplitAfterTest(TestCase):
  1145. """Tests for ``split_after()``"""
  1146. def test_starts_with_sep(self):
  1147. actual = list(mi.split_after('xooxoo', lambda c: c == 'x'))
  1148. expected = [['x'], ['o', 'o', 'x'], ['o', 'o']]
  1149. self.assertEqual(actual, expected)
  1150. def test_ends_with_sep(self):
  1151. actual = list(mi.split_after('ooxoox', lambda c: c == 'x'))
  1152. expected = [['o', 'o', 'x'], ['o', 'o', 'x']]
  1153. self.assertEqual(actual, expected)
  1154. def test_no_sep(self):
  1155. actual = list(mi.split_after('ooo', lambda c: c == 'x'))
  1156. expected = [['o', 'o', 'o']]
  1157. self.assertEqual(actual, expected)
  1158. def test_max_split(self):
  1159. for args, expected in [
  1160. (
  1161. ('a,b,c,d', lambda c: c == ',', -1),
  1162. [['a', ','], ['b', ','], ['c', ','], ['d']],
  1163. ),
  1164. (
  1165. ('a,b,c,d', lambda c: c == ',', 0),
  1166. [['a', ',', 'b', ',', 'c', ',', 'd']],
  1167. ),
  1168. (
  1169. ('a,b,c,d', lambda c: c == ',', 1),
  1170. [['a', ','], ['b', ',', 'c', ',', 'd']],
  1171. ),
  1172. (
  1173. ('a,b,c,d', lambda c: c == ',', 2),
  1174. [['a', ','], ['b', ','], ['c', ',', 'd']],
  1175. ),
  1176. (
  1177. ('a,b,c,d', lambda c: c == ',', 10),
  1178. [['a', ','], ['b', ','], ['c', ','], ['d']],
  1179. ),
  1180. (
  1181. ('a,b,c,d', lambda c: c == '@', 2),
  1182. [['a', ',', 'b', ',', 'c', ',', 'd']],
  1183. ),
  1184. (
  1185. ('a,b,c,d', lambda c: c != ',', 2),
  1186. [['a'], [',', 'b'], [',', 'c', ',', 'd']],
  1187. ),
  1188. (
  1189. ([1], lambda x: x == 1, 1),
  1190. [[1]],
  1191. ),
  1192. ]:
  1193. actual = list(mi.split_after(*args))
  1194. self.assertEqual(actual, expected)
  1195. class SplitWhenTests(TestCase):
  1196. """Tests for ``split_when()``"""
  1197. @staticmethod
  1198. def _split_when_before(iterable, pred):
  1199. return mi.split_when(iterable, lambda _, c: pred(c))
  1200. @staticmethod
  1201. def _split_when_after(iterable, pred):
  1202. return mi.split_when(iterable, lambda c, _: pred(c))
  1203. # split_before emulation
  1204. def test_before_emulation_starts_with_sep(self):
  1205. actual = list(self._split_when_before('xooxoo', lambda c: c == 'x'))
  1206. expected = [['x', 'o', 'o'], ['x', 'o', 'o']]
  1207. self.assertEqual(actual, expected)
  1208. def test_before_emulation_ends_with_sep(self):
  1209. actual = list(self._split_when_before('ooxoox', lambda c: c == 'x'))
  1210. expected = [['o', 'o'], ['x', 'o', 'o'], ['x']]
  1211. self.assertEqual(actual, expected)
  1212. def test_before_emulation_no_sep(self):
  1213. actual = list(self._split_when_before('ooo', lambda c: c == 'x'))
  1214. expected = [['o', 'o', 'o']]
  1215. self.assertEqual(actual, expected)
  1216. # split_after emulation
  1217. def test_after_emulation_starts_with_sep(self):
  1218. actual = list(self._split_when_after('xooxoo', lambda c: c == 'x'))
  1219. expected = [['x'], ['o', 'o', 'x'], ['o', 'o']]
  1220. self.assertEqual(actual, expected)
  1221. def test_after_emulation_ends_with_sep(self):
  1222. actual = list(self._split_when_after('ooxoox', lambda c: c == 'x'))
  1223. expected = [['o', 'o', 'x'], ['o', 'o', 'x']]
  1224. self.assertEqual(actual, expected)
  1225. def test_after_emulation_no_sep(self):
  1226. actual = list(self._split_when_after('ooo', lambda c: c == 'x'))
  1227. expected = [['o', 'o', 'o']]
  1228. self.assertEqual(actual, expected)
  1229. # edge cases
  1230. def test_empty_iterable(self):
  1231. actual = list(mi.split_when('', lambda a, b: a != b))
  1232. expected = []
  1233. self.assertEqual(actual, expected)
  1234. def test_one_element(self):
  1235. actual = list(mi.split_when('o', lambda a, b: a == b))
  1236. expected = [['o']]
  1237. self.assertEqual(actual, expected)
  1238. def test_one_element_is_second_item(self):
  1239. actual = list(self._split_when_before('x', lambda c: c == 'x'))
  1240. expected = [['x']]
  1241. self.assertEqual(actual, expected)
  1242. def test_one_element_is_first_item(self):
  1243. actual = list(self._split_when_after('x', lambda c: c == 'x'))
  1244. expected = [['x']]
  1245. self.assertEqual(actual, expected)
  1246. def test_max_split(self):
  1247. for args, expected in [
  1248. (
  1249. ('a,b,c,d', lambda a, _: a == ',', -1),
  1250. [['a', ','], ['b', ','], ['c', ','], ['d']],
  1251. ),
  1252. (
  1253. ('a,b,c,d', lambda a, _: a == ',', 0),
  1254. [['a', ',', 'b', ',', 'c', ',', 'd']],
  1255. ),
  1256. (
  1257. ('a,b,c,d', lambda _, b: b == ',', 1),
  1258. [['a'], [',', 'b', ',', 'c', ',', 'd']],
  1259. ),
  1260. (
  1261. ('a,b,c,d', lambda a, _: a == ',', 2),
  1262. [['a', ','], ['b', ','], ['c', ',', 'd']],
  1263. ),
  1264. (
  1265. ('0124376', lambda a, b: a > b, -1),
  1266. [['0', '1', '2', '4'], ['3', '7'], ['6']],
  1267. ),
  1268. (
  1269. ('0124376', lambda a, b: a > b, 0),
  1270. [['0', '1', '2', '4', '3', '7', '6']],
  1271. ),
  1272. (
  1273. ('0124376', lambda a, b: a > b, 1),
  1274. [['0', '1', '2', '4'], ['3', '7', '6']],
  1275. ),
  1276. (
  1277. ('0124376', lambda a, b: a > b, 2),
  1278. [['0', '1', '2', '4'], ['3', '7'], ['6']],
  1279. ),
  1280. ]:
  1281. actual = list(mi.split_when(*args))
  1282. self.assertEqual(actual, expected, str(args))
  1283. class SplitIntoTests(TestCase):
  1284. """Tests for ``split_into()``"""
  1285. def test_iterable_just_right(self):
  1286. """Size of ``iterable`` equals the sum of ``sizes``."""
  1287. iterable = [1, 2, 3, 4, 5, 6, 7, 8, 9]
  1288. sizes = [2, 3, 4]
  1289. expected = [[1, 2], [3, 4, 5], [6, 7, 8, 9]]
  1290. actual = list(mi.split_into(iterable, sizes))
  1291. self.assertEqual(actual, expected)
  1292. def test_iterable_too_small(self):
  1293. """Size of ``iterable`` is smaller than sum of ``sizes``. Last return
  1294. list is shorter as a result."""
  1295. iterable = [1, 2, 3, 4, 5, 6, 7]
  1296. sizes = [2, 3, 4]
  1297. expected = [[1, 2], [3, 4, 5], [6, 7]]
  1298. actual = list(mi.split_into(iterable, sizes))
  1299. self.assertEqual(actual, expected)
  1300. def test_iterable_too_small_extra(self):
  1301. """Size of ``iterable`` is smaller than sum of ``sizes``. Second last
  1302. return list is shorter and last return list is empty as a result."""
  1303. iterable = [1, 2, 3, 4, 5, 6, 7]
  1304. sizes = [2, 3, 4, 5]
  1305. expected = [[1, 2], [3, 4, 5], [6, 7], []]
  1306. actual = list(mi.split_into(iterable, sizes))
  1307. self.assertEqual(actual, expected)
  1308. def test_iterable_too_large(self):
  1309. """Size of ``iterable`` is larger than sum of ``sizes``. Not all
  1310. items of iterable are returned."""
  1311. iterable = [1, 2, 3, 4, 5, 6, 7, 8, 9]
  1312. sizes = [2, 3, 2]
  1313. expected = [[1, 2], [3, 4, 5], [6, 7]]
  1314. actual = list(mi.split_into(iterable, sizes))
  1315. self.assertEqual(actual, expected)
  1316. def test_using_none_with_leftover(self):
  1317. """Last item of ``sizes`` is None when items still remain in
  1318. ``iterable``. Last list returned stretches to fit all remaining items
  1319. of ``iterable``."""
  1320. iterable = [1, 2, 3, 4, 5, 6, 7, 8, 9]
  1321. sizes = [2, 3, None]
  1322. expected = [[1, 2], [3, 4, 5], [6, 7, 8, 9]]
  1323. actual = list(mi.split_into(iterable, sizes))
  1324. self.assertEqual(actual, expected)
  1325. def test_using_none_without_leftover(self):
  1326. """Last item of ``sizes`` is None when no items remain in
  1327. ``iterable``. Last list returned is empty."""
  1328. iterable = [1, 2, 3, 4, 5, 6, 7, 8, 9]
  1329. sizes = [2, 3, 4, None]
  1330. expected = [[1, 2], [3, 4, 5], [6, 7, 8, 9], []]
  1331. actual = list(mi.split_into(iterable, sizes))
  1332. self.assertEqual(actual, expected)
  1333. def test_using_none_mid_sizes(self):
  1334. """None is present in ``sizes`` but is not the last item. Last list
  1335. returned stretches to fit all remaining items of ``iterable`` but
  1336. all items in ``sizes`` after None are ignored."""
  1337. iterable = [1, 2, 3, 4, 5, 6, 7, 8, 9]
  1338. sizes = [2, 3, None, 4]
  1339. expected = [[1, 2], [3, 4, 5], [6, 7, 8, 9]]
  1340. actual = list(mi.split_into(iterable, sizes))
  1341. self.assertEqual(actual, expected)
  1342. def test_iterable_empty(self):
  1343. """``iterable`` argument is empty but ``sizes`` is not. An empty
  1344. list is returned for each item in ``sizes``."""
  1345. iterable = []
  1346. sizes = [2, 4, 2]
  1347. expected = [[], [], []]
  1348. actual = list(mi.split_into(iterable, sizes))
  1349. self.assertEqual(actual, expected)
  1350. def test_iterable_empty_using_none(self):
  1351. """``iterable`` argument is empty but ``sizes`` is not. An empty
  1352. list is returned for each item in ``sizes`` that is not after a
  1353. None item."""
  1354. iterable = []
  1355. sizes = [2, 4, None, 2]
  1356. expected = [[], [], []]
  1357. actual = list(mi.split_into(iterable, sizes))
  1358. self.assertEqual(actual, expected)
  1359. def test_sizes_empty(self):
  1360. """``sizes`` argument is empty but ``iterable`` is not. An empty
  1361. generator is returned."""
  1362. iterable = [1, 2, 3, 4, 5, 6, 7, 8, 9]
  1363. sizes = []
  1364. expected = []
  1365. actual = list(mi.split_into(iterable, sizes))
  1366. self.assertEqual(actual, expected)
  1367. def test_both_empty(self):
  1368. """Both ``sizes`` and ``iterable`` arguments are empty. An empty
  1369. generator is returned."""
  1370. iterable = []
  1371. sizes = []
  1372. expected = []
  1373. actual = list(mi.split_into(iterable, sizes))
  1374. self.assertEqual(actual, expected)
  1375. def test_bool_in_sizes(self):
  1376. """A bool object is present in ``sizes`` is treated as a 1 or 0 for
  1377. ``True`` or ``False`` due to bool being an instance of int."""
  1378. iterable = [1, 2, 3, 4, 5, 6, 7, 8, 9]
  1379. sizes = [3, True, 2, False]
  1380. expected = [[1, 2, 3], [4], [5, 6], []]
  1381. actual = list(mi.split_into(iterable, sizes))
  1382. self.assertEqual(actual, expected)
  1383. def test_invalid_in_sizes(self):
  1384. """A ValueError is raised if an object in ``sizes`` is neither ``None``
  1385. or an integer."""
  1386. iterable = [1, 2, 3, 4, 5, 6, 7, 8, 9]
  1387. sizes = [1, [], 3]
  1388. with self.assertRaises(ValueError):
  1389. list(mi.split_into(iterable, sizes))
  1390. def test_invalid_in_sizes_after_none(self):
  1391. """A item in ``sizes`` that is invalid will not raise a TypeError if it
  1392. comes after a ``None`` item."""
  1393. iterable = [1, 2, 3, 4, 5, 6, 7, 8, 9]
  1394. sizes = [3, 4, None, []]
  1395. expected = [[1, 2, 3], [4, 5, 6, 7], [8, 9]]
  1396. actual = list(mi.split_into(iterable, sizes))
  1397. self.assertEqual(actual, expected)
  1398. def test_generator_iterable_integrity(self):
  1399. """Check that if ``iterable`` is an iterator, it is consumed only by as
  1400. many items as the sum of ``sizes``."""
  1401. iterable = (i for i in range(10))
  1402. sizes = [2, 3]
  1403. expected = [[0, 1], [2, 3, 4]]
  1404. actual = list(mi.split_into(iterable, sizes))
  1405. self.assertEqual(actual, expected)
  1406. iterable_expected = [5, 6, 7, 8, 9]
  1407. iterable_actual = list(iterable)
  1408. self.assertEqual(iterable_actual, iterable_expected)
  1409. def test_generator_sizes_integrity(self):
  1410. """Check that if ``sizes`` is an iterator, it is consumed only until a
  1411. ``None`` item is reached"""
  1412. iterable = [1, 2, 3, 4, 5, 6, 7, 8, 9]
  1413. sizes = (i for i in [1, 2, None, 3, 4])
  1414. expected = [[1], [2, 3], [4, 5, 6, 7, 8, 9]]
  1415. actual = list(mi.split_into(iterable, sizes))
  1416. self.assertEqual(actual, expected)
  1417. sizes_expected = [3, 4]
  1418. sizes_actual = list(sizes)
  1419. self.assertEqual(sizes_actual, sizes_expected)
  1420. class PaddedTest(TestCase):
  1421. """Tests for ``padded()``"""
  1422. def test_no_n(self):
  1423. seq = [1, 2, 3]
  1424. # No fillvalue
  1425. self.assertEqual(mi.take(5, mi.padded(seq)), [1, 2, 3, None, None])
  1426. # With fillvalue
  1427. self.assertEqual(
  1428. mi.take(5, mi.padded(seq, fillvalue='')), [1, 2, 3, '', '']
  1429. )
  1430. def test_invalid_n(self):
  1431. self.assertRaises(ValueError, lambda: list(mi.padded([1, 2, 3], n=-1)))
  1432. self.assertRaises(ValueError, lambda: list(mi.padded([1, 2, 3], n=0)))
  1433. def test_valid_n(self):
  1434. seq = [1, 2, 3, 4, 5]
  1435. # No need for padding: len(seq) <= n
  1436. self.assertEqual(list(mi.padded(seq, n=4)), [1, 2, 3, 4, 5])
  1437. self.assertEqual(list(mi.padded(seq, n=5)), [1, 2, 3, 4, 5])
  1438. # No fillvalue
  1439. self.assertEqual(
  1440. list(mi.padded(seq, n=7)), [1, 2, 3, 4, 5, None, None]
  1441. )
  1442. # With fillvalue
  1443. self.assertEqual(
  1444. list(mi.padded(seq, fillvalue='', n=7)), [1, 2, 3, 4, 5, '', '']
  1445. )
  1446. def test_next_multiple(self):
  1447. seq = [1, 2, 3, 4, 5, 6]
  1448. # No need for padding: len(seq) % n == 0
  1449. self.assertEqual(
  1450. list(mi.padded(seq, n=3, next_multiple=True)), [1, 2, 3, 4, 5, 6]
  1451. )
  1452. # Padding needed: len(seq) < n
  1453. self.assertEqual(
  1454. list(mi.padded(seq, n=8, next_multiple=True)),
  1455. [1, 2, 3, 4, 5, 6, None, None],
  1456. )
  1457. # No padding needed: len(seq) == n
  1458. self.assertEqual(
  1459. list(mi.padded(seq, n=6, next_multiple=True)), [1, 2, 3, 4, 5, 6]
  1460. )
  1461. # Padding needed: len(seq) > n
  1462. self.assertEqual(
  1463. list(mi.padded(seq, n=4, next_multiple=True)),
  1464. [1, 2, 3, 4, 5, 6, None, None],
  1465. )
  1466. # With fillvalue
  1467. self.assertEqual(
  1468. list(mi.padded(seq, fillvalue='', n=4, next_multiple=True)),
  1469. [1, 2, 3, 4, 5, 6, '', ''],
  1470. )
  1471. class RepeatEachTests(TestCase):
  1472. """Tests for repeat_each()"""
  1473. def test_default(self):
  1474. actual = list(mi.repeat_each('ABC'))
  1475. expected = ['A', 'A', 'B', 'B', 'C', 'C']
  1476. self.assertEqual(actual, expected)
  1477. def test_basic(self):
  1478. actual = list(mi.repeat_each('ABC', 3))
  1479. expected = ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C']
  1480. self.assertEqual(actual, expected)
  1481. def test_empty(self):
  1482. actual = list(mi.repeat_each(''))
  1483. expected = []
  1484. self.assertEqual(actual, expected)
  1485. def test_no_repeat(self):
  1486. actual = list(mi.repeat_each('ABC', 0))
  1487. expected = []
  1488. self.assertEqual(actual, expected)
  1489. def test_negative_repeat(self):
  1490. actual = list(mi.repeat_each('ABC', -1))
  1491. expected = []
  1492. self.assertEqual(actual, expected)
  1493. def test_infinite_input(self):
  1494. repeater = mi.repeat_each(cycle('AB'))
  1495. actual = mi.take(6, repeater)
  1496. expected = ['A', 'A', 'B', 'B', 'A', 'A']
  1497. self.assertEqual(actual, expected)
  1498. class RepeatLastTests(TestCase):
  1499. def test_empty_iterable(self):
  1500. slice_length = 3
  1501. iterable = iter([])
  1502. actual = mi.take(slice_length, mi.repeat_last(iterable))
  1503. expected = [None] * slice_length
  1504. self.assertEqual(actual, expected)
  1505. def test_default_value(self):
  1506. slice_length = 3
  1507. iterable = iter([])
  1508. default = '3'
  1509. actual = mi.take(slice_length, mi.repeat_last(iterable, default))
  1510. expected = ['3'] * slice_length
  1511. self.assertEqual(actual, expected)
  1512. def test_basic(self):
  1513. slice_length = 10
  1514. iterable = (str(x) for x in range(5))
  1515. actual = mi.take(slice_length, mi.repeat_last(iterable))
  1516. expected = ['0', '1', '2', '3', '4', '4', '4', '4', '4', '4']
  1517. self.assertEqual(actual, expected)
  1518. class DistributeTest(TestCase):
  1519. """Tests for distribute()"""
  1520. def test_invalid_n(self):
  1521. self.assertRaises(ValueError, lambda: mi.distribute(-1, [1, 2, 3]))
  1522. self.assertRaises(ValueError, lambda: mi.distribute(0, [1, 2, 3]))
  1523. def test_basic(self):
  1524. iterable = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  1525. for n, expected in [
  1526. (1, [iterable]),
  1527. (2, [[1, 3, 5, 7, 9], [2, 4, 6, 8, 10]]),
  1528. (3, [[1, 4, 7, 10], [2, 5, 8], [3, 6, 9]]),
  1529. (10, [[n] for n in range(1, 10 + 1)]),
  1530. ]:
  1531. self.assertEqual(
  1532. [list(x) for x in mi.distribute(n, iterable)], expected
  1533. )
  1534. def test_large_n(self):
  1535. iterable = [1, 2, 3, 4]
  1536. self.assertEqual(
  1537. [list(x) for x in mi.distribute(6, iterable)],
  1538. [[1], [2], [3], [4], [], []],
  1539. )
  1540. class StaggerTest(TestCase):
  1541. """Tests for ``stagger()``"""
  1542. def test_default(self):
  1543. iterable = [0, 1, 2, 3]
  1544. actual = list(mi.stagger(iterable))
  1545. expected = [(None, 0, 1), (0, 1, 2), (1, 2, 3)]
  1546. self.assertEqual(actual, expected)
  1547. def test_offsets(self):
  1548. iterable = [0, 1, 2, 3]
  1549. for offsets, expected in [
  1550. ((-2, 0, 2), [('', 0, 2), ('', 1, 3)]),
  1551. ((-2, -1), [('', ''), ('', 0), (0, 1), (1, 2), (2, 3)]),
  1552. ((1, 2), [(1, 2), (2, 3)]),
  1553. ]:
  1554. all_groups = mi.stagger(iterable, offsets=offsets, fillvalue='')
  1555. self.assertEqual(list(all_groups), expected)
  1556. def test_longest(self):
  1557. iterable = [0, 1, 2, 3]
  1558. for offsets, expected in [
  1559. (
  1560. (-1, 0, 1),
  1561. [('', 0, 1), (0, 1, 2), (1, 2, 3), (2, 3, ''), (3, '', '')],
  1562. ),
  1563. ((-2, -1), [('', ''), ('', 0), (0, 1), (1, 2), (2, 3), (3, '')]),
  1564. ((1, 2), [(1, 2), (2, 3), (3, '')]),
  1565. ]:
  1566. all_groups = mi.stagger(
  1567. iterable, offsets=offsets, fillvalue='', longest=True
  1568. )
  1569. self.assertEqual(list(all_groups), expected)
  1570. class ZipEqualTest(TestCase):
  1571. @skipIf(version_info[:2] < (3, 10), 'zip_equal deprecated for 3.10+')
  1572. def test_deprecation(self):
  1573. with warnings.catch_warnings(record=True) as caught:
  1574. warnings.simplefilter('always')
  1575. self.assertEqual(
  1576. list(mi.zip_equal([1, 2], [3, 4])), [(1, 3), (2, 4)]
  1577. )
  1578. (warning,) = caught
  1579. assert warning.category == DeprecationWarning
  1580. def test_equal(self):
  1581. lists = [0, 1, 2], [2, 3, 4]
  1582. for iterables in [lists, map(iter, lists)]:
  1583. actual = list(mi.zip_equal(*iterables))
  1584. expected = [(0, 2), (1, 3), (2, 4)]
  1585. self.assertEqual(actual, expected)
  1586. def test_unequal_lists(self):
  1587. two_items = [0, 1]
  1588. three_items = [2, 3, 4]
  1589. four_items = [5, 6, 7, 8]
  1590. # the mismatch is at index 1
  1591. try:
  1592. list(mi.zip_equal(two_items, three_items, four_items))
  1593. except mi.UnequalIterablesError as e:
  1594. self.assertEqual(
  1595. e.args[0],
  1596. (
  1597. 'Iterables have different lengths: '
  1598. 'index 0 has length 2; index 1 has length 3'
  1599. ),
  1600. )
  1601. # the mismatch is at index 2
  1602. try:
  1603. list(mi.zip_equal(two_items, two_items, four_items, four_items))
  1604. except mi.UnequalIterablesError as e:
  1605. self.assertEqual(
  1606. e.args[0],
  1607. (
  1608. 'Iterables have different lengths: '
  1609. 'index 0 has length 2; index 2 has length 4'
  1610. ),
  1611. )
  1612. # One without length: delegate to _zip_equal_generator
  1613. try:
  1614. list(mi.zip_equal(two_items, iter(two_items), three_items))
  1615. except mi.UnequalIterablesError as e:
  1616. self.assertEqual(e.args[0], 'Iterables have different lengths')
  1617. class ZipOffsetTest(TestCase):
  1618. """Tests for ``zip_offset()``"""
  1619. def test_shortest(self):
  1620. a_1 = [0, 1, 2, 3]
  1621. a_2 = [0, 1, 2, 3, 4, 5]
  1622. a_3 = [0, 1, 2, 3, 4, 5, 6, 7]
  1623. actual = list(
  1624. mi.zip_offset(a_1, a_2, a_3, offsets=(-1, 0, 1), fillvalue='')
  1625. )
  1626. expected = [('', 0, 1), (0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5)]
  1627. self.assertEqual(actual, expected)
  1628. def test_longest(self):
  1629. a_1 = [0, 1, 2, 3]
  1630. a_2 = [0, 1, 2, 3, 4, 5]
  1631. a_3 = [0, 1, 2, 3, 4, 5, 6, 7]
  1632. actual = list(
  1633. mi.zip_offset(a_1, a_2, a_3, offsets=(-1, 0, 1), longest=True)
  1634. )
  1635. expected = [
  1636. (None, 0, 1),
  1637. (0, 1, 2),
  1638. (1, 2, 3),
  1639. (2, 3, 4),
  1640. (3, 4, 5),
  1641. (None, 5, 6),
  1642. (None, None, 7),
  1643. ]
  1644. self.assertEqual(actual, expected)
  1645. def test_mismatch(self):
  1646. iterables = [0, 1, 2], [2, 3, 4]
  1647. offsets = (-1, 0, 1)
  1648. self.assertRaises(
  1649. ValueError,
  1650. lambda: list(mi.zip_offset(*iterables, offsets=offsets)),
  1651. )
  1652. class UnzipTests(TestCase):
  1653. """Tests for unzip()"""
  1654. def test_empty_iterable(self):
  1655. self.assertEqual(list(mi.unzip([])), [])
  1656. # in reality zip([], [], []) is equivalent to iter([])
  1657. # but it doesn't hurt to test both
  1658. self.assertEqual(list(mi.unzip(zip([], [], []))), [])
  1659. def test_length_one_iterable(self):
  1660. xs, ys, zs = mi.unzip(zip([1], [2], [3]))
  1661. self.assertEqual(list(xs), [1])
  1662. self.assertEqual(list(ys), [2])
  1663. self.assertEqual(list(zs), [3])
  1664. def test_normal_case(self):
  1665. xs, ys, zs = range(10), range(1, 11), range(2, 12)
  1666. zipped = zip(xs, ys, zs)
  1667. xs, ys, zs = mi.unzip(zipped)
  1668. self.assertEqual(list(xs), list(range(10)))
  1669. self.assertEqual(list(ys), list(range(1, 11)))
  1670. self.assertEqual(list(zs), list(range(2, 12)))
  1671. def test_improperly_zipped(self):
  1672. zipped = iter([(1, 2, 3), (4, 5), (6,)])
  1673. xs, ys, zs = mi.unzip(zipped)
  1674. self.assertEqual(list(xs), [1, 4, 6])
  1675. self.assertEqual(list(ys), [2, 5])
  1676. self.assertEqual(list(zs), [3])
  1677. def test_increasingly_zipped(self):
  1678. zipped = iter([(1, 2), (3, 4, 5), (6, 7, 8, 9)])
  1679. unzipped = mi.unzip(zipped)
  1680. # from the docstring:
  1681. # len(first tuple) is the number of iterables zipped
  1682. self.assertEqual(len(unzipped), 2)
  1683. xs, ys = unzipped
  1684. self.assertEqual(list(xs), [1, 3, 6])
  1685. self.assertEqual(list(ys), [2, 4, 7])
  1686. class SortTogetherTest(TestCase):
  1687. """Tests for sort_together()"""
  1688. def test_key_list(self):
  1689. """tests `key_list` including default, iterables include duplicates"""
  1690. iterables = [
  1691. ['GA', 'GA', 'GA', 'CT', 'CT', 'CT'],
  1692. ['May', 'Aug.', 'May', 'June', 'July', 'July'],
  1693. [97, 20, 100, 70, 100, 20],
  1694. ]
  1695. self.assertEqual(
  1696. mi.sort_together(iterables),
  1697. [
  1698. ('CT', 'CT', 'CT', 'GA', 'GA', 'GA'),
  1699. ('June', 'July', 'July', 'May', 'Aug.', 'May'),
  1700. (70, 100, 20, 97, 20, 100),
  1701. ],
  1702. )
  1703. self.assertEqual(
  1704. mi.sort_together(iterables, key_list=(0, 1)),
  1705. [
  1706. ('CT', 'CT', 'CT', 'GA', 'GA', 'GA'),
  1707. ('July', 'July', 'June', 'Aug.', 'May', 'May'),
  1708. (100, 20, 70, 20, 97, 100),
  1709. ],
  1710. )
  1711. self.assertEqual(
  1712. mi.sort_together(iterables, key_list=(0, 1, 2)),
  1713. [
  1714. ('CT', 'CT', 'CT', 'GA', 'GA', 'GA'),
  1715. ('July', 'July', 'June', 'Aug.', 'May', 'May'),
  1716. (20, 100, 70, 20, 97, 100),
  1717. ],
  1718. )
  1719. self.assertEqual(
  1720. mi.sort_together(iterables, key_list=(2,)),
  1721. [
  1722. ('GA', 'CT', 'CT', 'GA', 'GA', 'CT'),
  1723. ('Aug.', 'July', 'June', 'May', 'May', 'July'),
  1724. (20, 20, 70, 97, 100, 100),
  1725. ],
  1726. )
  1727. def test_invalid_key_list(self):
  1728. """tests `key_list` for indexes not available in `iterables`"""
  1729. iterables = [
  1730. ['GA', 'GA', 'GA', 'CT', 'CT', 'CT'],
  1731. ['May', 'Aug.', 'May', 'June', 'July', 'July'],
  1732. [97, 20, 100, 70, 100, 20],
  1733. ]
  1734. self.assertRaises(
  1735. IndexError, lambda: mi.sort_together(iterables, key_list=(5,))
  1736. )
  1737. def test_key_function(self):
  1738. """tests `key` function, including interaction with `key_list`"""
  1739. iterables = [
  1740. ['GA', 'GA', 'GA', 'CT', 'CT', 'CT'],
  1741. ['May', 'Aug.', 'May', 'June', 'July', 'July'],
  1742. [97, 20, 100, 70, 100, 20],
  1743. ]
  1744. self.assertEqual(
  1745. mi.sort_together(iterables, key=lambda x: x),
  1746. [
  1747. ('CT', 'CT', 'CT', 'GA', 'GA', 'GA'),
  1748. ('June', 'July', 'July', 'May', 'Aug.', 'May'),
  1749. (70, 100, 20, 97, 20, 100),
  1750. ],
  1751. )
  1752. self.assertEqual(
  1753. mi.sort_together(iterables, key=lambda x: x[::-1]),
  1754. [
  1755. ('GA', 'GA', 'GA', 'CT', 'CT', 'CT'),
  1756. ('May', 'Aug.', 'May', 'June', 'July', 'July'),
  1757. (97, 20, 100, 70, 100, 20),
  1758. ],
  1759. )
  1760. self.assertEqual(
  1761. mi.sort_together(
  1762. iterables,
  1763. key_list=(0, 2),
  1764. key=lambda state, number: number
  1765. if state == 'CT'
  1766. else 2 * number,
  1767. ),
  1768. [
  1769. ('CT', 'GA', 'CT', 'CT', 'GA', 'GA'),
  1770. ('July', 'Aug.', 'June', 'July', 'May', 'May'),
  1771. (20, 20, 70, 100, 97, 100),
  1772. ],
  1773. )
  1774. def test_reverse(self):
  1775. """tests `reverse` to ensure a reverse sort for `key_list` iterables"""
  1776. iterables = [
  1777. ['GA', 'GA', 'GA', 'CT', 'CT', 'CT'],
  1778. ['May', 'Aug.', 'May', 'June', 'July', 'July'],
  1779. [97, 20, 100, 70, 100, 20],
  1780. ]
  1781. self.assertEqual(
  1782. mi.sort_together(iterables, key_list=(0, 1, 2), reverse=True),
  1783. [
  1784. ('GA', 'GA', 'GA', 'CT', 'CT', 'CT'),
  1785. ('May', 'May', 'Aug.', 'June', 'July', 'July'),
  1786. (100, 97, 20, 70, 100, 20),
  1787. ],
  1788. )
  1789. def test_uneven_iterables(self):
  1790. """tests trimming of iterables to the shortest length before sorting"""
  1791. iterables = [
  1792. ['GA', 'GA', 'GA', 'CT', 'CT', 'CT', 'MA'],
  1793. ['May', 'Aug.', 'May', 'June', 'July', 'July'],
  1794. [97, 20, 100, 70, 100, 20, 0],
  1795. ]
  1796. self.assertEqual(
  1797. mi.sort_together(iterables),
  1798. [
  1799. ('CT', 'CT', 'CT', 'GA', 'GA', 'GA'),
  1800. ('June', 'July', 'July', 'May', 'Aug.', 'May'),
  1801. (70, 100, 20, 97, 20, 100),
  1802. ],
  1803. )
  1804. class DivideTest(TestCase):
  1805. """Tests for divide()"""
  1806. def test_invalid_n(self):
  1807. self.assertRaises(ValueError, lambda: mi.divide(-1, [1, 2, 3]))
  1808. self.assertRaises(ValueError, lambda: mi.divide(0, [1, 2, 3]))
  1809. def test_basic(self):
  1810. iterable = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  1811. for n, expected in [
  1812. (1, [iterable]),
  1813. (2, [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]),
  1814. (3, [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]]),
  1815. (10, [[n] for n in range(1, 10 + 1)]),
  1816. ]:
  1817. self.assertEqual(
  1818. [list(x) for x in mi.divide(n, iterable)], expected
  1819. )
  1820. def test_large_n(self):
  1821. self.assertEqual(
  1822. [list(x) for x in mi.divide(6, iter(range(1, 4 + 1)))],
  1823. [[1], [2], [3], [4], [], []],
  1824. )
  1825. class TestAlwaysIterable(TestCase):
  1826. """Tests for always_iterable()"""
  1827. def test_single(self):
  1828. self.assertEqual(list(mi.always_iterable(1)), [1])
  1829. def test_strings(self):
  1830. for obj in ['foo', b'bar', 'baz']:
  1831. actual = list(mi.always_iterable(obj))
  1832. expected = [obj]
  1833. self.assertEqual(actual, expected)
  1834. def test_base_type(self):
  1835. dict_obj = {'a': 1, 'b': 2}
  1836. str_obj = '123'
  1837. # Default: dicts are iterable like they normally are
  1838. default_actual = list(mi.always_iterable(dict_obj))
  1839. default_expected = list(dict_obj)
  1840. self.assertEqual(default_actual, default_expected)
  1841. # Unitary types set: dicts are not iterable
  1842. custom_actual = list(mi.always_iterable(dict_obj, base_type=dict))
  1843. custom_expected = [dict_obj]
  1844. self.assertEqual(custom_actual, custom_expected)
  1845. # With unitary types set, strings are iterable
  1846. str_actual = list(mi.always_iterable(str_obj, base_type=None))
  1847. str_expected = list(str_obj)
  1848. self.assertEqual(str_actual, str_expected)
  1849. # base_type handles nested tuple (via isinstance).
  1850. base_type = ((dict,),)
  1851. custom_actual = list(mi.always_iterable(dict_obj, base_type=base_type))
  1852. custom_expected = [dict_obj]
  1853. self.assertEqual(custom_actual, custom_expected)
  1854. def test_iterables(self):
  1855. self.assertEqual(list(mi.always_iterable([0, 1])), [0, 1])
  1856. self.assertEqual(
  1857. list(mi.always_iterable([0, 1], base_type=list)), [[0, 1]]
  1858. )
  1859. self.assertEqual(
  1860. list(mi.always_iterable(iter('foo'))), ['f', 'o', 'o']
  1861. )
  1862. self.assertEqual(list(mi.always_iterable([])), [])
  1863. def test_none(self):
  1864. self.assertEqual(list(mi.always_iterable(None)), [])
  1865. def test_generator(self):
  1866. def _gen():
  1867. yield 0
  1868. yield 1
  1869. self.assertEqual(list(mi.always_iterable(_gen())), [0, 1])
  1870. class AdjacentTests(TestCase):
  1871. def test_typical(self):
  1872. actual = list(mi.adjacent(lambda x: x % 5 == 0, range(10)))
  1873. expected = [
  1874. (True, 0),
  1875. (True, 1),
  1876. (False, 2),
  1877. (False, 3),
  1878. (True, 4),
  1879. (True, 5),
  1880. (True, 6),
  1881. (False, 7),
  1882. (False, 8),
  1883. (False, 9),
  1884. ]
  1885. self.assertEqual(actual, expected)
  1886. def test_empty_iterable(self):
  1887. actual = list(mi.adjacent(lambda x: x % 5 == 0, []))
  1888. expected = []
  1889. self.assertEqual(actual, expected)
  1890. def test_length_one(self):
  1891. actual = list(mi.adjacent(lambda x: x % 5 == 0, [0]))
  1892. expected = [(True, 0)]
  1893. self.assertEqual(actual, expected)
  1894. actual = list(mi.adjacent(lambda x: x % 5 == 0, [1]))
  1895. expected = [(False, 1)]
  1896. self.assertEqual(actual, expected)
  1897. def test_consecutive_true(self):
  1898. """Test that when the predicate matches multiple consecutive elements
  1899. it doesn't repeat elements in the output"""
  1900. actual = list(mi.adjacent(lambda x: x % 5 < 2, range(10)))
  1901. expected = [
  1902. (True, 0),
  1903. (True, 1),
  1904. (True, 2),
  1905. (False, 3),
  1906. (True, 4),
  1907. (True, 5),
  1908. (True, 6),
  1909. (True, 7),
  1910. (False, 8),
  1911. (False, 9),
  1912. ]
  1913. self.assertEqual(actual, expected)
  1914. def test_distance(self):
  1915. actual = list(mi.adjacent(lambda x: x % 5 == 0, range(10), distance=2))
  1916. expected = [
  1917. (True, 0),
  1918. (True, 1),
  1919. (True, 2),
  1920. (True, 3),
  1921. (True, 4),
  1922. (True, 5),
  1923. (True, 6),
  1924. (True, 7),
  1925. (False, 8),
  1926. (False, 9),
  1927. ]
  1928. self.assertEqual(actual, expected)
  1929. actual = list(mi.adjacent(lambda x: x % 5 == 0, range(10), distance=3))
  1930. expected = [
  1931. (True, 0),
  1932. (True, 1),
  1933. (True, 2),
  1934. (True, 3),
  1935. (True, 4),
  1936. (True, 5),
  1937. (True, 6),
  1938. (True, 7),
  1939. (True, 8),
  1940. (False, 9),
  1941. ]
  1942. self.assertEqual(actual, expected)
  1943. def test_large_distance(self):
  1944. """Test distance larger than the length of the iterable"""
  1945. iterable = range(10)
  1946. actual = list(mi.adjacent(lambda x: x % 5 == 4, iterable, distance=20))
  1947. expected = list(zip(repeat(True), iterable))
  1948. self.assertEqual(actual, expected)
  1949. actual = list(mi.adjacent(lambda x: False, iterable, distance=20))
  1950. expected = list(zip(repeat(False), iterable))
  1951. self.assertEqual(actual, expected)
  1952. def test_zero_distance(self):
  1953. """Test that adjacent() reduces to zip+map when distance is 0"""
  1954. iterable = range(1000)
  1955. predicate = lambda x: x % 4 == 2
  1956. actual = mi.adjacent(predicate, iterable, 0)
  1957. expected = zip(map(predicate, iterable), iterable)
  1958. self.assertTrue(all(a == e for a, e in zip(actual, expected)))
  1959. def test_negative_distance(self):
  1960. """Test that adjacent() raises an error with negative distance"""
  1961. pred = lambda x: x
  1962. self.assertRaises(
  1963. ValueError, lambda: mi.adjacent(pred, range(1000), -1)
  1964. )
  1965. self.assertRaises(
  1966. ValueError, lambda: mi.adjacent(pred, range(10), -10)
  1967. )
  1968. def test_grouping(self):
  1969. """Test interaction of adjacent() with groupby_transform()"""
  1970. iterable = mi.adjacent(lambda x: x % 5 == 0, range(10))
  1971. grouper = mi.groupby_transform(iterable, itemgetter(0), itemgetter(1))
  1972. actual = [(k, list(g)) for k, g in grouper]
  1973. expected = [
  1974. (True, [0, 1]),
  1975. (False, [2, 3]),
  1976. (True, [4, 5, 6]),
  1977. (False, [7, 8, 9]),
  1978. ]
  1979. self.assertEqual(actual, expected)
  1980. def test_call_once(self):
  1981. """Test that the predicate is only called once per item."""
  1982. already_seen = set()
  1983. iterable = range(10)
  1984. def predicate(item):
  1985. self.assertNotIn(item, already_seen)
  1986. already_seen.add(item)
  1987. return True
  1988. actual = list(mi.adjacent(predicate, iterable))
  1989. expected = [(True, x) for x in iterable]
  1990. self.assertEqual(actual, expected)
  1991. class GroupByTransformTests(TestCase):
  1992. def assertAllGroupsEqual(self, groupby1, groupby2):
  1993. for a, b in zip(groupby1, groupby2):
  1994. key1, group1 = a
  1995. key2, group2 = b
  1996. self.assertEqual(key1, key2)
  1997. self.assertListEqual(list(group1), list(group2))
  1998. self.assertRaises(StopIteration, lambda: next(groupby1))
  1999. self.assertRaises(StopIteration, lambda: next(groupby2))
  2000. def test_default_funcs(self):
  2001. iterable = [(x // 5, x) for x in range(1000)]
  2002. actual = mi.groupby_transform(iterable)
  2003. expected = groupby(iterable)
  2004. self.assertAllGroupsEqual(actual, expected)
  2005. def test_valuefunc(self):
  2006. iterable = [(int(x / 5), int(x / 3), x) for x in range(10)]
  2007. # Test the standard usage of grouping one iterable using another's keys
  2008. grouper = mi.groupby_transform(
  2009. iterable, keyfunc=itemgetter(0), valuefunc=itemgetter(-1)
  2010. )
  2011. actual = [(k, list(g)) for k, g in grouper]
  2012. expected = [(0, [0, 1, 2, 3, 4]), (1, [5, 6, 7, 8, 9])]
  2013. self.assertEqual(actual, expected)
  2014. grouper = mi.groupby_transform(
  2015. iterable, keyfunc=itemgetter(1), valuefunc=itemgetter(-1)
  2016. )
  2017. actual = [(k, list(g)) for k, g in grouper]
  2018. expected = [(0, [0, 1, 2]), (1, [3, 4, 5]), (2, [6, 7, 8]), (3, [9])]
  2019. self.assertEqual(actual, expected)
  2020. # and now for something a little different
  2021. d = dict(zip(range(10), 'abcdefghij'))
  2022. grouper = mi.groupby_transform(
  2023. range(10), keyfunc=lambda x: x // 5, valuefunc=d.get
  2024. )
  2025. actual = [(k, ''.join(g)) for k, g in grouper]
  2026. expected = [(0, 'abcde'), (1, 'fghij')]
  2027. self.assertEqual(actual, expected)
  2028. def test_no_valuefunc(self):
  2029. iterable = range(1000)
  2030. def key(x):
  2031. return x // 5
  2032. actual = mi.groupby_transform(iterable, key, valuefunc=None)
  2033. expected = groupby(iterable, key)
  2034. self.assertAllGroupsEqual(actual, expected)
  2035. actual = mi.groupby_transform(iterable, key) # default valuefunc
  2036. expected = groupby(iterable, key)
  2037. self.assertAllGroupsEqual(actual, expected)
  2038. def test_reducefunc(self):
  2039. iterable = range(50)
  2040. keyfunc = lambda k: 10 * (k // 10)
  2041. valuefunc = lambda v: v + 1
  2042. reducefunc = sum
  2043. actual = list(
  2044. mi.groupby_transform(
  2045. iterable,
  2046. keyfunc=keyfunc,
  2047. valuefunc=valuefunc,
  2048. reducefunc=reducefunc,
  2049. )
  2050. )
  2051. expected = [(0, 55), (10, 155), (20, 255), (30, 355), (40, 455)]
  2052. self.assertEqual(actual, expected)
  2053. class NumericRangeTests(TestCase):
  2054. def test_basic(self):
  2055. for args, expected in [
  2056. ((4,), [0, 1, 2, 3]),
  2057. ((4.0,), [0.0, 1.0, 2.0, 3.0]),
  2058. ((1.0, 4), [1.0, 2.0, 3.0]),
  2059. ((1, 4.0), [1.0, 2.0, 3.0]),
  2060. ((1.0, 5), [1.0, 2.0, 3.0, 4.0]),
  2061. ((0, 20, 5), [0, 5, 10, 15]),
  2062. ((0, 20, 5.0), [0.0, 5.0, 10.0, 15.0]),
  2063. ((0, 10, 3), [0, 3, 6, 9]),
  2064. ((0, 10, 3.0), [0.0, 3.0, 6.0, 9.0]),
  2065. ((0, -5, -1), [0, -1, -2, -3, -4]),
  2066. ((0.0, -5, -1), [0.0, -1.0, -2.0, -3.0, -4.0]),
  2067. ((1, 2, Fraction(1, 2)), [Fraction(1, 1), Fraction(3, 2)]),
  2068. ((0,), []),
  2069. ((0.0,), []),
  2070. ((1, 0), []),
  2071. ((1.0, 0.0), []),
  2072. ((0.1, 0.30000000000000001, 0.2), [0.1]), # IEE 754 !
  2073. (
  2074. (
  2075. Decimal("0.1"),
  2076. Decimal("0.30000000000000001"),
  2077. Decimal("0.2"),
  2078. ),
  2079. [Decimal("0.1"), Decimal("0.3")],
  2080. ), # okay with Decimal
  2081. (
  2082. (
  2083. Fraction(1, 10),
  2084. Fraction(30000000000000001, 100000000000000000),
  2085. Fraction(2, 10),
  2086. ),
  2087. [Fraction(1, 10), Fraction(3, 10)],
  2088. ), # okay with Fraction
  2089. ((Fraction(2, 1),), [Fraction(0, 1), Fraction(1, 1)]),
  2090. ((Decimal('2.0'),), [Decimal('0.0'), Decimal('1.0')]),
  2091. (
  2092. (
  2093. datetime(2019, 3, 29, 12, 34, 56),
  2094. datetime(2019, 3, 29, 12, 37, 55),
  2095. timedelta(minutes=1),
  2096. ),
  2097. [
  2098. datetime(2019, 3, 29, 12, 34, 56),
  2099. datetime(2019, 3, 29, 12, 35, 56),
  2100. datetime(2019, 3, 29, 12, 36, 56),
  2101. ],
  2102. ),
  2103. ]:
  2104. actual = list(mi.numeric_range(*args))
  2105. self.assertEqual(expected, actual)
  2106. self.assertTrue(
  2107. all(type(a) is type(e) for a, e in zip(actual, expected))
  2108. )
  2109. def test_arg_count(self):
  2110. for args, message in [
  2111. ((), 'numeric_range expected at least 1 argument, got 0'),
  2112. (
  2113. (0, 1, 2, 3),
  2114. 'numeric_range expected at most 3 arguments, got 4',
  2115. ),
  2116. ]:
  2117. with self.assertRaisesRegex(TypeError, message):
  2118. mi.numeric_range(*args)
  2119. def test_zero_step(self):
  2120. for args in [
  2121. (1, 2, 0),
  2122. (
  2123. datetime(2019, 3, 29, 12, 34, 56),
  2124. datetime(2019, 3, 29, 12, 37, 55),
  2125. timedelta(minutes=0),
  2126. ),
  2127. (1.0, 2.0, 0.0),
  2128. (Decimal("1.0"), Decimal("2.0"), Decimal("0.0")),
  2129. (Fraction(2, 2), Fraction(4, 2), Fraction(0, 2)),
  2130. ]:
  2131. with self.assertRaises(ValueError):
  2132. list(mi.numeric_range(*args))
  2133. def test_bool(self):
  2134. for args, expected in [
  2135. ((1.0, 3.0, 1.5), True),
  2136. ((1.0, 2.0, 1.5), True),
  2137. ((1.0, 1.0, 1.5), False),
  2138. ((1.0, 0.0, 1.5), False),
  2139. ((3.0, 1.0, -1.5), True),
  2140. ((2.0, 1.0, -1.5), True),
  2141. ((1.0, 1.0, -1.5), False),
  2142. ((0.0, 1.0, -1.5), False),
  2143. ((Decimal("1.0"), Decimal("2.0"), Decimal("1.5")), True),
  2144. ((Decimal("1.0"), Decimal("0.0"), Decimal("1.5")), False),
  2145. ((Fraction(2, 2), Fraction(4, 2), Fraction(3, 2)), True),
  2146. ((Fraction(2, 2), Fraction(0, 2), Fraction(3, 2)), False),
  2147. (
  2148. (
  2149. datetime(2019, 3, 29),
  2150. datetime(2019, 3, 30),
  2151. timedelta(hours=1),
  2152. ),
  2153. True,
  2154. ),
  2155. (
  2156. (
  2157. datetime(2019, 3, 29),
  2158. datetime(2019, 3, 28),
  2159. timedelta(hours=1),
  2160. ),
  2161. False,
  2162. ),
  2163. ]:
  2164. self.assertEqual(expected, bool(mi.numeric_range(*args)))
  2165. def test_contains(self):
  2166. for args, expected_in, expected_not_in in [
  2167. ((10,), range(10), (0.5,)),
  2168. ((1.0, 9.9, 1.5), (1.0, 2.5, 4.0, 5.5, 7.0, 8.5), (0.9,)),
  2169. ((9.0, 1.0, -1.5), (1.5, 3.0, 4.5, 6.0, 7.5, 9.0), (0.0, 0.9)),
  2170. (
  2171. (Decimal("1.0"), Decimal("9.9"), Decimal("1.5")),
  2172. (
  2173. Decimal("1.0"),
  2174. Decimal("2.5"),
  2175. Decimal("4.0"),
  2176. Decimal("5.5"),
  2177. Decimal("7.0"),
  2178. Decimal("8.5"),
  2179. ),
  2180. (Decimal("0.9"),),
  2181. ),
  2182. (
  2183. (Fraction(0, 1), Fraction(5, 1), Fraction(1, 2)),
  2184. (Fraction(0, 1), Fraction(1, 2), Fraction(9, 2)),
  2185. (Fraction(10, 2),),
  2186. ),
  2187. (
  2188. (
  2189. datetime(2019, 3, 29),
  2190. datetime(2019, 3, 30),
  2191. timedelta(hours=1),
  2192. ),
  2193. (datetime(2019, 3, 29, 15),),
  2194. (datetime(2019, 3, 29, 15, 30),),
  2195. ),
  2196. ]:
  2197. r = mi.numeric_range(*args)
  2198. for v in expected_in:
  2199. self.assertTrue(v in r)
  2200. self.assertFalse(v not in r)
  2201. for v in expected_not_in:
  2202. self.assertFalse(v in r)
  2203. self.assertTrue(v not in r)
  2204. def test_eq(self):
  2205. for args1, args2 in [
  2206. ((0, 5, 2), (0, 6, 2)),
  2207. ((1.0, 9.9, 1.5), (1.0, 8.6, 1.5)),
  2208. ((8.5, 0.0, -1.5), (8.5, 0.7, -1.5)),
  2209. ((7.0, 0.0, 1.0), (17.0, 7.0, 0.5)),
  2210. (
  2211. (Decimal("1.0"), Decimal("9.9"), Decimal("1.5")),
  2212. (Decimal("1.0"), Decimal("8.6"), Decimal("1.5")),
  2213. ),
  2214. (
  2215. (Fraction(1, 1), Fraction(10, 1), Fraction(3, 2)),
  2216. (Fraction(1, 1), Fraction(9, 1), Fraction(3, 2)),
  2217. ),
  2218. (
  2219. (
  2220. datetime(2019, 3, 29),
  2221. datetime(2019, 3, 30),
  2222. timedelta(hours=10),
  2223. ),
  2224. (
  2225. datetime(2019, 3, 29),
  2226. datetime(2019, 3, 30, 1),
  2227. timedelta(hours=10),
  2228. ),
  2229. ),
  2230. ]:
  2231. self.assertEqual(
  2232. mi.numeric_range(*args1), mi.numeric_range(*args2)
  2233. )
  2234. for args1, args2 in [
  2235. ((0, 5, 2), (0, 7, 2)),
  2236. ((1.0, 9.9, 1.5), (1.2, 9.9, 1.5)),
  2237. ((1.0, 9.9, 1.5), (1.0, 10.3, 1.5)),
  2238. ((1.0, 9.9, 1.5), (1.0, 9.9, 1.4)),
  2239. ((8.5, 0.0, -1.5), (8.4, 0.0, -1.5)),
  2240. ((8.5, 0.0, -1.5), (8.5, -0.7, -1.5)),
  2241. ((8.5, 0.0, -1.5), (8.5, 0.0, -1.4)),
  2242. ((0.0, 7.0, 1.0), (7.0, 0.0, 1.0)),
  2243. (
  2244. (Decimal("1.0"), Decimal("10.0"), Decimal("1.5")),
  2245. (Decimal("1.0"), Decimal("10.5"), Decimal("1.5")),
  2246. ),
  2247. (
  2248. (Fraction(1, 1), Fraction(10, 1), Fraction(3, 2)),
  2249. (Fraction(1, 1), Fraction(21, 2), Fraction(3, 2)),
  2250. ),
  2251. (
  2252. (
  2253. datetime(2019, 3, 29),
  2254. datetime(2019, 3, 30),
  2255. timedelta(hours=10),
  2256. ),
  2257. (
  2258. datetime(2019, 3, 29),
  2259. datetime(2019, 3, 30, 15),
  2260. timedelta(hours=10),
  2261. ),
  2262. ),
  2263. ]:
  2264. self.assertNotEqual(
  2265. mi.numeric_range(*args1), mi.numeric_range(*args2)
  2266. )
  2267. self.assertNotEqual(mi.numeric_range(7.0), 1)
  2268. self.assertNotEqual(mi.numeric_range(7.0), "abc")
  2269. def test_get_item_by_index(self):
  2270. for args, index, expected in [
  2271. ((1, 6), 2, 3),
  2272. ((1.0, 6.0, 1.5), 0, 1.0),
  2273. ((1.0, 6.0, 1.5), 1, 2.5),
  2274. ((1.0, 6.0, 1.5), 2, 4.0),
  2275. ((1.0, 6.0, 1.5), 3, 5.5),
  2276. ((1.0, 6.0, 1.5), -1, 5.5),
  2277. ((1.0, 6.0, 1.5), -2, 4.0),
  2278. (
  2279. (Decimal("1.0"), Decimal("9.0"), Decimal("1.5")),
  2280. -1,
  2281. Decimal("8.5"),
  2282. ),
  2283. (
  2284. (Fraction(1, 1), Fraction(10, 1), Fraction(3, 2)),
  2285. 2,
  2286. Fraction(4, 1),
  2287. ),
  2288. (
  2289. (
  2290. datetime(2019, 3, 29),
  2291. datetime(2019, 3, 30),
  2292. timedelta(hours=10),
  2293. ),
  2294. 1,
  2295. datetime(2019, 3, 29, 10),
  2296. ),
  2297. ]:
  2298. self.assertEqual(expected, mi.numeric_range(*args)[index])
  2299. for args, index in [
  2300. ((1.0, 6.0, 1.5), 4),
  2301. ((1.0, 6.0, 1.5), -5),
  2302. ((6.0, 1.0, 1.5), 0),
  2303. ((6.0, 1.0, 1.5), -1),
  2304. ((Decimal("1.0"), Decimal("9.0"), Decimal("-1.5")), -1),
  2305. ((Fraction(1, 1), Fraction(2, 1), Fraction(3, 2)), 2),
  2306. (
  2307. (
  2308. datetime(2019, 3, 29),
  2309. datetime(2019, 3, 30),
  2310. timedelta(hours=10),
  2311. ),
  2312. 8,
  2313. ),
  2314. ]:
  2315. with self.assertRaises(IndexError):
  2316. mi.numeric_range(*args)[index]
  2317. def test_get_item_by_slice(self):
  2318. for args, sl, expected_args in [
  2319. ((1.0, 9.0, 1.5), slice(None, None, None), (1.0, 9.0, 1.5)),
  2320. ((1.0, 9.0, 1.5), slice(None, 1, None), (1.0, 2.5, 1.5)),
  2321. ((1.0, 9.0, 1.5), slice(None, None, 2), (1.0, 9.0, 3.0)),
  2322. ((1.0, 9.0, 1.5), slice(None, 2, None), (1.0, 4.0, 1.5)),
  2323. ((1.0, 9.0, 1.5), slice(1, 2, None), (2.5, 4.0, 1.5)),
  2324. ((1.0, 9.0, 1.5), slice(1, -1, None), (2.5, 8.5, 1.5)),
  2325. ((1.0, 9.0, 1.5), slice(10, None, 3), (9.0, 9.0, 4.5)),
  2326. ((1.0, 9.0, 1.5), slice(-10, None, 3), (1.0, 9.0, 4.5)),
  2327. ((1.0, 9.0, 1.5), slice(None, -10, 3), (1.0, 1.0, 4.5)),
  2328. ((1.0, 9.0, 1.5), slice(None, 10, 3), (1.0, 9.0, 4.5)),
  2329. (
  2330. (Decimal("1.0"), Decimal("9.0"), Decimal("1.5")),
  2331. slice(1, -1, None),
  2332. (Decimal("2.5"), Decimal("8.5"), Decimal("1.5")),
  2333. ),
  2334. (
  2335. (Fraction(1, 1), Fraction(5, 1), Fraction(3, 2)),
  2336. slice(1, -1, None),
  2337. (Fraction(5, 2), Fraction(4, 1), Fraction(3, 2)),
  2338. ),
  2339. (
  2340. (
  2341. datetime(2019, 3, 29),
  2342. datetime(2019, 3, 30),
  2343. timedelta(hours=10),
  2344. ),
  2345. slice(1, -1, None),
  2346. (
  2347. datetime(2019, 3, 29, 10),
  2348. datetime(2019, 3, 29, 20),
  2349. timedelta(hours=10),
  2350. ),
  2351. ),
  2352. ]:
  2353. self.assertEqual(
  2354. mi.numeric_range(*expected_args), mi.numeric_range(*args)[sl]
  2355. )
  2356. def test_hash(self):
  2357. for args, expected in [
  2358. ((1.0, 6.0, 1.5), hash((1.0, 5.5, 1.5))),
  2359. ((1.0, 7.0, 1.5), hash((1.0, 5.5, 1.5))),
  2360. ((1.0, 7.5, 1.5), hash((1.0, 7.0, 1.5))),
  2361. ((1.0, 1.5, 1.5), hash((1.0, 1.0, 1.5))),
  2362. ((1.5, 1.0, 1.5), hash(range(0, 0))),
  2363. ((1.5, 1.5, 1.5), hash(range(0, 0))),
  2364. (
  2365. (Decimal("1.0"), Decimal("9.0"), Decimal("1.5")),
  2366. hash((Decimal("1.0"), Decimal("8.5"), Decimal("1.5"))),
  2367. ),
  2368. (
  2369. (Fraction(1, 1), Fraction(5, 1), Fraction(3, 2)),
  2370. hash((Fraction(1, 1), Fraction(4, 1), Fraction(3, 2))),
  2371. ),
  2372. (
  2373. (
  2374. datetime(2019, 3, 29),
  2375. datetime(2019, 3, 30),
  2376. timedelta(hours=10),
  2377. ),
  2378. hash(
  2379. (
  2380. datetime(2019, 3, 29),
  2381. datetime(2019, 3, 29, 20),
  2382. timedelta(hours=10),
  2383. )
  2384. ),
  2385. ),
  2386. ]:
  2387. self.assertEqual(expected, hash(mi.numeric_range(*args)))
  2388. def test_iter_twice(self):
  2389. r1 = mi.numeric_range(1.0, 9.9, 1.5)
  2390. r2 = mi.numeric_range(8.5, 0.0, -1.5)
  2391. self.assertEqual([1.0, 2.5, 4.0, 5.5, 7.0, 8.5], list(r1))
  2392. self.assertEqual([1.0, 2.5, 4.0, 5.5, 7.0, 8.5], list(r1))
  2393. self.assertEqual([8.5, 7.0, 5.5, 4.0, 2.5, 1.0], list(r2))
  2394. self.assertEqual([8.5, 7.0, 5.5, 4.0, 2.5, 1.0], list(r2))
  2395. def test_len(self):
  2396. for args, expected in [
  2397. ((1.0, 7.0, 1.5), 4),
  2398. ((1.0, 7.01, 1.5), 5),
  2399. ((7.0, 1.0, -1.5), 4),
  2400. ((7.01, 1.0, -1.5), 5),
  2401. ((0.1, 0.30000000000000001, 0.2), 1), # IEE 754 !
  2402. (
  2403. (
  2404. Decimal("0.1"),
  2405. Decimal("0.30000000000000001"),
  2406. Decimal("0.2"),
  2407. ),
  2408. 2,
  2409. ), # works with Decimal
  2410. ((Decimal("1.0"), Decimal("9.0"), Decimal("1.5")), 6),
  2411. ((Fraction(1, 1), Fraction(5, 1), Fraction(3, 2)), 3),
  2412. (
  2413. (
  2414. datetime(2019, 3, 29),
  2415. datetime(2019, 3, 30),
  2416. timedelta(hours=10),
  2417. ),
  2418. 3,
  2419. ),
  2420. ]:
  2421. self.assertEqual(expected, len(mi.numeric_range(*args)))
  2422. def test_repr(self):
  2423. for args, *expected in [
  2424. ((7.0,), "numeric_range(0.0, 7.0)"),
  2425. ((1.0, 7.0), "numeric_range(1.0, 7.0)"),
  2426. ((7.0, 1.0, -1.5), "numeric_range(7.0, 1.0, -1.5)"),
  2427. (
  2428. (Decimal("1.0"), Decimal("9.0"), Decimal("1.5")),
  2429. (
  2430. "numeric_range(Decimal('1.0'), Decimal('9.0'), "
  2431. "Decimal('1.5'))"
  2432. ),
  2433. ),
  2434. (
  2435. (Fraction(7, 7), Fraction(10, 2), Fraction(3, 2)),
  2436. (
  2437. "numeric_range(Fraction(1, 1), Fraction(5, 1), "
  2438. "Fraction(3, 2))"
  2439. ),
  2440. ),
  2441. (
  2442. (
  2443. datetime(2019, 3, 29),
  2444. datetime(2019, 3, 30),
  2445. timedelta(hours=10),
  2446. ),
  2447. "numeric_range(datetime.datetime(2019, 3, 29, 0, 0), "
  2448. "datetime.datetime(2019, 3, 30, 0, 0), "
  2449. "datetime.timedelta(seconds=36000))",
  2450. "numeric_range(datetime.datetime(2019, 3, 29, 0, 0), "
  2451. "datetime.datetime(2019, 3, 30, 0, 0), "
  2452. "datetime.timedelta(0, 36000))",
  2453. ),
  2454. ]:
  2455. with self.subTest(args=args):
  2456. self.assertIn(repr(mi.numeric_range(*args)), expected)
  2457. def test_reversed(self):
  2458. for args, expected in [
  2459. ((7.0,), [6.0, 5.0, 4.0, 3.0, 2.0, 1.0, 0.0]),
  2460. ((1.0, 7.0), [6.0, 5.0, 4.0, 3.0, 2.0, 1.0]),
  2461. ((7.0, 1.0, -1.5), [2.5, 4.0, 5.5, 7.0]),
  2462. ((7.0, 0.9, -1.5), [1.0, 2.5, 4.0, 5.5, 7.0]),
  2463. (
  2464. (Decimal("1.0"), Decimal("5.0"), Decimal("1.5")),
  2465. [Decimal('4.0'), Decimal('2.5'), Decimal('1.0')],
  2466. ),
  2467. (
  2468. (Fraction(1, 1), Fraction(5, 1), Fraction(3, 2)),
  2469. [Fraction(4, 1), Fraction(5, 2), Fraction(1, 1)],
  2470. ),
  2471. (
  2472. (
  2473. datetime(2019, 3, 29),
  2474. datetime(2019, 3, 30),
  2475. timedelta(hours=10),
  2476. ),
  2477. [
  2478. datetime(2019, 3, 29, 20),
  2479. datetime(2019, 3, 29, 10),
  2480. datetime(2019, 3, 29),
  2481. ],
  2482. ),
  2483. ]:
  2484. self.assertEqual(expected, list(reversed(mi.numeric_range(*args))))
  2485. def test_count(self):
  2486. for args, v, c in [
  2487. ((7.0,), 0.0, 1),
  2488. ((7.0,), 0.5, 0),
  2489. ((7.0,), 6.0, 1),
  2490. ((7.0,), 7.0, 0),
  2491. ((7.0,), 10.0, 0),
  2492. (
  2493. (Decimal("1.0"), Decimal("5.0"), Decimal("1.5")),
  2494. Decimal('4.0'),
  2495. 1,
  2496. ),
  2497. (
  2498. (Fraction(1, 1), Fraction(5, 1), Fraction(3, 2)),
  2499. Fraction(5, 2),
  2500. 1,
  2501. ),
  2502. (
  2503. (
  2504. datetime(2019, 3, 29),
  2505. datetime(2019, 3, 30),
  2506. timedelta(hours=10),
  2507. ),
  2508. datetime(2019, 3, 29, 20),
  2509. 1,
  2510. ),
  2511. ]:
  2512. self.assertEqual(c, mi.numeric_range(*args).count(v))
  2513. def test_index(self):
  2514. for args, v, i in [
  2515. ((7.0,), 0.0, 0),
  2516. ((7.0,), 6.0, 6),
  2517. ((7.0, 0.0, -1.0), 7.0, 0),
  2518. ((7.0, 0.0, -1.0), 1.0, 6),
  2519. (
  2520. (Decimal("1.0"), Decimal("5.0"), Decimal("1.5")),
  2521. Decimal('4.0'),
  2522. 2,
  2523. ),
  2524. (
  2525. (Fraction(1, 1), Fraction(5, 1), Fraction(3, 2)),
  2526. Fraction(5, 2),
  2527. 1,
  2528. ),
  2529. (
  2530. (
  2531. datetime(2019, 3, 29),
  2532. datetime(2019, 3, 30),
  2533. timedelta(hours=10),
  2534. ),
  2535. datetime(2019, 3, 29, 20),
  2536. 2,
  2537. ),
  2538. ]:
  2539. self.assertEqual(i, mi.numeric_range(*args).index(v))
  2540. for args, v in [
  2541. ((0.7,), 0.5),
  2542. ((0.7,), 7.0),
  2543. ((0.7,), 10.0),
  2544. ((7.0, 0.0, -1.0), 0.5),
  2545. ((7.0, 0.0, -1.0), 0.0),
  2546. ((7.0, 0.0, -1.0), 10.0),
  2547. ((7.0, 0.0), 5.0),
  2548. ((Decimal("1.0"), Decimal("5.0"), Decimal("1.5")), Decimal('4.5')),
  2549. ((Fraction(1, 1), Fraction(5, 1), Fraction(3, 2)), Fraction(5, 3)),
  2550. (
  2551. (
  2552. datetime(2019, 3, 29),
  2553. datetime(2019, 3, 30),
  2554. timedelta(hours=10),
  2555. ),
  2556. datetime(2019, 3, 30),
  2557. ),
  2558. ]:
  2559. with self.assertRaises(ValueError):
  2560. mi.numeric_range(*args).index(v)
  2561. def test_parent_classes(self):
  2562. r = mi.numeric_range(7.0)
  2563. self.assertTrue(isinstance(r, abc.Iterable))
  2564. self.assertFalse(isinstance(r, abc.Iterator))
  2565. self.assertTrue(isinstance(r, abc.Sequence))
  2566. self.assertTrue(isinstance(r, abc.Hashable))
  2567. def test_bad_key(self):
  2568. r = mi.numeric_range(7.0)
  2569. for arg, message in [
  2570. ('a', 'numeric range indices must be integers or slices, not str'),
  2571. (
  2572. (),
  2573. 'numeric range indices must be integers or slices, not tuple',
  2574. ),
  2575. ]:
  2576. with self.assertRaisesRegex(TypeError, message):
  2577. r[arg]
  2578. def test_pickle(self):
  2579. for args in [
  2580. (7.0,),
  2581. (5.0, 7.0),
  2582. (5.0, 7.0, 3.0),
  2583. (7.0, 5.0),
  2584. (7.0, 5.0, 4.0),
  2585. (7.0, 5.0, -1.0),
  2586. (Decimal("1.0"), Decimal("5.0"), Decimal("1.5")),
  2587. (Fraction(1, 1), Fraction(5, 1), Fraction(3, 2)),
  2588. (datetime(2019, 3, 29), datetime(2019, 3, 30)),
  2589. ]:
  2590. r = mi.numeric_range(*args)
  2591. self.assertTrue(dumps(r)) # assert not empty
  2592. self.assertEqual(r, loads(dumps(r)))
  2593. class CountCycleTests(TestCase):
  2594. def test_basic(self):
  2595. expected = [
  2596. (0, 'a'),
  2597. (0, 'b'),
  2598. (0, 'c'),
  2599. (1, 'a'),
  2600. (1, 'b'),
  2601. (1, 'c'),
  2602. (2, 'a'),
  2603. (2, 'b'),
  2604. (2, 'c'),
  2605. ]
  2606. for actual in [
  2607. mi.take(9, mi.count_cycle('abc')), # n=None
  2608. list(mi.count_cycle('abc', 3)), # n=3
  2609. ]:
  2610. self.assertEqual(actual, expected)
  2611. def test_empty(self):
  2612. self.assertEqual(list(mi.count_cycle('')), [])
  2613. self.assertEqual(list(mi.count_cycle('', 2)), [])
  2614. def test_negative(self):
  2615. self.assertEqual(list(mi.count_cycle('abc', -3)), [])
  2616. class MarkEndsTests(TestCase):
  2617. def test_basic(self):
  2618. for size, expected in [
  2619. (0, []),
  2620. (1, [(True, True, '0')]),
  2621. (2, [(True, False, '0'), (False, True, '1')]),
  2622. (3, [(True, False, '0'), (False, False, '1'), (False, True, '2')]),
  2623. (
  2624. 4,
  2625. [
  2626. (True, False, '0'),
  2627. (False, False, '1'),
  2628. (False, False, '2'),
  2629. (False, True, '3'),
  2630. ],
  2631. ),
  2632. ]:
  2633. with self.subTest(size=size):
  2634. iterable = map(str, range(size))
  2635. actual = list(mi.mark_ends(iterable))
  2636. self.assertEqual(actual, expected)
  2637. class LocateTests(TestCase):
  2638. def test_default_pred(self):
  2639. iterable = [0, 1, 1, 0, 1, 0, 0]
  2640. actual = list(mi.locate(iterable))
  2641. expected = [1, 2, 4]
  2642. self.assertEqual(actual, expected)
  2643. def test_no_matches(self):
  2644. iterable = [0, 0, 0]
  2645. actual = list(mi.locate(iterable))
  2646. expected = []
  2647. self.assertEqual(actual, expected)
  2648. def test_custom_pred(self):
  2649. iterable = ['0', 1, 1, '0', 1, '0', '0']
  2650. pred = lambda x: x == '0'
  2651. actual = list(mi.locate(iterable, pred))
  2652. expected = [0, 3, 5, 6]
  2653. self.assertEqual(actual, expected)
  2654. def test_window_size(self):
  2655. iterable = ['0', 1, 1, '0', 1, '0', '0']
  2656. pred = lambda *args: args == ('0', 1)
  2657. actual = list(mi.locate(iterable, pred, window_size=2))
  2658. expected = [0, 3]
  2659. self.assertEqual(actual, expected)
  2660. def test_window_size_large(self):
  2661. iterable = [1, 2, 3, 4]
  2662. pred = lambda a, b, c, d, e: True
  2663. actual = list(mi.locate(iterable, pred, window_size=5))
  2664. expected = [0]
  2665. self.assertEqual(actual, expected)
  2666. def test_window_size_zero(self):
  2667. iterable = [1, 2, 3, 4]
  2668. pred = lambda: True
  2669. with self.assertRaises(ValueError):
  2670. list(mi.locate(iterable, pred, window_size=0))
  2671. class StripFunctionTests(TestCase):
  2672. def test_hashable(self):
  2673. iterable = list('www.example.com')
  2674. pred = lambda x: x in set('cmowz.')
  2675. self.assertEqual(list(mi.lstrip(iterable, pred)), list('example.com'))
  2676. self.assertEqual(list(mi.rstrip(iterable, pred)), list('www.example'))
  2677. self.assertEqual(list(mi.strip(iterable, pred)), list('example'))
  2678. def test_not_hashable(self):
  2679. iterable = [
  2680. list('http://'),
  2681. list('www'),
  2682. list('.example'),
  2683. list('.com'),
  2684. ]
  2685. pred = lambda x: x in [list('http://'), list('www'), list('.com')]
  2686. self.assertEqual(list(mi.lstrip(iterable, pred)), iterable[2:])
  2687. self.assertEqual(list(mi.rstrip(iterable, pred)), iterable[:3])
  2688. self.assertEqual(list(mi.strip(iterable, pred)), iterable[2:3])
  2689. def test_math(self):
  2690. iterable = [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2]
  2691. pred = lambda x: x <= 2
  2692. self.assertEqual(list(mi.lstrip(iterable, pred)), iterable[3:])
  2693. self.assertEqual(list(mi.rstrip(iterable, pred)), iterable[:-3])
  2694. self.assertEqual(list(mi.strip(iterable, pred)), iterable[3:-3])
  2695. class IsliceExtendedTests(TestCase):
  2696. def test_all(self):
  2697. iterable = ['0', '1', '2', '3', '4', '5']
  2698. indexes = [*range(-4, 10), None]
  2699. steps = [1, 2, 3, 4, -1, -2, -3, -4]
  2700. for slice_args in product(indexes, indexes, steps):
  2701. with self.subTest(slice_args=slice_args):
  2702. actual = list(mi.islice_extended(iterable, *slice_args))
  2703. expected = iterable[slice(*slice_args)]
  2704. self.assertEqual(actual, expected, slice_args)
  2705. def test_zero_step(self):
  2706. with self.assertRaises(ValueError):
  2707. list(mi.islice_extended([1, 2, 3], 0, 1, 0))
  2708. def test_slicing(self):
  2709. iterable = map(str, count())
  2710. first_slice = mi.islice_extended(iterable)[10:]
  2711. second_slice = mi.islice_extended(first_slice)[:10]
  2712. third_slice = mi.islice_extended(second_slice)[::2]
  2713. self.assertEqual(list(third_slice), ['10', '12', '14', '16', '18'])
  2714. def test_slicing_extensive(self):
  2715. iterable = range(10)
  2716. options = (None, 1, 2, 7, -1)
  2717. for start, stop, step in product(options, options, options):
  2718. with self.subTest(slice_args=(start, stop, step)):
  2719. sliced_tuple_0 = tuple(
  2720. mi.islice_extended(iterable)[start:stop:step]
  2721. )
  2722. sliced_tuple_1 = tuple(
  2723. mi.islice_extended(iterable, start, stop, step)
  2724. )
  2725. sliced_range = tuple(iterable[start:stop:step])
  2726. self.assertEqual(sliced_tuple_0, sliced_range)
  2727. self.assertEqual(sliced_tuple_1, sliced_range)
  2728. def test_invalid_slice(self):
  2729. with self.assertRaises(TypeError):
  2730. mi.islice_extended(count())[13]
  2731. class ConsecutiveGroupsTest(TestCase):
  2732. def test_numbers(self):
  2733. iterable = [-10, -8, -7, -6, 1, 2, 4, 5, -1, 7]
  2734. actual = [list(g) for g in mi.consecutive_groups(iterable)]
  2735. expected = [[-10], [-8, -7, -6], [1, 2], [4, 5], [-1], [7]]
  2736. self.assertEqual(actual, expected)
  2737. def test_custom_ordering(self):
  2738. iterable = ['1', '10', '11', '20', '21', '22', '30', '31']
  2739. ordering = lambda x: int(x)
  2740. actual = [list(g) for g in mi.consecutive_groups(iterable, ordering)]
  2741. expected = [['1'], ['10', '11'], ['20', '21', '22'], ['30', '31']]
  2742. self.assertEqual(actual, expected)
  2743. def test_exotic_ordering(self):
  2744. iterable = [
  2745. ('a', 'b', 'c', 'd'),
  2746. ('a', 'c', 'b', 'd'),
  2747. ('a', 'c', 'd', 'b'),
  2748. ('a', 'd', 'b', 'c'),
  2749. ('d', 'b', 'c', 'a'),
  2750. ('d', 'c', 'a', 'b'),
  2751. ]
  2752. ordering = list(permutations('abcd')).index
  2753. actual = [list(g) for g in mi.consecutive_groups(iterable, ordering)]
  2754. expected = [
  2755. [('a', 'b', 'c', 'd')],
  2756. [('a', 'c', 'b', 'd'), ('a', 'c', 'd', 'b'), ('a', 'd', 'b', 'c')],
  2757. [('d', 'b', 'c', 'a'), ('d', 'c', 'a', 'b')],
  2758. ]
  2759. self.assertEqual(actual, expected)
  2760. class DifferenceTest(TestCase):
  2761. def test_normal(self):
  2762. iterable = [10, 20, 30, 40, 50]
  2763. actual = list(mi.difference(iterable))
  2764. expected = [10, 10, 10, 10, 10]
  2765. self.assertEqual(actual, expected)
  2766. def test_custom(self):
  2767. iterable = [10, 20, 30, 40, 50]
  2768. actual = list(mi.difference(iterable, add))
  2769. expected = [10, 30, 50, 70, 90]
  2770. self.assertEqual(actual, expected)
  2771. def test_roundtrip(self):
  2772. original = list(range(100))
  2773. accumulated = accumulate(original)
  2774. actual = list(mi.difference(accumulated))
  2775. self.assertEqual(actual, original)
  2776. def test_one(self):
  2777. self.assertEqual(list(mi.difference([0])), [0])
  2778. def test_empty(self):
  2779. self.assertEqual(list(mi.difference([])), [])
  2780. def test_initial(self):
  2781. original = list(range(100))
  2782. accumulated = accumulate(original, initial=100)
  2783. actual = list(mi.difference(accumulated, initial=100))
  2784. self.assertEqual(actual, original)
  2785. class SeekableTest(PeekableMixinTests, TestCase):
  2786. cls = mi.seekable
  2787. def test_exhaustion_reset(self):
  2788. iterable = [str(n) for n in range(10)]
  2789. s = mi.seekable(iterable)
  2790. self.assertEqual(list(s), iterable) # Normal iteration
  2791. self.assertEqual(list(s), []) # Iterable is exhausted
  2792. s.seek(0)
  2793. self.assertEqual(list(s), iterable) # Back in action
  2794. def test_partial_reset(self):
  2795. iterable = [str(n) for n in range(10)]
  2796. s = mi.seekable(iterable)
  2797. self.assertEqual(mi.take(5, s), iterable[:5]) # Normal iteration
  2798. s.seek(1)
  2799. self.assertEqual(list(s), iterable[1:]) # Get the rest of the iterable
  2800. def test_forward(self):
  2801. iterable = [str(n) for n in range(10)]
  2802. s = mi.seekable(iterable)
  2803. self.assertEqual(mi.take(1, s), iterable[:1]) # Normal iteration
  2804. s.seek(3) # Skip over index 2
  2805. self.assertEqual(list(s), iterable[3:]) # Result is similar to slicing
  2806. s.seek(0) # Back to 0
  2807. self.assertEqual(list(s), iterable) # No difference in result
  2808. def test_past_end(self):
  2809. iterable = [str(n) for n in range(10)]
  2810. s = mi.seekable(iterable)
  2811. self.assertEqual(mi.take(1, s), iterable[:1]) # Normal iteration
  2812. s.seek(20)
  2813. self.assertEqual(list(s), []) # Iterable is exhausted
  2814. s.seek(0) # Back to 0
  2815. self.assertEqual(list(s), iterable) # No difference in result
  2816. def test_elements(self):
  2817. iterable = map(str, count())
  2818. s = mi.seekable(iterable)
  2819. mi.take(10, s)
  2820. elements = s.elements()
  2821. self.assertEqual(
  2822. [elements[i] for i in range(10)], [str(n) for n in range(10)]
  2823. )
  2824. self.assertEqual(len(elements), 10)
  2825. mi.take(10, s)
  2826. self.assertEqual(list(elements), [str(n) for n in range(20)])
  2827. def test_maxlen(self):
  2828. iterable = map(str, count())
  2829. s = mi.seekable(iterable, maxlen=4)
  2830. self.assertEqual(mi.take(10, s), [str(n) for n in range(10)])
  2831. self.assertEqual(list(s.elements()), ['6', '7', '8', '9'])
  2832. s.seek(0)
  2833. self.assertEqual(mi.take(14, s), [str(n) for n in range(6, 20)])
  2834. self.assertEqual(list(s.elements()), ['16', '17', '18', '19'])
  2835. def test_maxlen_zero(self):
  2836. iterable = [str(x) for x in range(5)]
  2837. s = mi.seekable(iterable, maxlen=0)
  2838. self.assertEqual(list(s), iterable)
  2839. self.assertEqual(list(s.elements()), [])
  2840. def test_relative_seek(self):
  2841. iterable = [str(x) for x in range(5)]
  2842. s = mi.seekable(iterable)
  2843. s.relative_seek(2)
  2844. self.assertEqual(next(s), '2')
  2845. s.relative_seek(-2)
  2846. self.assertEqual(next(s), '1')
  2847. s.relative_seek(-10) # Lower bound
  2848. self.assertEqual(next(s), '0')
  2849. s.relative_seek(10) # Lower bound
  2850. self.assertEqual(list(s.elements()), [str(x) for x in range(5)])
  2851. class SequenceViewTests(TestCase):
  2852. def test_init(self):
  2853. view = mi.SequenceView((1, 2, 3))
  2854. self.assertEqual(repr(view), "SequenceView((1, 2, 3))")
  2855. self.assertRaises(TypeError, lambda: mi.SequenceView({}))
  2856. def test_update(self):
  2857. seq = [1, 2, 3]
  2858. view = mi.SequenceView(seq)
  2859. self.assertEqual(len(view), 3)
  2860. self.assertEqual(repr(view), "SequenceView([1, 2, 3])")
  2861. seq.pop()
  2862. self.assertEqual(len(view), 2)
  2863. self.assertEqual(repr(view), "SequenceView([1, 2])")
  2864. def test_indexing(self):
  2865. seq = ('a', 'b', 'c', 'd', 'e', 'f')
  2866. view = mi.SequenceView(seq)
  2867. for i in range(-len(seq), len(seq)):
  2868. self.assertEqual(view[i], seq[i])
  2869. def test_slicing(self):
  2870. seq = ('a', 'b', 'c', 'd', 'e', 'f')
  2871. view = mi.SequenceView(seq)
  2872. n = len(seq)
  2873. indexes = list(range(-n - 1, n + 1)) + [None]
  2874. steps = list(range(-n, n + 1))
  2875. steps.remove(0)
  2876. for slice_args in product(indexes, indexes, steps):
  2877. i = slice(*slice_args)
  2878. self.assertEqual(view[i], seq[i])
  2879. def test_abc_methods(self):
  2880. # collections.Sequence should provide all of this functionality
  2881. seq = ('a', 'b', 'c', 'd', 'e', 'f', 'f')
  2882. view = mi.SequenceView(seq)
  2883. # __contains__
  2884. self.assertIn('b', view)
  2885. self.assertNotIn('g', view)
  2886. # __iter__
  2887. self.assertEqual(list(iter(view)), list(seq))
  2888. # __reversed__
  2889. self.assertEqual(list(reversed(view)), list(reversed(seq)))
  2890. # index
  2891. self.assertEqual(view.index('b'), 1)
  2892. # count
  2893. self.assertEqual(seq.count('f'), 2)
  2894. class RunLengthTest(TestCase):
  2895. def test_encode(self):
  2896. iterable = (int(str(n)[0]) for n in count(800))
  2897. actual = mi.take(4, mi.run_length.encode(iterable))
  2898. expected = [(8, 100), (9, 100), (1, 1000), (2, 1000)]
  2899. self.assertEqual(actual, expected)
  2900. def test_decode(self):
  2901. iterable = [('d', 4), ('c', 3), ('b', 2), ('a', 1)]
  2902. actual = ''.join(mi.run_length.decode(iterable))
  2903. expected = 'ddddcccbba'
  2904. self.assertEqual(actual, expected)
  2905. class ExactlyNTests(TestCase):
  2906. """Tests for ``exactly_n()``"""
  2907. def test_true(self):
  2908. """Iterable has ``n`` ``True`` elements"""
  2909. self.assertTrue(mi.exactly_n([True, False, True], 2))
  2910. self.assertTrue(mi.exactly_n([1, 1, 1, 0], 3))
  2911. self.assertTrue(mi.exactly_n([False, False], 0))
  2912. self.assertTrue(mi.exactly_n(range(100), 10, lambda x: x < 10))
  2913. def test_false(self):
  2914. """Iterable does not have ``n`` ``True`` elements"""
  2915. self.assertFalse(mi.exactly_n([True, False, False], 2))
  2916. self.assertFalse(mi.exactly_n([True, True, False], 1))
  2917. self.assertFalse(mi.exactly_n([False], 1))
  2918. self.assertFalse(mi.exactly_n([True], -1))
  2919. self.assertFalse(mi.exactly_n(repeat(True), 100))
  2920. def test_empty(self):
  2921. """Return ``True`` if the iterable is empty and ``n`` is 0"""
  2922. self.assertTrue(mi.exactly_n([], 0))
  2923. self.assertFalse(mi.exactly_n([], 1))
  2924. class AlwaysReversibleTests(TestCase):
  2925. """Tests for ``always_reversible()``"""
  2926. def test_regular_reversed(self):
  2927. self.assertEqual(
  2928. list(reversed(range(10))), list(mi.always_reversible(range(10)))
  2929. )
  2930. self.assertEqual(
  2931. list(reversed([1, 2, 3])), list(mi.always_reversible([1, 2, 3]))
  2932. )
  2933. self.assertEqual(
  2934. reversed([1, 2, 3]).__class__,
  2935. mi.always_reversible([1, 2, 3]).__class__,
  2936. )
  2937. def test_nonseq_reversed(self):
  2938. # Create a non-reversible generator from a sequence
  2939. with self.assertRaises(TypeError):
  2940. reversed(x for x in range(10))
  2941. self.assertEqual(
  2942. list(reversed(range(10))),
  2943. list(mi.always_reversible(x for x in range(10))),
  2944. )
  2945. self.assertEqual(
  2946. list(reversed([1, 2, 3])),
  2947. list(mi.always_reversible(x for x in [1, 2, 3])),
  2948. )
  2949. self.assertNotEqual(
  2950. reversed((1, 2)).__class__,
  2951. mi.always_reversible(x for x in (1, 2)).__class__,
  2952. )
  2953. class CircularShiftsTests(TestCase):
  2954. def test_empty(self):
  2955. # empty iterable -> empty list
  2956. self.assertEqual(list(mi.circular_shifts([])), [])
  2957. def test_simple_circular_shifts(self):
  2958. # test the a simple iterator case
  2959. self.assertEqual(
  2960. mi.circular_shifts(range(4)),
  2961. [(0, 1, 2, 3), (1, 2, 3, 0), (2, 3, 0, 1), (3, 0, 1, 2)],
  2962. )
  2963. def test_duplicates(self):
  2964. # test non-distinct entries
  2965. self.assertEqual(
  2966. mi.circular_shifts([0, 1, 0, 1]),
  2967. [(0, 1, 0, 1), (1, 0, 1, 0), (0, 1, 0, 1), (1, 0, 1, 0)],
  2968. )
  2969. class MakeDecoratorTests(TestCase):
  2970. def test_basic(self):
  2971. slicer = mi.make_decorator(islice)
  2972. @slicer(1, 10, 2)
  2973. def user_function(arg_1, arg_2, kwarg_1=None):
  2974. self.assertEqual(arg_1, 'arg_1')
  2975. self.assertEqual(arg_2, 'arg_2')
  2976. self.assertEqual(kwarg_1, 'kwarg_1')
  2977. return map(str, count())
  2978. it = user_function('arg_1', 'arg_2', kwarg_1='kwarg_1')
  2979. actual = list(it)
  2980. expected = ['1', '3', '5', '7', '9']
  2981. self.assertEqual(actual, expected)
  2982. def test_result_index(self):
  2983. def stringify(*args, **kwargs):
  2984. self.assertEqual(args[0], 'arg_0')
  2985. iterable = args[1]
  2986. self.assertEqual(args[2], 'arg_2')
  2987. self.assertEqual(kwargs['kwarg_1'], 'kwarg_1')
  2988. return map(str, iterable)
  2989. stringifier = mi.make_decorator(stringify, result_index=1)
  2990. @stringifier('arg_0', 'arg_2', kwarg_1='kwarg_1')
  2991. def user_function(n):
  2992. return count(n)
  2993. it = user_function(1)
  2994. actual = mi.take(5, it)
  2995. expected = ['1', '2', '3', '4', '5']
  2996. self.assertEqual(actual, expected)
  2997. def test_wrap_class(self):
  2998. seeker = mi.make_decorator(mi.seekable)
  2999. @seeker()
  3000. def user_function(n):
  3001. return map(str, range(n))
  3002. it = user_function(5)
  3003. self.assertEqual(list(it), ['0', '1', '2', '3', '4'])
  3004. it.seek(0)
  3005. self.assertEqual(list(it), ['0', '1', '2', '3', '4'])
  3006. class MapReduceTests(TestCase):
  3007. def test_default(self):
  3008. iterable = (str(x) for x in range(5))
  3009. keyfunc = lambda x: int(x) // 2
  3010. actual = sorted(mi.map_reduce(iterable, keyfunc).items())
  3011. expected = [(0, ['0', '1']), (1, ['2', '3']), (2, ['4'])]
  3012. self.assertEqual(actual, expected)
  3013. def test_valuefunc(self):
  3014. iterable = (str(x) for x in range(5))
  3015. keyfunc = lambda x: int(x) // 2
  3016. valuefunc = int
  3017. actual = sorted(mi.map_reduce(iterable, keyfunc, valuefunc).items())
  3018. expected = [(0, [0, 1]), (1, [2, 3]), (2, [4])]
  3019. self.assertEqual(actual, expected)
  3020. def test_reducefunc(self):
  3021. iterable = (str(x) for x in range(5))
  3022. keyfunc = lambda x: int(x) // 2
  3023. valuefunc = int
  3024. reducefunc = lambda value_list: reduce(mul, value_list, 1)
  3025. actual = sorted(
  3026. mi.map_reduce(iterable, keyfunc, valuefunc, reducefunc).items()
  3027. )
  3028. expected = [(0, 0), (1, 6), (2, 4)]
  3029. self.assertEqual(actual, expected)
  3030. def test_ret(self):
  3031. d = mi.map_reduce([1, 0, 2, 0, 1, 0], bool)
  3032. self.assertEqual(d, {False: [0, 0, 0], True: [1, 2, 1]})
  3033. self.assertRaises(KeyError, lambda: d[None].append(1))
  3034. class RlocateTests(TestCase):
  3035. def test_default_pred(self):
  3036. iterable = [0, 1, 1, 0, 1, 0, 0]
  3037. for it in (iterable[:], iter(iterable)):
  3038. actual = list(mi.rlocate(it))
  3039. expected = [4, 2, 1]
  3040. self.assertEqual(actual, expected)
  3041. def test_no_matches(self):
  3042. iterable = [0, 0, 0]
  3043. for it in (iterable[:], iter(iterable)):
  3044. actual = list(mi.rlocate(it))
  3045. expected = []
  3046. self.assertEqual(actual, expected)
  3047. def test_custom_pred(self):
  3048. iterable = ['0', 1, 1, '0', 1, '0', '0']
  3049. pred = lambda x: x == '0'
  3050. for it in (iterable[:], iter(iterable)):
  3051. actual = list(mi.rlocate(it, pred))
  3052. expected = [6, 5, 3, 0]
  3053. self.assertEqual(actual, expected)
  3054. def test_efficient_reversal(self):
  3055. iterable = range(9**9) # Is efficiently reversible
  3056. target = 9**9 - 2
  3057. pred = lambda x: x == target # Find-able from the right
  3058. actual = next(mi.rlocate(iterable, pred))
  3059. self.assertEqual(actual, target)
  3060. def test_window_size(self):
  3061. iterable = ['0', 1, 1, '0', 1, '0', '0']
  3062. pred = lambda *args: args == ('0', 1)
  3063. for it in (iterable, iter(iterable)):
  3064. actual = list(mi.rlocate(it, pred, window_size=2))
  3065. expected = [3, 0]
  3066. self.assertEqual(actual, expected)
  3067. def test_window_size_large(self):
  3068. iterable = [1, 2, 3, 4]
  3069. pred = lambda a, b, c, d, e: True
  3070. for it in (iterable, iter(iterable)):
  3071. actual = list(mi.rlocate(iterable, pred, window_size=5))
  3072. expected = [0]
  3073. self.assertEqual(actual, expected)
  3074. def test_window_size_zero(self):
  3075. iterable = [1, 2, 3, 4]
  3076. pred = lambda: True
  3077. for it in (iterable, iter(iterable)):
  3078. with self.assertRaises(ValueError):
  3079. list(mi.locate(iterable, pred, window_size=0))
  3080. class ReplaceTests(TestCase):
  3081. def test_basic(self):
  3082. iterable = range(10)
  3083. pred = lambda x: x % 2 == 0
  3084. substitutes = []
  3085. actual = list(mi.replace(iterable, pred, substitutes))
  3086. expected = [1, 3, 5, 7, 9]
  3087. self.assertEqual(actual, expected)
  3088. def test_count(self):
  3089. iterable = range(10)
  3090. pred = lambda x: x % 2 == 0
  3091. substitutes = []
  3092. actual = list(mi.replace(iterable, pred, substitutes, count=4))
  3093. expected = [1, 3, 5, 7, 8, 9]
  3094. self.assertEqual(actual, expected)
  3095. def test_window_size(self):
  3096. iterable = range(10)
  3097. pred = lambda *args: args == (0, 1, 2)
  3098. substitutes = []
  3099. actual = list(mi.replace(iterable, pred, substitutes, window_size=3))
  3100. expected = [3, 4, 5, 6, 7, 8, 9]
  3101. self.assertEqual(actual, expected)
  3102. def test_window_size_end(self):
  3103. iterable = range(10)
  3104. pred = lambda *args: args == (7, 8, 9)
  3105. substitutes = []
  3106. actual = list(mi.replace(iterable, pred, substitutes, window_size=3))
  3107. expected = [0, 1, 2, 3, 4, 5, 6]
  3108. self.assertEqual(actual, expected)
  3109. def test_window_size_count(self):
  3110. iterable = range(10)
  3111. pred = lambda *args: (args == (0, 1, 2)) or (args == (7, 8, 9))
  3112. substitutes = []
  3113. actual = list(
  3114. mi.replace(iterable, pred, substitutes, count=1, window_size=3)
  3115. )
  3116. expected = [3, 4, 5, 6, 7, 8, 9]
  3117. self.assertEqual(actual, expected)
  3118. def test_window_size_large(self):
  3119. iterable = range(4)
  3120. pred = lambda a, b, c, d, e: True
  3121. substitutes = [5, 6, 7]
  3122. actual = list(mi.replace(iterable, pred, substitutes, window_size=5))
  3123. expected = [5, 6, 7]
  3124. self.assertEqual(actual, expected)
  3125. def test_window_size_zero(self):
  3126. iterable = range(10)
  3127. pred = lambda *args: True
  3128. substitutes = []
  3129. with self.assertRaises(ValueError):
  3130. list(mi.replace(iterable, pred, substitutes, window_size=0))
  3131. def test_iterable_substitutes(self):
  3132. iterable = range(5)
  3133. pred = lambda x: x % 2 == 0
  3134. substitutes = iter('__')
  3135. actual = list(mi.replace(iterable, pred, substitutes))
  3136. expected = ['_', '_', 1, '_', '_', 3, '_', '_']
  3137. self.assertEqual(actual, expected)
  3138. class PartitionsTest(TestCase):
  3139. def test_types(self):
  3140. for iterable in ['abcd', ['a', 'b', 'c', 'd'], ('a', 'b', 'c', 'd')]:
  3141. with self.subTest(iterable=iterable):
  3142. actual = list(mi.partitions(iterable))
  3143. expected = [
  3144. [['a', 'b', 'c', 'd']],
  3145. [['a'], ['b', 'c', 'd']],
  3146. [['a', 'b'], ['c', 'd']],
  3147. [['a', 'b', 'c'], ['d']],
  3148. [['a'], ['b'], ['c', 'd']],
  3149. [['a'], ['b', 'c'], ['d']],
  3150. [['a', 'b'], ['c'], ['d']],
  3151. [['a'], ['b'], ['c'], ['d']],
  3152. ]
  3153. self.assertEqual(actual, expected)
  3154. def test_empty(self):
  3155. iterable = []
  3156. actual = list(mi.partitions(iterable))
  3157. expected = [[[]]]
  3158. self.assertEqual(actual, expected)
  3159. def test_order(self):
  3160. iterable = iter([3, 2, 1])
  3161. actual = list(mi.partitions(iterable))
  3162. expected = [[[3, 2, 1]], [[3], [2, 1]], [[3, 2], [1]], [[3], [2], [1]]]
  3163. self.assertEqual(actual, expected)
  3164. def test_duplicates(self):
  3165. iterable = [1, 1, 1]
  3166. actual = list(mi.partitions(iterable))
  3167. expected = [[[1, 1, 1]], [[1], [1, 1]], [[1, 1], [1]], [[1], [1], [1]]]
  3168. self.assertEqual(actual, expected)
  3169. class _FrozenMultiset(Set):
  3170. """
  3171. A helper class, useful to compare two lists without reference to the order
  3172. of elements.
  3173. FrozenMultiset represents a hashable set that allows duplicate elements.
  3174. """
  3175. def __init__(self, iterable):
  3176. self._collection = frozenset(Counter(iterable).items())
  3177. def __contains__(self, y):
  3178. """
  3179. >>> (0, 1) in _FrozenMultiset([(0, 1), (2,), (0, 1)])
  3180. True
  3181. """
  3182. return any(y == x for x, _ in self._collection)
  3183. def __iter__(self):
  3184. """
  3185. >>> sorted(_FrozenMultiset([(0, 1), (2,), (0, 1)]))
  3186. [(0, 1), (0, 1), (2,)]
  3187. """
  3188. return (x for x, c in self._collection for _ in range(c))
  3189. def __len__(self):
  3190. """
  3191. >>> len(_FrozenMultiset([(0, 1), (2,), (0, 1)]))
  3192. 3
  3193. """
  3194. return sum(c for x, c in self._collection)
  3195. def has_duplicates(self):
  3196. """
  3197. >>> _FrozenMultiset([(0, 1), (2,), (0, 1)]).has_duplicates()
  3198. True
  3199. """
  3200. return any(c != 1 for _, c in self._collection)
  3201. def __hash__(self):
  3202. return hash(self._collection)
  3203. def __repr__(self):
  3204. return "FrozenSet([{}]".format(", ".join(repr(x) for x in iter(self)))
  3205. class SetPartitionsTests(TestCase):
  3206. @staticmethod
  3207. def _normalize_partition(p):
  3208. """
  3209. Return a normalized, hashable, version of a partition using
  3210. _FrozenMultiset
  3211. """
  3212. return _FrozenMultiset(_FrozenMultiset(g) for g in p)
  3213. @staticmethod
  3214. def _normalize_partitions(ps):
  3215. """
  3216. Return a normalized set of all normalized partitions using
  3217. _FrozenMultiset
  3218. """
  3219. return _FrozenMultiset(
  3220. SetPartitionsTests._normalize_partition(p) for p in ps
  3221. )
  3222. def test_repeated(self):
  3223. it = 'aaa'
  3224. actual = mi.set_partitions(it, 2)
  3225. expected = [['a', 'aa'], ['a', 'aa'], ['a', 'aa']]
  3226. self.assertEqual(
  3227. self._normalize_partitions(expected),
  3228. self._normalize_partitions(actual),
  3229. )
  3230. def test_each_correct(self):
  3231. a = set(range(6))
  3232. for p in mi.set_partitions(a):
  3233. total = {e for g in p for e in g}
  3234. self.assertEqual(a, total)
  3235. def test_duplicates(self):
  3236. a = set(range(6))
  3237. for p in mi.set_partitions(a):
  3238. self.assertFalse(self._normalize_partition(p).has_duplicates())
  3239. def test_found_all(self):
  3240. """small example, hand-checked"""
  3241. expected = [
  3242. [[0], [1], [2, 3, 4]],
  3243. [[0], [1, 2], [3, 4]],
  3244. [[0], [2], [1, 3, 4]],
  3245. [[0], [3], [1, 2, 4]],
  3246. [[0], [4], [1, 2, 3]],
  3247. [[0], [1, 3], [2, 4]],
  3248. [[0], [1, 4], [2, 3]],
  3249. [[1], [2], [0, 3, 4]],
  3250. [[1], [3], [0, 2, 4]],
  3251. [[1], [4], [0, 2, 3]],
  3252. [[1], [0, 2], [3, 4]],
  3253. [[1], [0, 3], [2, 4]],
  3254. [[1], [0, 4], [2, 3]],
  3255. [[2], [3], [0, 1, 4]],
  3256. [[2], [4], [0, 1, 3]],
  3257. [[2], [0, 1], [3, 4]],
  3258. [[2], [0, 3], [1, 4]],
  3259. [[2], [0, 4], [1, 3]],
  3260. [[3], [4], [0, 1, 2]],
  3261. [[3], [0, 1], [2, 4]],
  3262. [[3], [0, 2], [1, 4]],
  3263. [[3], [0, 4], [1, 2]],
  3264. [[4], [0, 1], [2, 3]],
  3265. [[4], [0, 2], [1, 3]],
  3266. [[4], [0, 3], [1, 2]],
  3267. ]
  3268. actual = mi.set_partitions(range(5), 3)
  3269. self.assertEqual(
  3270. self._normalize_partitions(expected),
  3271. self._normalize_partitions(actual),
  3272. )
  3273. def test_stirling_numbers(self):
  3274. """Check against https://en.wikipedia.org/wiki/
  3275. Stirling_numbers_of_the_second_kind#Table_of_values"""
  3276. cardinality_by_k_by_n = [
  3277. [1],
  3278. [1, 1],
  3279. [1, 3, 1],
  3280. [1, 7, 6, 1],
  3281. [1, 15, 25, 10, 1],
  3282. [1, 31, 90, 65, 15, 1],
  3283. ]
  3284. for n, cardinality_by_k in enumerate(cardinality_by_k_by_n, 1):
  3285. for k, cardinality in enumerate(cardinality_by_k, 1):
  3286. self.assertEqual(
  3287. cardinality, len(list(mi.set_partitions(range(n), k)))
  3288. )
  3289. def test_no_group(self):
  3290. def helper():
  3291. list(mi.set_partitions(range(4), -1))
  3292. self.assertRaises(ValueError, helper)
  3293. def test_to_many_groups(self):
  3294. self.assertEqual([], list(mi.set_partitions(range(4), 5)))
  3295. class TimeLimitedTests(TestCase):
  3296. def test_basic(self):
  3297. def generator():
  3298. yield 1
  3299. yield 2
  3300. sleep(0.2)
  3301. yield 3
  3302. iterable = mi.time_limited(0.1, generator())
  3303. actual = list(iterable)
  3304. expected = [1, 2]
  3305. self.assertEqual(actual, expected)
  3306. self.assertTrue(iterable.timed_out)
  3307. def test_complete(self):
  3308. iterable = mi.time_limited(2, iter(range(10)))
  3309. actual = list(iterable)
  3310. expected = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  3311. self.assertEqual(actual, expected)
  3312. self.assertFalse(iterable.timed_out)
  3313. def test_zero_limit(self):
  3314. iterable = mi.time_limited(0, count())
  3315. actual = list(iterable)
  3316. expected = []
  3317. self.assertEqual(actual, expected)
  3318. self.assertTrue(iterable.timed_out)
  3319. def test_invalid_limit(self):
  3320. with self.assertRaises(ValueError):
  3321. list(mi.time_limited(-0.1, count()))
  3322. class OnlyTests(TestCase):
  3323. def test_defaults(self):
  3324. self.assertEqual(mi.only([]), None)
  3325. self.assertEqual(mi.only([1]), 1)
  3326. self.assertRaises(ValueError, lambda: mi.only([1, 2]))
  3327. def test_custom_value(self):
  3328. self.assertEqual(mi.only([], default='!'), '!')
  3329. self.assertEqual(mi.only([1], default='!'), 1)
  3330. self.assertRaises(ValueError, lambda: mi.only([1, 2], default='!'))
  3331. def test_custom_exception(self):
  3332. self.assertEqual(mi.only([], too_long=RuntimeError), None)
  3333. self.assertEqual(mi.only([1], too_long=RuntimeError), 1)
  3334. self.assertRaises(
  3335. RuntimeError, lambda: mi.only([1, 2], too_long=RuntimeError)
  3336. )
  3337. def test_default_exception_message(self):
  3338. self.assertRaisesRegex(
  3339. ValueError,
  3340. "Expected exactly one item in iterable, "
  3341. "but got 'foo', 'bar', and perhaps more",
  3342. lambda: mi.only(['foo', 'bar', 'baz']),
  3343. )
  3344. class IchunkedTests(TestCase):
  3345. def test_even(self):
  3346. iterable = (str(x) for x in range(10))
  3347. actual = [''.join(c) for c in mi.ichunked(iterable, 5)]
  3348. expected = ['01234', '56789']
  3349. self.assertEqual(actual, expected)
  3350. def test_odd(self):
  3351. iterable = (str(x) for x in range(10))
  3352. actual = [''.join(c) for c in mi.ichunked(iterable, 4)]
  3353. expected = ['0123', '4567', '89']
  3354. self.assertEqual(actual, expected)
  3355. def test_zero(self):
  3356. iterable = []
  3357. actual = [list(c) for c in mi.ichunked(iterable, 0)]
  3358. expected = []
  3359. self.assertEqual(actual, expected)
  3360. def test_negative(self):
  3361. iterable = count()
  3362. with self.assertRaises(ValueError):
  3363. [list(c) for c in mi.ichunked(iterable, -1)]
  3364. def test_out_of_order(self):
  3365. iterable = map(str, count())
  3366. it = mi.ichunked(iterable, 4)
  3367. chunk_1 = next(it)
  3368. chunk_2 = next(it)
  3369. self.assertEqual(''.join(chunk_2), '4567')
  3370. self.assertEqual(''.join(chunk_1), '0123')
  3371. def test_laziness(self):
  3372. def gen():
  3373. yield 0
  3374. raise RuntimeError
  3375. yield from count(1)
  3376. it = mi.ichunked(gen(), 4)
  3377. chunk = next(it)
  3378. self.assertEqual(next(chunk), 0)
  3379. self.assertRaises(RuntimeError, next, it)
  3380. def test_memory_in_order(self):
  3381. # No items should be kept in memory when a chunk is produced
  3382. all_chunks = mi.ichunked(count(), 4)
  3383. first_chunk = next(all_chunks)
  3384. self.assertEqual(len(first_chunk._cache), 0)
  3385. # If we don't read a chunk before getting its successor, its contents
  3386. # will be cached
  3387. second_chunk = next(all_chunks)
  3388. self.assertEqual(len(first_chunk._cache), 4)
  3389. # If we read in order, there again should be nothing cached
  3390. mi.consume(first_chunk)
  3391. mi.consume(second_chunk)
  3392. third_chunk = next(all_chunks)
  3393. for chunk in (first_chunk, second_chunk, third_chunk):
  3394. self.assertEqual(len(chunk._cache), 0)
  3395. class DistinctCombinationsTests(TestCase):
  3396. def test_basic(self):
  3397. for iterable in [
  3398. (1, 2, 2, 3, 3, 3), # In order
  3399. range(6), # All distinct
  3400. 'abbccc', # Not numbers
  3401. 'cccbba', # Backward
  3402. 'mississippi', # No particular order
  3403. ]:
  3404. for r in range(len(iterable)):
  3405. with self.subTest(iterable=iterable, r=r):
  3406. actual = list(mi.distinct_combinations(iterable, r))
  3407. expected = list(
  3408. mi.unique_everseen(combinations(iterable, r))
  3409. )
  3410. self.assertEqual(actual, expected)
  3411. def test_negative(self):
  3412. with self.assertRaises(ValueError):
  3413. list(mi.distinct_combinations([], -1))
  3414. def test_empty(self):
  3415. self.assertEqual(list(mi.distinct_combinations([], 2)), [])
  3416. class FilterExceptTests(TestCase):
  3417. def test_no_exceptions_pass(self):
  3418. iterable = '0123'
  3419. actual = list(mi.filter_except(int, iterable))
  3420. expected = ['0', '1', '2', '3']
  3421. self.assertEqual(actual, expected)
  3422. def test_no_exceptions_raise(self):
  3423. iterable = ['0', '1', 'two', '3']
  3424. with self.assertRaises(ValueError):
  3425. list(mi.filter_except(int, iterable))
  3426. def test_raise(self):
  3427. iterable = ['0', '1' '2', 'three', None]
  3428. with self.assertRaises(TypeError):
  3429. list(mi.filter_except(int, iterable, ValueError))
  3430. def test_false(self):
  3431. # Even if the validator returns false, we pass through
  3432. validator = lambda x: False
  3433. iterable = ['0', '1', '2', 'three', None]
  3434. actual = list(mi.filter_except(validator, iterable, Exception))
  3435. expected = ['0', '1', '2', 'three', None]
  3436. self.assertEqual(actual, expected)
  3437. def test_multiple(self):
  3438. iterable = ['0', '1', '2', 'three', None, '4']
  3439. actual = list(mi.filter_except(int, iterable, ValueError, TypeError))
  3440. expected = ['0', '1', '2', '4']
  3441. self.assertEqual(actual, expected)
  3442. class MapExceptTests(TestCase):
  3443. def test_no_exceptions_pass(self):
  3444. iterable = '0123'
  3445. actual = list(mi.map_except(int, iterable))
  3446. expected = [0, 1, 2, 3]
  3447. self.assertEqual(actual, expected)
  3448. def test_no_exceptions_raise(self):
  3449. iterable = ['0', '1', 'two', '3']
  3450. with self.assertRaises(ValueError):
  3451. list(mi.map_except(int, iterable))
  3452. def test_raise(self):
  3453. iterable = ['0', '1' '2', 'three', None]
  3454. with self.assertRaises(TypeError):
  3455. list(mi.map_except(int, iterable, ValueError))
  3456. def test_multiple(self):
  3457. iterable = ['0', '1', '2', 'three', None, '4']
  3458. actual = list(mi.map_except(int, iterable, ValueError, TypeError))
  3459. expected = [0, 1, 2, 4]
  3460. self.assertEqual(actual, expected)
  3461. class MapIfTests(TestCase):
  3462. def test_without_func_else(self):
  3463. iterable = list(range(-5, 5))
  3464. actual = list(mi.map_if(iterable, lambda x: x > 3, lambda x: 'toobig'))
  3465. expected = [-5, -4, -3, -2, -1, 0, 1, 2, 3, 'toobig']
  3466. self.assertEqual(actual, expected)
  3467. def test_with_func_else(self):
  3468. iterable = list(range(-5, 5))
  3469. actual = list(
  3470. mi.map_if(
  3471. iterable, lambda x: x >= 0, lambda x: 'notneg', lambda x: 'neg'
  3472. )
  3473. )
  3474. expected = ['neg'] * 5 + ['notneg'] * 5
  3475. self.assertEqual(actual, expected)
  3476. def test_empty(self):
  3477. actual = list(mi.map_if([], lambda x: len(x) > 5, lambda x: None))
  3478. expected = []
  3479. self.assertEqual(actual, expected)
  3480. class SampleTests(TestCase):
  3481. def test_unit_case(self):
  3482. """Test against a fixed case by seeding the random module."""
  3483. # Beware that this test really just verifies random.random() behavior.
  3484. # If the algorithm is changed (e.g. to a more naive implementation)
  3485. # this test will fail, but the algorithm might be correct.
  3486. # Also, this test can pass and the algorithm can be completely wrong.
  3487. data = "abcdef"
  3488. weights = list(range(1, len(data) + 1))
  3489. seed(123)
  3490. actual = mi.sample(data, k=2, weights=weights)
  3491. expected = ['f', 'e']
  3492. self.assertEqual(actual, expected)
  3493. def test_length(self):
  3494. """Check that *k* elements are sampled."""
  3495. data = [1, 2, 3, 4, 5]
  3496. for k in [0, 3, 5, 7]:
  3497. sampled = mi.sample(data, k=k)
  3498. actual = len(sampled)
  3499. expected = min(k, len(data))
  3500. self.assertEqual(actual, expected)
  3501. def test_sampling_entire_iterable(self):
  3502. """If k=len(iterable), the sample contains the original elements."""
  3503. data = ["a", 2, "a", 4, (1, 2, 3)]
  3504. actual = set(mi.sample(data, k=len(data)))
  3505. expected = set(data)
  3506. self.assertEqual(actual, expected)
  3507. def test_scale_invariance_of_weights(self):
  3508. """The probability of choosing element a_i is w_i / sum(weights).
  3509. Scaling weights should not change the probability or outcome."""
  3510. data = "abcdef"
  3511. weights = list(range(1, len(data) + 1))
  3512. seed(123)
  3513. first_sample = mi.sample(data, k=2, weights=weights)
  3514. # Scale the weights and sample again
  3515. weights_scaled = [w / 1e10 for w in weights]
  3516. seed(123)
  3517. second_sample = mi.sample(data, k=2, weights=weights_scaled)
  3518. self.assertEqual(first_sample, second_sample)
  3519. def test_invariance_under_permutations_unweighted(self):
  3520. """The order of the data should not matter. This is a stochastic test,
  3521. but it will fail in less than 1 / 10_000 cases."""
  3522. # Create a data set and a reversed data set
  3523. data = list(range(100))
  3524. data_rev = list(reversed(data))
  3525. # Sample each data set 10 times
  3526. data_means = [mean(mi.sample(data, k=50)) for _ in range(10)]
  3527. data_rev_means = [mean(mi.sample(data_rev, k=50)) for _ in range(10)]
  3528. # The difference in the means should be low, i.e. little bias
  3529. difference_in_means = abs(mean(data_means) - mean(data_rev_means))
  3530. # The observed largest difference in 10,000 simulations was 5.09599
  3531. self.assertTrue(difference_in_means < 5.1)
  3532. def test_invariance_under_permutations_weighted(self):
  3533. """The order of the data should not matter. This is a stochastic test,
  3534. but it will fail in less than 1 / 10_000 cases."""
  3535. # Create a data set and a reversed data set
  3536. data = list(range(1, 101))
  3537. data_rev = list(reversed(data))
  3538. # Sample each data set 10 times
  3539. data_means = [
  3540. mean(mi.sample(data, k=50, weights=data)) for _ in range(10)
  3541. ]
  3542. data_rev_means = [
  3543. mean(mi.sample(data_rev, k=50, weights=data_rev))
  3544. for _ in range(10)
  3545. ]
  3546. # The difference in the means should be low, i.e. little bias
  3547. difference_in_means = abs(mean(data_means) - mean(data_rev_means))
  3548. # The observed largest difference in 10,000 simulations was 4.337999
  3549. self.assertTrue(difference_in_means < 4.4)
  3550. class IsSortedTests(TestCase):
  3551. def test_basic(self):
  3552. for iterable, kwargs, expected in [
  3553. ([], {}, True),
  3554. ([1], {}, True),
  3555. ([1, 2, 3], {}, True),
  3556. ([1, 1, 2, 3], {}, True),
  3557. ([1, 10, 2, 3], {}, False),
  3558. (['1', '10', '2', '3'], {}, True),
  3559. (['1', '10', '2', '3'], {'key': int}, False),
  3560. ([1, 2, 3], {'reverse': True}, False),
  3561. ([1, 1, 2, 3], {'reverse': True}, False),
  3562. ([1, 10, 2, 3], {'reverse': True}, False),
  3563. (['3', '2', '10', '1'], {'reverse': True}, True),
  3564. (['3', '2', '10', '1'], {'key': int, 'reverse': True}, False),
  3565. # strict
  3566. ([], {'strict': True}, True),
  3567. ([1], {'strict': True}, True),
  3568. ([1, 1], {'strict': True}, False),
  3569. ([1, 2, 3], {'strict': True}, True),
  3570. ([1, 1, 2, 3], {'strict': True}, False),
  3571. ([1, 10, 2, 3], {'strict': True}, False),
  3572. (['1', '10', '2', '3'], {'strict': True}, True),
  3573. (['1', '10', '2', '3', '3'], {'strict': True}, False),
  3574. (['1', '10', '2', '3'], {'strict': True, 'key': int}, False),
  3575. ([1, 2, 3], {'strict': True, 'reverse': True}, False),
  3576. ([1, 1, 2, 3], {'strict': True, 'reverse': True}, False),
  3577. ([1, 10, 2, 3], {'strict': True, 'reverse': True}, False),
  3578. (['3', '2', '10', '1'], {'strict': True, 'reverse': True}, True),
  3579. (
  3580. ['3', '2', '10', '10', '1'],
  3581. {'strict': True, 'reverse': True},
  3582. False,
  3583. ),
  3584. (
  3585. ['3', '2', '10', '1'],
  3586. {'strict': True, 'key': int, 'reverse': True},
  3587. False,
  3588. ),
  3589. # We'll do the same weird thing as Python here
  3590. (['nan', 0, 'nan', 0], {'key': float}, True),
  3591. ([0, 'nan', 0, 'nan'], {'key': float}, True),
  3592. (['nan', 0, 'nan', 0], {'key': float, 'reverse': True}, True),
  3593. ([0, 'nan', 0, 'nan'], {'key': float, 'reverse': True}, True),
  3594. ([0, 'nan', 0, 'nan'], {'strict': True, 'key': float}, True),
  3595. (
  3596. ['nan', 0, 'nan', 0],
  3597. {'strict': True, 'key': float, 'reverse': True},
  3598. True,
  3599. ),
  3600. ]:
  3601. key = kwargs.get('key', None)
  3602. reverse = kwargs.get('reverse', False)
  3603. strict = kwargs.get('strict', False)
  3604. with self.subTest(
  3605. iterable=iterable, key=key, reverse=reverse, strict=strict
  3606. ):
  3607. mi_result = mi.is_sorted(
  3608. iter(iterable), key=key, reverse=reverse, strict=strict
  3609. )
  3610. sorted_iterable = sorted(iterable, key=key, reverse=reverse)
  3611. if strict:
  3612. sorted_iterable = list(mi.unique_justseen(sorted_iterable))
  3613. py_result = iterable == sorted_iterable
  3614. self.assertEqual(mi_result, expected)
  3615. self.assertEqual(mi_result, py_result)
  3616. class CallbackIterTests(TestCase):
  3617. def _target(self, cb=None, exc=None, wait=0):
  3618. total = 0
  3619. for i, c in enumerate('abc', 1):
  3620. total += i
  3621. if wait:
  3622. sleep(wait)
  3623. if cb:
  3624. cb(i, c, intermediate_total=total)
  3625. if exc:
  3626. raise exc('error in target')
  3627. return total
  3628. def test_basic(self):
  3629. func = lambda callback=None: self._target(cb=callback, wait=0.02)
  3630. with mi.callback_iter(func, wait_seconds=0.01) as it:
  3631. # Execution doesn't start until we begin iterating
  3632. self.assertFalse(it.done)
  3633. # Consume everything
  3634. self.assertEqual(
  3635. list(it),
  3636. [
  3637. ((1, 'a'), {'intermediate_total': 1}),
  3638. ((2, 'b'), {'intermediate_total': 3}),
  3639. ((3, 'c'), {'intermediate_total': 6}),
  3640. ],
  3641. )
  3642. # After consuming everything the future is done and the
  3643. # result is available.
  3644. self.assertTrue(it.done)
  3645. self.assertEqual(it.result, 6)
  3646. # This examines the internal state of the ThreadPoolExecutor. This
  3647. # isn't documented, so may break in future Python versions.
  3648. self.assertTrue(it._executor._shutdown)
  3649. def test_callback_kwd(self):
  3650. with mi.callback_iter(self._target, callback_kwd='cb') as it:
  3651. self.assertEqual(
  3652. list(it),
  3653. [
  3654. ((1, 'a'), {'intermediate_total': 1}),
  3655. ((2, 'b'), {'intermediate_total': 3}),
  3656. ((3, 'c'), {'intermediate_total': 6}),
  3657. ],
  3658. )
  3659. def test_partial_consumption(self):
  3660. func = lambda callback=None: self._target(cb=callback)
  3661. with mi.callback_iter(func) as it:
  3662. self.assertEqual(next(it), ((1, 'a'), {'intermediate_total': 1}))
  3663. self.assertTrue(it._executor._shutdown)
  3664. def test_abort(self):
  3665. func = lambda callback=None: self._target(cb=callback, wait=0.1)
  3666. with mi.callback_iter(func) as it:
  3667. self.assertEqual(next(it), ((1, 'a'), {'intermediate_total': 1}))
  3668. with self.assertRaises(mi.AbortThread):
  3669. it.result
  3670. def test_no_result(self):
  3671. func = lambda callback=None: self._target(cb=callback)
  3672. with mi.callback_iter(func) as it:
  3673. with self.assertRaises(RuntimeError):
  3674. it.result
  3675. def test_exception(self):
  3676. func = lambda callback=None: self._target(cb=callback, exc=ValueError)
  3677. with mi.callback_iter(func) as it:
  3678. self.assertEqual(
  3679. next(it),
  3680. ((1, 'a'), {'intermediate_total': 1}),
  3681. )
  3682. with self.assertRaises(ValueError):
  3683. it.result
  3684. class WindowedCompleteTests(TestCase):
  3685. """Tests for ``windowed_complete()``"""
  3686. def test_basic(self):
  3687. actual = list(mi.windowed_complete([1, 2, 3, 4, 5], 3))
  3688. expected = [
  3689. ((), (1, 2, 3), (4, 5)),
  3690. ((1,), (2, 3, 4), (5,)),
  3691. ((1, 2), (3, 4, 5), ()),
  3692. ]
  3693. self.assertEqual(actual, expected)
  3694. def test_zero_length(self):
  3695. actual = list(mi.windowed_complete([1, 2, 3], 0))
  3696. expected = [
  3697. ((), (), (1, 2, 3)),
  3698. ((1,), (), (2, 3)),
  3699. ((1, 2), (), (3,)),
  3700. ((1, 2, 3), (), ()),
  3701. ]
  3702. self.assertEqual(actual, expected)
  3703. def test_wrong_length(self):
  3704. seq = [1, 2, 3, 4, 5]
  3705. for n in (-10, -1, len(seq) + 1, len(seq) + 10):
  3706. with self.subTest(n=n):
  3707. with self.assertRaises(ValueError):
  3708. list(mi.windowed_complete(seq, n))
  3709. def test_every_partition(self):
  3710. every_partition = lambda seq: chain(
  3711. *map(partial(mi.windowed_complete, seq), range(len(seq)))
  3712. )
  3713. seq = 'ABC'
  3714. actual = list(every_partition(seq))
  3715. expected = [
  3716. ((), (), ('A', 'B', 'C')),
  3717. (('A',), (), ('B', 'C')),
  3718. (('A', 'B'), (), ('C',)),
  3719. (('A', 'B', 'C'), (), ()),
  3720. ((), ('A',), ('B', 'C')),
  3721. (('A',), ('B',), ('C',)),
  3722. (('A', 'B'), ('C',), ()),
  3723. ((), ('A', 'B'), ('C',)),
  3724. (('A',), ('B', 'C'), ()),
  3725. ]
  3726. self.assertEqual(actual, expected)
  3727. class AllUniqueTests(TestCase):
  3728. def test_basic(self):
  3729. for iterable, expected in [
  3730. ([], True),
  3731. ([1, 2, 3], True),
  3732. ([1, 1], False),
  3733. ([1, 2, 3, 1], False),
  3734. ([1, 2, 3, '1'], True),
  3735. ]:
  3736. with self.subTest(args=(iterable,)):
  3737. self.assertEqual(mi.all_unique(iterable), expected)
  3738. def test_non_hashable(self):
  3739. self.assertEqual(mi.all_unique([[1, 2], [3, 4]]), True)
  3740. self.assertEqual(mi.all_unique([[1, 2], [3, 4], [1, 2]]), False)
  3741. def test_partially_hashable(self):
  3742. self.assertEqual(mi.all_unique([[1, 2], [3, 4], (5, 6)]), True)
  3743. self.assertEqual(
  3744. mi.all_unique([[1, 2], [3, 4], (5, 6), [1, 2]]), False
  3745. )
  3746. self.assertEqual(
  3747. mi.all_unique([[1, 2], [3, 4], (5, 6), (5, 6)]), False
  3748. )
  3749. def test_key(self):
  3750. iterable = ['A', 'B', 'C', 'b']
  3751. self.assertEqual(mi.all_unique(iterable, lambda x: x), True)
  3752. self.assertEqual(mi.all_unique(iterable, str.lower), False)
  3753. def test_infinite(self):
  3754. self.assertEqual(mi.all_unique(mi.prepend(3, count())), False)
  3755. class NthProductTests(TestCase):
  3756. def test_basic(self):
  3757. iterables = ['ab', 'cdef', 'ghi']
  3758. for index, expected in enumerate(product(*iterables)):
  3759. actual = mi.nth_product(index, *iterables)
  3760. self.assertEqual(actual, expected)
  3761. def test_long(self):
  3762. actual = mi.nth_product(1337, range(101), range(22), range(53))
  3763. expected = (1, 3, 12)
  3764. self.assertEqual(actual, expected)
  3765. def test_negative(self):
  3766. iterables = ['abc', 'de', 'fghi']
  3767. for index, expected in enumerate(product(*iterables)):
  3768. actual = mi.nth_product(index - 24, *iterables)
  3769. self.assertEqual(actual, expected)
  3770. def test_invalid_index(self):
  3771. with self.assertRaises(IndexError):
  3772. mi.nth_product(24, 'ab', 'cde', 'fghi')
  3773. class NthCombinationWithReplacementTests(TestCase):
  3774. def test_basic(self):
  3775. iterable = 'abcdefg'
  3776. r = 4
  3777. for index, expected in enumerate(
  3778. combinations_with_replacement(iterable, r)
  3779. ):
  3780. actual = mi.nth_combination_with_replacement(iterable, r, index)
  3781. self.assertEqual(actual, expected)
  3782. def test_long(self):
  3783. actual = mi.nth_combination_with_replacement(range(90), 4, 2000000)
  3784. expected = (22, 65, 68, 81)
  3785. self.assertEqual(actual, expected)
  3786. def test_invalid_r(self):
  3787. for r in (-1, 3):
  3788. with self.assertRaises(ValueError):
  3789. mi.nth_combination_with_replacement([], r, 0)
  3790. def test_invalid_index(self):
  3791. with self.assertRaises(IndexError):
  3792. mi.nth_combination_with_replacement('abcdefg', 3, -85)
  3793. class ValueChainTests(TestCase):
  3794. def test_empty(self):
  3795. actual = list(mi.value_chain())
  3796. expected = []
  3797. self.assertEqual(actual, expected)
  3798. def test_simple(self):
  3799. actual = list(mi.value_chain(1, 2.71828, False, 'foo'))
  3800. expected = [1, 2.71828, False, 'foo']
  3801. self.assertEqual(actual, expected)
  3802. def test_more(self):
  3803. actual = list(mi.value_chain(b'bar', [1, 2, 3], 4, {'key': 1}))
  3804. expected = [b'bar', 1, 2, 3, 4, 'key']
  3805. self.assertEqual(actual, expected)
  3806. def test_empty_lists(self):
  3807. actual = list(mi.value_chain(1, 2, [], [3, 4]))
  3808. expected = [1, 2, 3, 4]
  3809. self.assertEqual(actual, expected)
  3810. def test_complex(self):
  3811. obj = object()
  3812. actual = list(
  3813. mi.value_chain(
  3814. (1, (2, (3,))),
  3815. ['foo', ['bar', ['baz']], 'tic'],
  3816. {'key': {'foo': 1}},
  3817. obj,
  3818. )
  3819. )
  3820. expected = [1, (2, (3,)), 'foo', ['bar', ['baz']], 'tic', 'key', obj]
  3821. self.assertEqual(actual, expected)
  3822. class ProductIndexTests(TestCase):
  3823. def test_basic(self):
  3824. iterables = ['ab', 'cdef', 'ghi']
  3825. first_index = {}
  3826. for index, element in enumerate(product(*iterables)):
  3827. actual = mi.product_index(element, *iterables)
  3828. expected = first_index.setdefault(element, index)
  3829. self.assertEqual(actual, expected)
  3830. def test_multiplicity(self):
  3831. iterables = ['ab', 'bab', 'cab']
  3832. first_index = {}
  3833. for index, element in enumerate(product(*iterables)):
  3834. actual = mi.product_index(element, *iterables)
  3835. expected = first_index.setdefault(element, index)
  3836. self.assertEqual(actual, expected)
  3837. def test_long(self):
  3838. actual = mi.product_index((1, 3, 12), range(101), range(22), range(53))
  3839. expected = 1337
  3840. self.assertEqual(actual, expected)
  3841. def test_invalid_empty(self):
  3842. with self.assertRaises(ValueError):
  3843. mi.product_index('', 'ab', 'cde', 'fghi')
  3844. def test_invalid_small(self):
  3845. with self.assertRaises(ValueError):
  3846. mi.product_index('ac', 'ab', 'cde', 'fghi')
  3847. def test_invalid_large(self):
  3848. with self.assertRaises(ValueError):
  3849. mi.product_index('achi', 'ab', 'cde', 'fghi')
  3850. def test_invalid_match(self):
  3851. with self.assertRaises(ValueError):
  3852. mi.product_index('axf', 'ab', 'cde', 'fghi')
  3853. class CombinationIndexTests(TestCase):
  3854. def test_r_less_than_n(self):
  3855. iterable = 'abcdefg'
  3856. r = 4
  3857. first_index = {}
  3858. for index, element in enumerate(combinations(iterable, r)):
  3859. actual = mi.combination_index(element, iterable)
  3860. expected = first_index.setdefault(element, index)
  3861. self.assertEqual(actual, expected)
  3862. def test_r_equal_to_n(self):
  3863. iterable = 'abcd'
  3864. r = len(iterable)
  3865. first_index = {}
  3866. for index, element in enumerate(combinations(iterable, r=r)):
  3867. actual = mi.combination_index(element, iterable)
  3868. expected = first_index.setdefault(element, index)
  3869. self.assertEqual(actual, expected)
  3870. def test_multiplicity(self):
  3871. iterable = 'abacba'
  3872. r = 3
  3873. first_index = {}
  3874. for index, element in enumerate(combinations(iterable, r)):
  3875. actual = mi.combination_index(element, iterable)
  3876. expected = first_index.setdefault(element, index)
  3877. self.assertEqual(actual, expected)
  3878. def test_null(self):
  3879. actual = mi.combination_index(tuple(), [])
  3880. expected = 0
  3881. self.assertEqual(actual, expected)
  3882. def test_long(self):
  3883. actual = mi.combination_index((2, 12, 35, 126), range(180))
  3884. expected = 2000000
  3885. self.assertEqual(actual, expected)
  3886. def test_invalid_order(self):
  3887. with self.assertRaises(ValueError):
  3888. mi.combination_index(tuple('acb'), 'abcde')
  3889. def test_invalid_large(self):
  3890. with self.assertRaises(ValueError):
  3891. mi.combination_index(tuple('abcdefg'), 'abcdef')
  3892. def test_invalid_match(self):
  3893. with self.assertRaises(ValueError):
  3894. mi.combination_index(tuple('axe'), 'abcde')
  3895. class CombinationWithReplacementIndexTests(TestCase):
  3896. def test_r_less_than_n(self):
  3897. iterable = 'abcdefg'
  3898. r = 4
  3899. first_index = {}
  3900. for index, element in enumerate(
  3901. combinations_with_replacement(iterable, r)
  3902. ):
  3903. actual = mi.combination_with_replacement_index(element, iterable)
  3904. expected = first_index.setdefault(element, index)
  3905. self.assertEqual(actual, expected)
  3906. def test_r_equal_to_n(self):
  3907. iterable = 'abcd'
  3908. r = len(iterable)
  3909. first_index = {}
  3910. for index, element in enumerate(
  3911. combinations_with_replacement(iterable, r=r)
  3912. ):
  3913. actual = mi.combination_with_replacement_index(element, iterable)
  3914. expected = first_index.setdefault(element, index)
  3915. self.assertEqual(actual, expected)
  3916. def test_multiplicity(self):
  3917. iterable = 'abacba'
  3918. r = 3
  3919. first_index = {}
  3920. for index, element in enumerate(
  3921. combinations_with_replacement(iterable, r)
  3922. ):
  3923. actual = mi.combination_with_replacement_index(element, iterable)
  3924. expected = first_index.setdefault(element, index)
  3925. self.assertEqual(actual, expected)
  3926. def test_null(self):
  3927. actual = mi.combination_with_replacement_index(tuple(), [])
  3928. expected = 0
  3929. self.assertEqual(actual, expected)
  3930. def test_long(self):
  3931. actual = mi.combination_with_replacement_index(
  3932. (22, 65, 68, 81), range(90)
  3933. )
  3934. expected = 2000000
  3935. self.assertEqual(actual, expected)
  3936. def test_invalid_order(self):
  3937. with self.assertRaises(ValueError):
  3938. mi.combination_with_replacement_index(tuple('acb'), 'abcde')
  3939. def test_invalid_large(self):
  3940. with self.assertRaises(ValueError):
  3941. mi.combination_with_replacement_index(tuple('abcdefg'), 'abcdef')
  3942. def test_invalid_match(self):
  3943. with self.assertRaises(ValueError):
  3944. mi.combination_with_replacement_index(tuple('axe'), 'abcde')
  3945. class PermutationIndexTests(TestCase):
  3946. def test_r_less_than_n(self):
  3947. iterable = 'abcdefg'
  3948. r = 4
  3949. first_index = {}
  3950. for index, element in enumerate(permutations(iterable, r)):
  3951. actual = mi.permutation_index(element, iterable)
  3952. expected = first_index.setdefault(element, index)
  3953. self.assertEqual(actual, expected)
  3954. def test_r_equal_to_n(self):
  3955. iterable = 'abcd'
  3956. first_index = {}
  3957. for index, element in enumerate(permutations(iterable)):
  3958. actual = mi.permutation_index(element, iterable)
  3959. expected = first_index.setdefault(element, index)
  3960. self.assertEqual(actual, expected)
  3961. def test_multiplicity(self):
  3962. iterable = 'abacba'
  3963. r = 3
  3964. first_index = {}
  3965. for index, element in enumerate(permutations(iterable, r)):
  3966. actual = mi.permutation_index(element, iterable)
  3967. expected = first_index.setdefault(element, index)
  3968. self.assertEqual(actual, expected)
  3969. def test_null(self):
  3970. actual = mi.permutation_index(tuple(), [])
  3971. expected = 0
  3972. self.assertEqual(actual, expected)
  3973. def test_long(self):
  3974. actual = mi.permutation_index((2, 12, 35, 126), range(180))
  3975. expected = 11631678
  3976. self.assertEqual(actual, expected)
  3977. def test_invalid_large(self):
  3978. with self.assertRaises(ValueError):
  3979. mi.permutation_index(tuple('abcdefg'), 'abcdef')
  3980. def test_invalid_match(self):
  3981. with self.assertRaises(ValueError):
  3982. mi.permutation_index(tuple('axe'), 'abcde')
  3983. class CountableTests(TestCase):
  3984. def test_empty(self):
  3985. iterable = []
  3986. it = mi.countable(iterable)
  3987. self.assertEqual(it.items_seen, 0)
  3988. self.assertEqual(list(it), [])
  3989. def test_basic(self):
  3990. iterable = '0123456789'
  3991. it = mi.countable(iterable)
  3992. self.assertEqual(it.items_seen, 0)
  3993. self.assertEqual(next(it), '0')
  3994. self.assertEqual(it.items_seen, 1)
  3995. self.assertEqual(''.join(it), '123456789')
  3996. self.assertEqual(it.items_seen, 10)
  3997. class ChunkedEvenTests(TestCase):
  3998. """Tests for ``chunked_even()``"""
  3999. def test_0(self):
  4000. self._test_finite('', 3, [])
  4001. def test_1(self):
  4002. self._test_finite('A', 1, [['A']])
  4003. def test_4(self):
  4004. self._test_finite('ABCD', 3, [['A', 'B'], ['C', 'D']])
  4005. def test_5(self):
  4006. self._test_finite('ABCDE', 3, [['A', 'B', 'C'], ['D', 'E']])
  4007. def test_6(self):
  4008. self._test_finite('ABCDEF', 3, [['A', 'B', 'C'], ['D', 'E', 'F']])
  4009. def test_7(self):
  4010. self._test_finite(
  4011. 'ABCDEFG', 3, [['A', 'B', 'C'], ['D', 'E'], ['F', 'G']]
  4012. )
  4013. def _test_finite(self, seq, n, expected):
  4014. # Check with and without `len()`
  4015. self.assertEqual(list(mi.chunked_even(seq, n)), expected)
  4016. self.assertEqual(list(mi.chunked_even(iter(seq), n)), expected)
  4017. def test_infinite(self):
  4018. for n in range(1, 5):
  4019. k = 0
  4020. def count_with_assert():
  4021. for i in count():
  4022. # Look-ahead should be less than n^2
  4023. self.assertLessEqual(i, n * k + n * n)
  4024. yield i
  4025. ls = mi.chunked_even(count_with_assert(), n)
  4026. while k < 2:
  4027. self.assertEqual(next(ls), list(range(k * n, (k + 1) * n)))
  4028. k += 1
  4029. def test_evenness(self):
  4030. for N in range(1, 50):
  4031. for n in range(1, N + 2):
  4032. lengths = []
  4033. items = []
  4034. for l in mi.chunked_even(range(N), n):
  4035. L = len(l)
  4036. self.assertLessEqual(L, n)
  4037. self.assertGreaterEqual(L, 1)
  4038. lengths.append(L)
  4039. items.extend(l)
  4040. self.assertEqual(items, list(range(N)))
  4041. self.assertLessEqual(max(lengths) - min(lengths), 1)
  4042. class ZipBroadcastTests(TestCase):
  4043. def test_zip(self):
  4044. for objects, zipped, strict_ok in [
  4045. # Empty
  4046. ([], [], True),
  4047. # One argument
  4048. ([1], [(1,)], True),
  4049. ([[1]], [(1,)], True),
  4050. ([[1, 2]], [(1,), (2,)], True),
  4051. # All scalars
  4052. ([1, 2], [(1, 2)], True),
  4053. ([1, 2, 3], [(1, 2, 3)], True),
  4054. # Iterables with length = 0
  4055. ([[], 1], [], True),
  4056. ([1, []], [], True),
  4057. ([[], []], [], True),
  4058. ([[], 1, 2], [], True),
  4059. ([[], 1, []], [], True),
  4060. ([1, [], 2], [], True),
  4061. ([1, [], []], [], True),
  4062. ([[], [], 1], [], True),
  4063. ([[], [], []], [], True),
  4064. # Iterables with length = 1
  4065. ([1, [2]], [(1, 2)], True),
  4066. ([[1], 2], [(1, 2)], True),
  4067. ([[1], [2]], [(1, 2)], True),
  4068. ([1, [2], 3], [(1, 2, 3)], True),
  4069. ([1, [2], [3]], [(1, 2, 3)], True),
  4070. ([[1], 2, 3], [(1, 2, 3)], True),
  4071. ([[1], 2, [3]], [(1, 2, 3)], True),
  4072. ([[1], [2], 3], [(1, 2, 3)], True),
  4073. ([[1], [2], [3]], [(1, 2, 3)], True),
  4074. # Iterables with length > 1
  4075. ([1, [2, 3]], [(1, 2), (1, 3)], True),
  4076. ([[1, 2], 3], [(1, 3), (2, 3)], True),
  4077. ([[1, 2], [3, 4]], [(1, 3), (2, 4)], True),
  4078. ([1, [2, 3], 4], [(1, 2, 4), (1, 3, 4)], True),
  4079. ([1, [2, 3], [4, 5]], [(1, 2, 4), (1, 3, 5)], True),
  4080. ([[1, 2], 3, 4], [(1, 3, 4), (2, 3, 4)], True),
  4081. ([[1, 2], 3, [4, 5]], [(1, 3, 4), (2, 3, 5)], True),
  4082. ([[1, 2], [3, 4], 5], [(1, 3, 5), (2, 4, 5)], True),
  4083. ([[1, 2], [3, 4], [5, 6]], [(1, 3, 5), (2, 4, 6)], True),
  4084. # Iterables with different lengths
  4085. ([[], [1]], [], False),
  4086. ([[1], []], [], False),
  4087. ([[1], [2, 3]], [(1, 2)], False),
  4088. ([[1, 2], [3]], [(1, 3)], False),
  4089. ([[1, 2], [3], [4]], [(1, 3, 4)], False),
  4090. ([[1], [2, 3], [4]], [(1, 2, 4)], False),
  4091. ([[1], [2], [3, 4]], [(1, 2, 3)], False),
  4092. ([[1], [2, 3], [4, 5]], [(1, 2, 4)], False),
  4093. ([[1, 2], [3], [4, 5]], [(1, 3, 4)], False),
  4094. ([[1, 2], [3, 4], [5]], [(1, 3, 5)], False),
  4095. ([1, [2, 3], [4, 5, 6]], [(1, 2, 4), (1, 3, 5)], False),
  4096. ([[1, 2], 3, [4, 5, 6]], [(1, 3, 4), (2, 3, 5)], False),
  4097. ([1, [2, 3, 4], [5, 6]], [(1, 2, 5), (1, 3, 6)], False),
  4098. ([[1, 2, 3], 4, [5, 6]], [(1, 4, 5), (2, 4, 6)], False),
  4099. ([[1, 2], [3, 4, 5], 6], [(1, 3, 6), (2, 4, 6)], False),
  4100. ([[1, 2, 3], [4, 5], 6], [(1, 4, 6), (2, 5, 6)], False),
  4101. # Infinite
  4102. ([count(), 1, [2]], [(0, 1, 2)], False),
  4103. ([count(), 1, [2, 3]], [(0, 1, 2), (1, 1, 3)], False),
  4104. # Miscellaneous
  4105. (['a', [1, 2], [3, 4, 5]], [('a', 1, 3), ('a', 2, 4)], False),
  4106. ]:
  4107. # Truncate by default
  4108. with self.subTest(objects=objects, strict=False, zipped=zipped):
  4109. self.assertEqual(list(mi.zip_broadcast(*objects)), zipped)
  4110. # Raise an exception for strict=True
  4111. with self.subTest(objects=objects, strict=True, zipped=zipped):
  4112. if strict_ok:
  4113. self.assertEqual(
  4114. list(mi.zip_broadcast(*objects, strict=True)),
  4115. zipped,
  4116. )
  4117. else:
  4118. with self.assertRaises(ValueError):
  4119. list(mi.zip_broadcast(*objects, strict=True))
  4120. def test_scalar_types(self):
  4121. # Default: str and bytes are treated as scalar
  4122. self.assertEqual(
  4123. list(mi.zip_broadcast('ab', [1, 2, 3])),
  4124. [('ab', 1), ('ab', 2), ('ab', 3)],
  4125. )
  4126. self.assertEqual(
  4127. list(mi.zip_broadcast(b'ab', [1, 2, 3])),
  4128. [(b'ab', 1), (b'ab', 2), (b'ab', 3)],
  4129. )
  4130. # scalar_types=None allows str and bytes to be treated as iterable
  4131. self.assertEqual(
  4132. list(mi.zip_broadcast('abc', [1, 2, 3], scalar_types=None)),
  4133. [('a', 1), ('b', 2), ('c', 3)],
  4134. )
  4135. # Use a custom type
  4136. self.assertEqual(
  4137. list(mi.zip_broadcast({'a': 'b'}, [1, 2, 3], scalar_types=dict)),
  4138. [({'a': 'b'}, 1), ({'a': 'b'}, 2), ({'a': 'b'}, 3)],
  4139. )
  4140. class UniqueInWindowTests(TestCase):
  4141. def test_invalid_n(self):
  4142. with self.assertRaises(ValueError):
  4143. list(mi.unique_in_window([], 0))
  4144. def test_basic(self):
  4145. for iterable, n, expected in [
  4146. (range(9), 10, list(range(9))),
  4147. (range(20), 10, list(range(20))),
  4148. ([1, 2, 3, 4, 4, 4], 1, [1, 2, 3, 4, 4, 4]),
  4149. ([1, 2, 3, 4, 4, 4], 2, [1, 2, 3, 4]),
  4150. ([1, 2, 3, 4, 4, 4], 3, [1, 2, 3, 4]),
  4151. ([1, 2, 3, 4, 4, 4], 4, [1, 2, 3, 4]),
  4152. ([1, 2, 3, 4, 4, 4], 5, [1, 2, 3, 4]),
  4153. (
  4154. [0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 2, 3, 4, 2],
  4155. 2,
  4156. [0, 1, 0, 2, 3, 4, 2],
  4157. ),
  4158. ]:
  4159. with self.subTest(expected=expected):
  4160. actual = list(mi.unique_in_window(iterable, n))
  4161. self.assertEqual(actual, expected)
  4162. def test_key(self):
  4163. iterable = [0, 1, 3, 4, 5, 6, 7, 8, 9]
  4164. n = 3
  4165. key = lambda x: x // 3
  4166. actual = list(mi.unique_in_window(iterable, n, key=key))
  4167. expected = [0, 3, 6, 9]
  4168. self.assertEqual(actual, expected)
  4169. class StrictlyNTests(TestCase):
  4170. def test_basic(self):
  4171. iterable = ['a', 'b', 'c', 'd']
  4172. n = 4
  4173. actual = list(mi.strictly_n(iter(iterable), n))
  4174. expected = iterable
  4175. self.assertEqual(actual, expected)
  4176. def test_too_short_default(self):
  4177. iterable = ['a', 'b', 'c', 'd']
  4178. n = 5
  4179. with self.assertRaises(ValueError) as exc:
  4180. list(mi.strictly_n(iter(iterable), n))
  4181. self.assertEqual(
  4182. 'Too few items in iterable (got 4)', exc.exception.args[0]
  4183. )
  4184. def test_too_long_default(self):
  4185. iterable = ['a', 'b', 'c', 'd']
  4186. n = 3
  4187. with self.assertRaises(ValueError) as cm:
  4188. list(mi.strictly_n(iter(iterable), n))
  4189. self.assertEqual(
  4190. 'Too many items in iterable (got at least 4)',
  4191. cm.exception.args[0],
  4192. )
  4193. def test_too_short_custom(self):
  4194. call_count = 0
  4195. def too_short(item_count):
  4196. nonlocal call_count
  4197. call_count += 1
  4198. iterable = ['a', 'b', 'c', 'd']
  4199. n = 6
  4200. actual = []
  4201. for item in mi.strictly_n(iter(iterable), n, too_short=too_short):
  4202. actual.append(item)
  4203. expected = ['a', 'b', 'c', 'd']
  4204. self.assertEqual(actual, expected)
  4205. self.assertEqual(call_count, 1)
  4206. def test_too_long_custom(self):
  4207. import logging
  4208. iterable = ['a', 'b', 'c', 'd']
  4209. n = 2
  4210. too_long = lambda item_count: logging.warning(
  4211. 'Picked the first %s items', n
  4212. )
  4213. with self.assertLogs(level='WARNING') as cm:
  4214. actual = list(mi.strictly_n(iter(iterable), n, too_long=too_long))
  4215. self.assertEqual(actual, ['a', 'b'])
  4216. self.assertIn('Picked the first 2 items', cm.output[0])
  4217. class DuplicatesEverSeenTests(TestCase):
  4218. def test_basic(self):
  4219. for iterable, expected in [
  4220. ([], []),
  4221. ([1, 2, 3], []),
  4222. ([1, 1], [1]),
  4223. ([1, 2, 1, 2], [1, 2]),
  4224. ([1, 2, 3, '1'], []),
  4225. ]:
  4226. with self.subTest(args=(iterable,)):
  4227. self.assertEqual(
  4228. list(mi.duplicates_everseen(iterable)), expected
  4229. )
  4230. def test_non_hashable(self):
  4231. self.assertEqual(list(mi.duplicates_everseen([[1, 2], [3, 4]])), [])
  4232. self.assertEqual(
  4233. list(mi.duplicates_everseen([[1, 2], [3, 4], [1, 2]])), [[1, 2]]
  4234. )
  4235. def test_partially_hashable(self):
  4236. self.assertEqual(
  4237. list(mi.duplicates_everseen([[1, 2], [3, 4], (5, 6)])), []
  4238. )
  4239. self.assertEqual(
  4240. list(mi.duplicates_everseen([[1, 2], [3, 4], (5, 6), [1, 2]])),
  4241. [[1, 2]],
  4242. )
  4243. self.assertEqual(
  4244. list(mi.duplicates_everseen([[1, 2], [3, 4], (5, 6), (5, 6)])),
  4245. [(5, 6)],
  4246. )
  4247. def test_key_hashable(self):
  4248. iterable = 'HEheHEhe'
  4249. self.assertEqual(list(mi.duplicates_everseen(iterable)), list('HEhe'))
  4250. self.assertEqual(
  4251. list(mi.duplicates_everseen(iterable, str.lower)),
  4252. list('heHEhe'),
  4253. )
  4254. def test_key_non_hashable(self):
  4255. iterable = [[1, 2], [3, 0], [5, -2], [5, 6]]
  4256. self.assertEqual(
  4257. list(mi.duplicates_everseen(iterable, lambda x: x)), []
  4258. )
  4259. self.assertEqual(
  4260. list(mi.duplicates_everseen(iterable, sum)), [[3, 0], [5, -2]]
  4261. )
  4262. def test_key_partially_hashable(self):
  4263. iterable = [[1, 2], (1, 2), [1, 2], [5, 6]]
  4264. self.assertEqual(
  4265. list(mi.duplicates_everseen(iterable, lambda x: x)), [[1, 2]]
  4266. )
  4267. self.assertEqual(
  4268. list(mi.duplicates_everseen(iterable, list)), [(1, 2), [1, 2]]
  4269. )
  4270. class DuplicatesJustSeenTests(TestCase):
  4271. def test_basic(self):
  4272. for iterable, expected in [
  4273. ([], []),
  4274. ([1, 2, 3, 3, 2, 2], [3, 2]),
  4275. ([1, 1], [1]),
  4276. ([1, 2, 1, 2], []),
  4277. ([1, 2, 3, '1'], []),
  4278. ]:
  4279. with self.subTest(args=(iterable,)):
  4280. self.assertEqual(
  4281. list(mi.duplicates_justseen(iterable)), expected
  4282. )
  4283. def test_non_hashable(self):
  4284. self.assertEqual(list(mi.duplicates_justseen([[1, 2], [3, 4]])), [])
  4285. self.assertEqual(
  4286. list(
  4287. mi.duplicates_justseen(
  4288. [[1, 2], [3, 4], [3, 4], [3, 4], [1, 2]]
  4289. )
  4290. ),
  4291. [[3, 4], [3, 4]],
  4292. )
  4293. def test_partially_hashable(self):
  4294. self.assertEqual(
  4295. list(mi.duplicates_justseen([[1, 2], [3, 4], (5, 6)])), []
  4296. )
  4297. self.assertEqual(
  4298. list(
  4299. mi.duplicates_justseen(
  4300. [[1, 2], [3, 4], (5, 6), [1, 2], [1, 2]]
  4301. )
  4302. ),
  4303. [[1, 2]],
  4304. )
  4305. self.assertEqual(
  4306. list(
  4307. mi.duplicates_justseen(
  4308. [[1, 2], [3, 4], (5, 6), (5, 6), (5, 6)]
  4309. )
  4310. ),
  4311. [(5, 6), (5, 6)],
  4312. )
  4313. def test_key_hashable(self):
  4314. iterable = 'HEheHHHhEheeEe'
  4315. self.assertEqual(list(mi.duplicates_justseen(iterable)), list('HHe'))
  4316. self.assertEqual(
  4317. list(mi.duplicates_justseen(iterable, str.lower)),
  4318. list('HHheEe'),
  4319. )
  4320. def test_key_non_hashable(self):
  4321. iterable = [[1, 2], [3, 0], [5, -2], [5, 6], [1, 2]]
  4322. self.assertEqual(
  4323. list(mi.duplicates_justseen(iterable, lambda x: x)), []
  4324. )
  4325. self.assertEqual(
  4326. list(mi.duplicates_justseen(iterable, sum)), [[3, 0], [5, -2]]
  4327. )
  4328. def test_key_partially_hashable(self):
  4329. iterable = [[1, 2], (1, 2), [1, 2], [5, 6], [1, 2]]
  4330. self.assertEqual(
  4331. list(mi.duplicates_justseen(iterable, lambda x: x)), []
  4332. )
  4333. self.assertEqual(
  4334. list(mi.duplicates_justseen(iterable, list)), [(1, 2), [1, 2]]
  4335. )
  4336. def test_nested(self):
  4337. iterable = [[[1, 2], [1, 2]], [5, 6], [5, 6]]
  4338. self.assertEqual(list(mi.duplicates_justseen(iterable)), [[5, 6]])
  4339. class ClassifyUniqueTests(TestCase):
  4340. def test_basic(self):
  4341. self.assertEqual(
  4342. list(mi.classify_unique('mississippi')),
  4343. [
  4344. ('m', True, True),
  4345. ('i', True, True),
  4346. ('s', True, True),
  4347. ('s', False, False),
  4348. ('i', True, False),
  4349. ('s', True, False),
  4350. ('s', False, False),
  4351. ('i', True, False),
  4352. ('p', True, True),
  4353. ('p', False, False),
  4354. ('i', True, False),
  4355. ],
  4356. )
  4357. def test_non_hashable(self):
  4358. self.assertEqual(
  4359. list(mi.classify_unique([[1, 2], [3, 4], [3, 4], [1, 2]])),
  4360. [
  4361. ([1, 2], True, True),
  4362. ([3, 4], True, True),
  4363. ([3, 4], False, False),
  4364. ([1, 2], True, False),
  4365. ],
  4366. )
  4367. def test_partially_hashable(self):
  4368. self.assertEqual(
  4369. list(
  4370. mi.classify_unique(
  4371. [[1, 2], [3, 4], (5, 6), (5, 6), (3, 4), [1, 2]]
  4372. )
  4373. ),
  4374. [
  4375. ([1, 2], True, True),
  4376. ([3, 4], True, True),
  4377. ((5, 6), True, True),
  4378. ((5, 6), False, False),
  4379. ((3, 4), True, True),
  4380. ([1, 2], True, False),
  4381. ],
  4382. )
  4383. def test_key_hashable(self):
  4384. iterable = 'HEheHHHhEheeEe'
  4385. self.assertEqual(
  4386. list(mi.classify_unique(iterable)),
  4387. [
  4388. ('H', True, True),
  4389. ('E', True, True),
  4390. ('h', True, True),
  4391. ('e', True, True),
  4392. ('H', True, False),
  4393. ('H', False, False),
  4394. ('H', False, False),
  4395. ('h', True, False),
  4396. ('E', True, False),
  4397. ('h', True, False),
  4398. ('e', True, False),
  4399. ('e', False, False),
  4400. ('E', True, False),
  4401. ('e', True, False),
  4402. ],
  4403. )
  4404. self.assertEqual(
  4405. list(mi.classify_unique(iterable, str.lower)),
  4406. [
  4407. ('H', True, True),
  4408. ('E', True, True),
  4409. ('h', True, False),
  4410. ('e', True, False),
  4411. ('H', True, False),
  4412. ('H', False, False),
  4413. ('H', False, False),
  4414. ('h', False, False),
  4415. ('E', True, False),
  4416. ('h', True, False),
  4417. ('e', True, False),
  4418. ('e', False, False),
  4419. ('E', False, False),
  4420. ('e', False, False),
  4421. ],
  4422. )
  4423. def test_key_non_hashable(self):
  4424. iterable = [[1, 2], [3, 0], [5, -2], [5, 6], [1, 2]]
  4425. self.assertEqual(
  4426. list(mi.classify_unique(iterable, lambda x: x)),
  4427. [
  4428. ([1, 2], True, True),
  4429. ([3, 0], True, True),
  4430. ([5, -2], True, True),
  4431. ([5, 6], True, True),
  4432. ([1, 2], True, False),
  4433. ],
  4434. )
  4435. self.assertEqual(
  4436. list(mi.classify_unique(iterable, sum)),
  4437. [
  4438. ([1, 2], True, True),
  4439. ([3, 0], False, False),
  4440. ([5, -2], False, False),
  4441. ([5, 6], True, True),
  4442. ([1, 2], True, False),
  4443. ],
  4444. )
  4445. def test_key_partially_hashable(self):
  4446. iterable = [[1, 2], (1, 2), [1, 2], [5, 6], [1, 2]]
  4447. self.assertEqual(
  4448. list(mi.classify_unique(iterable, lambda x: x)),
  4449. [
  4450. ([1, 2], True, True),
  4451. ((1, 2), True, True),
  4452. ([1, 2], True, False),
  4453. ([5, 6], True, True),
  4454. ([1, 2], True, False),
  4455. ],
  4456. )
  4457. self.assertEqual(
  4458. list(mi.classify_unique(iterable, list)),
  4459. [
  4460. ([1, 2], True, True),
  4461. ((1, 2), False, False),
  4462. ([1, 2], False, False),
  4463. ([5, 6], True, True),
  4464. ([1, 2], True, False),
  4465. ],
  4466. )
  4467. def test_vs_unique_everseen(self):
  4468. input = 'AAAABBBBCCDAABBB'
  4469. output = [e for e, j, u in mi.classify_unique(input) if u]
  4470. self.assertEqual(output, ['A', 'B', 'C', 'D'])
  4471. self.assertEqual(list(mi.unique_everseen(input)), output)
  4472. def test_vs_unique_everseen_key(self):
  4473. input = 'aAbACCc'
  4474. output = [e for e, j, u in mi.classify_unique(input, str.lower) if u]
  4475. self.assertEqual(output, list('abC'))
  4476. self.assertEqual(list(mi.unique_everseen(input, str.lower)), output)
  4477. def test_vs_unique_justseen(self):
  4478. input = 'AAAABBBCCDABB'
  4479. output = [e for e, j, u in mi.classify_unique(input) if j]
  4480. self.assertEqual(output, list('ABCDAB'))
  4481. self.assertEqual(list(mi.unique_justseen(input)), output)
  4482. def test_vs_unique_justseen_key(self):
  4483. input = 'AABCcAD'
  4484. output = [e for e, j, u in mi.classify_unique(input, str.lower) if j]
  4485. self.assertEqual(output, list('ABCAD'))
  4486. self.assertEqual(list(mi.unique_justseen(input, str.lower)), output)
  4487. def test_vs_duplicates_everseen(self):
  4488. input = [1, 2, 1, 2]
  4489. output = [e for e, j, u in mi.classify_unique(input) if not u]
  4490. self.assertEqual(output, [1, 2])
  4491. self.assertEqual(list(mi.duplicates_everseen(input)), output)
  4492. def test_vs_duplicates_everseen_key(self):
  4493. input = 'HEheHEhe'
  4494. output = [
  4495. e for e, j, u in mi.classify_unique(input, str.lower) if not u
  4496. ]
  4497. self.assertEqual(output, list('heHEhe'))
  4498. self.assertEqual(
  4499. list(mi.duplicates_everseen(input, str.lower)), output
  4500. )
  4501. def test_vs_duplicates_justseen(self):
  4502. input = [1, 2, 3, 3, 2, 2]
  4503. output = [e for e, j, u in mi.classify_unique(input) if not j]
  4504. self.assertEqual(output, [3, 2])
  4505. self.assertEqual(list(mi.duplicates_justseen(input)), output)
  4506. def test_vs_duplicates_justseen_key(self):
  4507. input = 'HEheHHHhEheeEe'
  4508. output = [
  4509. e for e, j, u in mi.classify_unique(input, str.lower) if not j
  4510. ]
  4511. self.assertEqual(output, list('HHheEe'))
  4512. self.assertEqual(
  4513. list(mi.duplicates_justseen(input, str.lower)), output
  4514. )
  4515. class LongestCommonPrefixTests(TestCase):
  4516. def test_basic(self):
  4517. iterables = [[1, 2], [1, 2, 3], [1, 2, 4]]
  4518. self.assertEqual(list(mi.longest_common_prefix(iterables)), [1, 2])
  4519. def test_iterators(self):
  4520. iterables = iter([iter([1, 2]), iter([1, 2, 3]), iter([1, 2, 4])])
  4521. self.assertEqual(list(mi.longest_common_prefix(iterables)), [1, 2])
  4522. def test_no_iterables(self):
  4523. iterables = []
  4524. self.assertEqual(list(mi.longest_common_prefix(iterables)), [])
  4525. def test_empty_iterables_only(self):
  4526. iterables = [[], [], []]
  4527. self.assertEqual(list(mi.longest_common_prefix(iterables)), [])
  4528. def test_includes_empty_iterables(self):
  4529. iterables = [[1, 2], [1, 2, 3], [1, 2, 4], []]
  4530. self.assertEqual(list(mi.longest_common_prefix(iterables)), [])
  4531. def test_non_hashable(self):
  4532. # See https://github.com/more-itertools/more-itertools/issues/603
  4533. iterables = [[[1], [2]], [[1], [2], [3]], [[1], [2], [4]]]
  4534. self.assertEqual(list(mi.longest_common_prefix(iterables)), [[1], [2]])
  4535. def test_prefix_contains_elements_of_the_first_iterable(self):
  4536. iterables = [[[1], [2]], [[1], [2], [3]], [[1], [2], [4]]]
  4537. prefix = list(mi.longest_common_prefix(iterables))
  4538. self.assertIs(prefix[0], iterables[0][0])
  4539. self.assertIs(prefix[1], iterables[0][1])
  4540. self.assertIsNot(prefix[0], iterables[1][0])
  4541. self.assertIsNot(prefix[1], iterables[1][1])
  4542. self.assertIsNot(prefix[0], iterables[2][0])
  4543. self.assertIsNot(prefix[1], iterables[2][1])
  4544. def test_infinite_iterables(self):
  4545. prefix = mi.longest_common_prefix([count(), count()])
  4546. self.assertEqual(next(prefix), 0)
  4547. self.assertEqual(next(prefix), 1)
  4548. self.assertEqual(next(prefix), 2)
  4549. def test_contains_infinite_iterables(self):
  4550. iterables = [[0, 1, 2], count()]
  4551. self.assertEqual(list(mi.longest_common_prefix(iterables)), [0, 1, 2])
  4552. class IequalsTests(TestCase):
  4553. def test_basic(self):
  4554. self.assertTrue(mi.iequals("abc", iter("abc")))
  4555. self.assertTrue(mi.iequals(range(3), [0, 1, 2]))
  4556. self.assertFalse(mi.iequals("abc", [0, 1, 2]))
  4557. def test_no_iterables(self):
  4558. self.assertTrue(mi.iequals())
  4559. def test_one_iterable(self):
  4560. self.assertTrue(mi.iequals("abc"))
  4561. def test_more_than_two_iterable(self):
  4562. self.assertTrue(mi.iequals("abc", iter("abc"), ['a', 'b', 'c']))
  4563. self.assertFalse(mi.iequals("abc", iter("abc"), ['a', 'b', 'd']))
  4564. def test_order_matters(self):
  4565. self.assertFalse(mi.iequals("abc", "acb"))
  4566. def test_not_equal_lengths(self):
  4567. self.assertFalse(mi.iequals("abc", "ab"))
  4568. self.assertFalse(mi.iequals("abc", "bc"))
  4569. self.assertFalse(mi.iequals("aaa", "aaaa"))
  4570. def test_empty_iterables(self):
  4571. self.assertTrue(mi.iequals([], ""))
  4572. def test_none_is_not_a_sentinel(self):
  4573. # See https://stackoverflow.com/a/900444
  4574. self.assertFalse(mi.iequals([1, 2], [1, 2, None]))
  4575. self.assertFalse(mi.iequals([1, 2], [None, 1, 2]))
  4576. def test_not_identical_but_equal(self):
  4577. self.assertTrue([1, True], [1.0, complex(1, 0)])
  4578. class ConstrainedBatchesTests(TestCase):
  4579. def test_basic(self):
  4580. zen = [
  4581. 'Beautiful is better than ugly',
  4582. 'Explicit is better than implicit',
  4583. 'Simple is better than complex',
  4584. 'Complex is better than complicated',
  4585. 'Flat is better than nested',
  4586. 'Sparse is better than dense',
  4587. 'Readability counts',
  4588. ]
  4589. for size, expected in (
  4590. (
  4591. 34,
  4592. [
  4593. (zen[0],),
  4594. (zen[1],),
  4595. (zen[2],),
  4596. (zen[3],),
  4597. (zen[4],),
  4598. (zen[5],),
  4599. (zen[6],),
  4600. ],
  4601. ),
  4602. (
  4603. 61,
  4604. [
  4605. (zen[0], zen[1]),
  4606. (zen[2],),
  4607. (zen[3], zen[4]),
  4608. (zen[5], zen[6]),
  4609. ],
  4610. ),
  4611. (
  4612. 90,
  4613. [
  4614. (zen[0], zen[1], zen[2]),
  4615. (zen[3], zen[4], zen[5]),
  4616. (zen[6],),
  4617. ],
  4618. ),
  4619. (
  4620. 124,
  4621. [(zen[0], zen[1], zen[2], zen[3]), (zen[4], zen[5], zen[6])],
  4622. ),
  4623. (
  4624. 150,
  4625. [(zen[0], zen[1], zen[2], zen[3], zen[4]), (zen[5], zen[6])],
  4626. ),
  4627. (
  4628. 177,
  4629. [(zen[0], zen[1], zen[2], zen[3], zen[4], zen[5]), (zen[6],)],
  4630. ),
  4631. ):
  4632. with self.subTest(size=size):
  4633. actual = list(mi.constrained_batches(iter(zen), size))
  4634. self.assertEqual(actual, expected)
  4635. def test_max_count(self):
  4636. iterable = ['1', '1', '12345678', '12345', '12345']
  4637. max_size = 10
  4638. max_count = 2
  4639. actual = list(mi.constrained_batches(iterable, max_size, max_count))
  4640. expected = [('1', '1'), ('12345678',), ('12345', '12345')]
  4641. self.assertEqual(actual, expected)
  4642. def test_strict(self):
  4643. iterable = ['1', '123456789', '1']
  4644. size = 8
  4645. with self.assertRaises(ValueError):
  4646. list(mi.constrained_batches(iterable, size))
  4647. actual = list(mi.constrained_batches(iterable, size, strict=False))
  4648. expected = [('1',), ('123456789',), ('1',)]
  4649. self.assertEqual(actual, expected)
  4650. def test_get_len(self):
  4651. class Record(tuple):
  4652. def total_size(self):
  4653. return sum(len(x) for x in self)
  4654. record_3 = Record(('1', '23'))
  4655. record_5 = Record(('1234', '1'))
  4656. record_10 = Record(('1', '12345678', '1'))
  4657. record_2 = Record(('1', '1'))
  4658. iterable = [record_3, record_5, record_10, record_2]
  4659. self.assertEqual(
  4660. list(
  4661. mi.constrained_batches(
  4662. iterable, 10, get_len=lambda x: x.total_size()
  4663. )
  4664. ),
  4665. [(record_3, record_5), (record_10,), (record_2,)],
  4666. )
  4667. class GrayProductTests(TestCase):
  4668. def test_basic(self):
  4669. self.assertEqual(
  4670. tuple(mi.gray_product(('a', 'b', 'c'), range(1, 3))),
  4671. (("a", 1), ("b", 1), ("c", 1), ("c", 2), ("b", 2), ("a", 2)),
  4672. )
  4673. out = mi.gray_product(('foo', 'bar'), (3, 4, 5, 6), ['quz', 'baz'])
  4674. self.assertEqual(next(out), ('foo', 3, 'quz'))
  4675. self.assertEqual(
  4676. list(out),
  4677. [
  4678. ('bar', 3, 'quz'),
  4679. ('bar', 4, 'quz'),
  4680. ('foo', 4, 'quz'),
  4681. ('foo', 5, 'quz'),
  4682. ('bar', 5, 'quz'),
  4683. ('bar', 6, 'quz'),
  4684. ('foo', 6, 'quz'),
  4685. ('foo', 6, 'baz'),
  4686. ('bar', 6, 'baz'),
  4687. ('bar', 5, 'baz'),
  4688. ('foo', 5, 'baz'),
  4689. ('foo', 4, 'baz'),
  4690. ('bar', 4, 'baz'),
  4691. ('bar', 3, 'baz'),
  4692. ('foo', 3, 'baz'),
  4693. ],
  4694. )
  4695. self.assertEqual(tuple(mi.gray_product()), ((),))
  4696. self.assertEqual(tuple(mi.gray_product((1, 2))), ((1,), (2,)))
  4697. def test_errors(self):
  4698. with self.assertRaises(ValueError):
  4699. list(mi.gray_product((1, 2), ()))
  4700. with self.assertRaises(ValueError):
  4701. list(mi.gray_product((1, 2), (2,)))
  4702. def test_vs_product(self):
  4703. iters = (
  4704. ("a", "b"),
  4705. range(3, 6),
  4706. [None, None],
  4707. {"i", "j", "k", "l"},
  4708. "XYZ",
  4709. )
  4710. self.assertEqual(
  4711. sorted(product(*iters)), sorted(mi.gray_product(*iters))
  4712. )
  4713. class PartialProductTests(TestCase):
  4714. def test_no_iterables(self):
  4715. self.assertEqual(tuple(mi.partial_product()), ((),))
  4716. def test_empty_iterable(self):
  4717. self.assertEqual(tuple(mi.partial_product('AB', '', 'CD')), ())
  4718. def test_one_iterable(self):
  4719. # a single iterable should pass through
  4720. self.assertEqual(
  4721. tuple(mi.partial_product('ABCD')),
  4722. (
  4723. ('A',),
  4724. ('B',),
  4725. ('C',),
  4726. ('D',),
  4727. ),
  4728. )
  4729. def test_two_iterables(self):
  4730. self.assertEqual(
  4731. list(mi.partial_product('ABCD', [1])),
  4732. [('A', 1), ('B', 1), ('C', 1), ('D', 1)],
  4733. )
  4734. expected = [
  4735. ('A', 1),
  4736. ('B', 1),
  4737. ('C', 1),
  4738. ('D', 1),
  4739. ('D', 2),
  4740. ('D', 3),
  4741. ('D', 4),
  4742. ]
  4743. self.assertEqual(
  4744. list(mi.partial_product('ABCD', [1, 2, 3, 4])), expected
  4745. )
  4746. def test_basic(self):
  4747. ones = [1, 2, 3]
  4748. tens = [10, 20, 30, 40, 50]
  4749. hundreds = [100, 200]
  4750. expected = [
  4751. (1, 10, 100),
  4752. (2, 10, 100),
  4753. (3, 10, 100),
  4754. (3, 20, 100),
  4755. (3, 30, 100),
  4756. (3, 40, 100),
  4757. (3, 50, 100),
  4758. (3, 50, 200),
  4759. ]
  4760. actual = list(mi.partial_product(ones, tens, hundreds))
  4761. self.assertEqual(actual, expected)
  4762. def test_uneven_length_iterables(self):
  4763. # this is also the docstring example
  4764. expected = [
  4765. ('A', 'C', 'D'),
  4766. ('B', 'C', 'D'),
  4767. ('B', 'C', 'E'),
  4768. ('B', 'C', 'F'),
  4769. ]
  4770. self.assertEqual(list(mi.partial_product('AB', 'C', 'DEF')), expected)
  4771. class IterateTests(TestCase):
  4772. def test_basic(self) -> None:
  4773. result = list(islice(mi.iterate(lambda x: 2 * x, start=1), 10))
  4774. expected = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
  4775. self.assertEqual(result, expected)
  4776. def test_func_controls_iteration_stop(self) -> None:
  4777. def func(num):
  4778. if num > 100:
  4779. raise StopIteration
  4780. return num * 2
  4781. result = list(islice(mi.iterate(func, start=1), 10))
  4782. expected = [1, 2, 4, 8, 16, 32, 64, 128]
  4783. self.assertEqual(result, expected)
  4784. class TakewhileInclusiveTests(TestCase):
  4785. def test_basic(self) -> None:
  4786. result = list(mi.takewhile_inclusive(lambda x: x < 5, [1, 4, 6, 4, 1]))
  4787. expected = [1, 4, 6]
  4788. self.assertEqual(result, expected)
  4789. def test_empty_iterator(self) -> None:
  4790. result = list(mi.takewhile_inclusive(lambda x: True, []))
  4791. expected = []
  4792. self.assertEqual(result, expected)
  4793. def test_collatz_sequence(self) -> None:
  4794. is_even = lambda n: n % 2 == 0
  4795. start = 11
  4796. result = list(
  4797. mi.takewhile_inclusive(
  4798. lambda n: n != 1,
  4799. mi.iterate(
  4800. lambda n: n // 2 if is_even(n) else 3 * n + 1, start
  4801. ),
  4802. )
  4803. )
  4804. expected = [11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1]
  4805. self.assertEqual(result, expected)
  4806. class OuterProductTests(TestCase):
  4807. def test_basic(self) -> None:
  4808. greetings = ['Hello', 'Goodbye']
  4809. names = ['Alice', 'Bob', 'Carol']
  4810. greet = lambda greeting, name: f'{greeting}, {name}!'
  4811. result = list(mi.outer_product(greet, greetings, names))
  4812. expected = [
  4813. ('Hello, Alice!', 'Hello, Bob!', 'Hello, Carol!'),
  4814. ('Goodbye, Alice!', 'Goodbye, Bob!', 'Goodbye, Carol!'),
  4815. ]
  4816. self.assertEqual(result, expected)
  4817. class IterSuppressTests(TestCase):
  4818. class Producer:
  4819. def __init__(self, exc, die_early=False):
  4820. self.exc = exc
  4821. self.pos = 0
  4822. self.die_early = die_early
  4823. def __iter__(self):
  4824. if self.die_early:
  4825. raise self.exc
  4826. return self
  4827. def __next__(self):
  4828. ret = self.pos
  4829. if self.pos >= 5:
  4830. raise self.exc
  4831. self.pos += 1
  4832. return ret
  4833. def test_no_error(self):
  4834. iterator = range(5)
  4835. actual = list(mi.iter_suppress(iterator, RuntimeError))
  4836. expected = [0, 1, 2, 3, 4]
  4837. self.assertEqual(actual, expected)
  4838. def test_raises_error(self):
  4839. iterator = self.Producer(ValueError)
  4840. with self.assertRaises(ValueError):
  4841. list(mi.iter_suppress(iterator, RuntimeError))
  4842. def test_suppression(self):
  4843. iterator = self.Producer(ValueError)
  4844. actual = list(mi.iter_suppress(iterator, RuntimeError, ValueError))
  4845. expected = [0, 1, 2, 3, 4]
  4846. self.assertEqual(actual, expected)
  4847. def test_early_suppression(self):
  4848. iterator = self.Producer(ValueError, die_early=True)
  4849. actual = list(mi.iter_suppress(iterator, RuntimeError, ValueError))
  4850. expected = []
  4851. self.assertEqual(actual, expected)
  4852. class FilterMapTests(TestCase):
  4853. def test_no_iterables(self):
  4854. actual = list(mi.filter_map(lambda _: None, []))
  4855. expected = []
  4856. self.assertEqual(actual, expected)
  4857. def test_filter(self):
  4858. actual = list(mi.filter_map(lambda _: None, [1, 2, 3]))
  4859. expected = []
  4860. self.assertEqual(actual, expected)
  4861. def test_map(self):
  4862. actual = list(mi.filter_map(lambda x: x + 1, [1, 2, 3]))
  4863. expected = [2, 3, 4]
  4864. self.assertEqual(actual, expected)
  4865. def test_filter_map(self):
  4866. actual = list(
  4867. mi.filter_map(
  4868. lambda x: int(x) if x.isnumeric() else None,
  4869. ['1', 'a', '2', 'b', '3'],
  4870. )
  4871. )
  4872. expected = [1, 2, 3]
  4873. self.assertEqual(actual, expected)