test_decimal.py 214 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897
  1. # Copyright (c) 2004 Python Software Foundation.
  2. # All rights reserved.
  3. # Written by Eric Price <eprice at tjhsst.edu>
  4. # and Facundo Batista <facundo at taniquetil.com.ar>
  5. # and Raymond Hettinger <python at rcn.com>
  6. # and Aahz (aahz at pobox.com)
  7. # and Tim Peters
  8. """
  9. These are the test cases for the Decimal module.
  10. There are two groups of tests, Arithmetic and Behaviour. The former test
  11. the Decimal arithmetic using the tests provided by Mike Cowlishaw. The latter
  12. test the pythonic behaviour according to PEP 327.
  13. Cowlishaw's tests can be downloaded from:
  14. http://speleotrove.com/decimal/dectest.zip
  15. This test module can be called from command line with one parameter (Arithmetic
  16. or Behaviour) to test each part, or without parameter to test both parts. If
  17. you're working through IDLE, you can import this test module and call test_main()
  18. with the corresponding argument.
  19. """
  20. import math
  21. import os, sys
  22. import operator
  23. import warnings
  24. import pickle, copy
  25. import unittest
  26. import numbers
  27. import locale
  28. from test.support import (run_unittest, run_doctest, is_resource_enabled,
  29. requires_IEEE_754, requires_docstrings,
  30. requires_legacy_unicode_capi, check_sanitizer)
  31. from test.support import (TestFailed,
  32. run_with_locale, cpython_only,
  33. darwin_malloc_err_warning, is_emscripten)
  34. from test.support.import_helper import import_fresh_module
  35. from test.support import threading_helper
  36. from test.support import warnings_helper
  37. import random
  38. import inspect
  39. import threading
  40. if sys.platform == 'darwin':
  41. darwin_malloc_err_warning('test_decimal')
  42. C = import_fresh_module('decimal', fresh=['_decimal'])
  43. P = import_fresh_module('decimal', blocked=['_decimal'])
  44. import decimal as orig_sys_decimal
  45. # fractions module must import the correct decimal module.
  46. cfractions = import_fresh_module('fractions', fresh=['fractions'])
  47. sys.modules['decimal'] = P
  48. pfractions = import_fresh_module('fractions', fresh=['fractions'])
  49. sys.modules['decimal'] = C
  50. fractions = {C:cfractions, P:pfractions}
  51. sys.modules['decimal'] = orig_sys_decimal
  52. # Useful Test Constant
  53. Signals = {
  54. C: tuple(C.getcontext().flags.keys()) if C else None,
  55. P: tuple(P.getcontext().flags.keys())
  56. }
  57. # Signals ordered with respect to precedence: when an operation
  58. # produces multiple signals, signals occurring later in the list
  59. # should be handled before those occurring earlier in the list.
  60. OrderedSignals = {
  61. C: [C.Clamped, C.Rounded, C.Inexact, C.Subnormal, C.Underflow,
  62. C.Overflow, C.DivisionByZero, C.InvalidOperation,
  63. C.FloatOperation] if C else None,
  64. P: [P.Clamped, P.Rounded, P.Inexact, P.Subnormal, P.Underflow,
  65. P.Overflow, P.DivisionByZero, P.InvalidOperation,
  66. P.FloatOperation]
  67. }
  68. def assert_signals(cls, context, attr, expected):
  69. d = getattr(context, attr)
  70. cls.assertTrue(all(d[s] if s in expected else not d[s] for s in d))
  71. ROUND_UP = P.ROUND_UP
  72. ROUND_DOWN = P.ROUND_DOWN
  73. ROUND_CEILING = P.ROUND_CEILING
  74. ROUND_FLOOR = P.ROUND_FLOOR
  75. ROUND_HALF_UP = P.ROUND_HALF_UP
  76. ROUND_HALF_DOWN = P.ROUND_HALF_DOWN
  77. ROUND_HALF_EVEN = P.ROUND_HALF_EVEN
  78. ROUND_05UP = P.ROUND_05UP
  79. RoundingModes = [
  80. ROUND_UP, ROUND_DOWN, ROUND_CEILING, ROUND_FLOOR,
  81. ROUND_HALF_UP, ROUND_HALF_DOWN, ROUND_HALF_EVEN,
  82. ROUND_05UP
  83. ]
  84. # Tests are built around these assumed context defaults.
  85. # test_main() restores the original context.
  86. ORIGINAL_CONTEXT = {
  87. C: C.getcontext().copy() if C else None,
  88. P: P.getcontext().copy()
  89. }
  90. def init(m):
  91. if not m: return
  92. DefaultTestContext = m.Context(
  93. prec=9, rounding=ROUND_HALF_EVEN, traps=dict.fromkeys(Signals[m], 0)
  94. )
  95. m.setcontext(DefaultTestContext)
  96. TESTDATADIR = 'decimaltestdata'
  97. if __name__ == '__main__':
  98. file = sys.argv[0]
  99. else:
  100. file = __file__
  101. testdir = os.path.dirname(file) or os.curdir
  102. directory = testdir + os.sep + TESTDATADIR + os.sep
  103. skip_expected = not os.path.isdir(directory)
  104. # Make sure it actually raises errors when not expected and caught in flags
  105. # Slower, since it runs some things several times.
  106. EXTENDEDERRORTEST = False
  107. # Test extra functionality in the C version (-DEXTRA_FUNCTIONALITY).
  108. EXTRA_FUNCTIONALITY = True if hasattr(C, 'DecClamped') else False
  109. requires_extra_functionality = unittest.skipUnless(
  110. EXTRA_FUNCTIONALITY, "test requires build with -DEXTRA_FUNCTIONALITY")
  111. skip_if_extra_functionality = unittest.skipIf(
  112. EXTRA_FUNCTIONALITY, "test requires regular build")
  113. class IBMTestCases(unittest.TestCase):
  114. """Class which tests the Decimal class against the IBM test cases."""
  115. def setUp(self):
  116. self.context = self.decimal.Context()
  117. self.readcontext = self.decimal.Context()
  118. self.ignore_list = ['#']
  119. # List of individual .decTest test ids that correspond to tests that
  120. # we're skipping for one reason or another.
  121. self.skipped_test_ids = set([
  122. # Skip implementation-specific scaleb tests.
  123. 'scbx164',
  124. 'scbx165',
  125. # For some operations (currently exp, ln, log10, power), the decNumber
  126. # reference implementation imposes additional restrictions on the context
  127. # and operands. These restrictions are not part of the specification;
  128. # however, the effect of these restrictions does show up in some of the
  129. # testcases. We skip testcases that violate these restrictions, since
  130. # Decimal behaves differently from decNumber for these testcases so these
  131. # testcases would otherwise fail.
  132. 'expx901',
  133. 'expx902',
  134. 'expx903',
  135. 'expx905',
  136. 'lnx901',
  137. 'lnx902',
  138. 'lnx903',
  139. 'lnx905',
  140. 'logx901',
  141. 'logx902',
  142. 'logx903',
  143. 'logx905',
  144. 'powx1183',
  145. 'powx1184',
  146. 'powx4001',
  147. 'powx4002',
  148. 'powx4003',
  149. 'powx4005',
  150. 'powx4008',
  151. 'powx4010',
  152. 'powx4012',
  153. 'powx4014',
  154. ])
  155. if self.decimal == C:
  156. # status has additional Subnormal, Underflow
  157. self.skipped_test_ids.add('pwsx803')
  158. self.skipped_test_ids.add('pwsx805')
  159. # Correct rounding (skipped for decNumber, too)
  160. self.skipped_test_ids.add('powx4302')
  161. self.skipped_test_ids.add('powx4303')
  162. self.skipped_test_ids.add('powx4342')
  163. self.skipped_test_ids.add('powx4343')
  164. # http://bugs.python.org/issue7049
  165. self.skipped_test_ids.add('pwmx325')
  166. self.skipped_test_ids.add('pwmx326')
  167. # Map test directives to setter functions.
  168. self.ChangeDict = {'precision' : self.change_precision,
  169. 'rounding' : self.change_rounding_method,
  170. 'maxexponent' : self.change_max_exponent,
  171. 'minexponent' : self.change_min_exponent,
  172. 'clamp' : self.change_clamp}
  173. # Name adapter to be able to change the Decimal and Context
  174. # interface without changing the test files from Cowlishaw.
  175. self.NameAdapter = {'and':'logical_and',
  176. 'apply':'_apply',
  177. 'class':'number_class',
  178. 'comparesig':'compare_signal',
  179. 'comparetotal':'compare_total',
  180. 'comparetotmag':'compare_total_mag',
  181. 'copy':'copy_decimal',
  182. 'copyabs':'copy_abs',
  183. 'copynegate':'copy_negate',
  184. 'copysign':'copy_sign',
  185. 'divideint':'divide_int',
  186. 'invert':'logical_invert',
  187. 'iscanonical':'is_canonical',
  188. 'isfinite':'is_finite',
  189. 'isinfinite':'is_infinite',
  190. 'isnan':'is_nan',
  191. 'isnormal':'is_normal',
  192. 'isqnan':'is_qnan',
  193. 'issigned':'is_signed',
  194. 'issnan':'is_snan',
  195. 'issubnormal':'is_subnormal',
  196. 'iszero':'is_zero',
  197. 'maxmag':'max_mag',
  198. 'minmag':'min_mag',
  199. 'nextminus':'next_minus',
  200. 'nextplus':'next_plus',
  201. 'nexttoward':'next_toward',
  202. 'or':'logical_or',
  203. 'reduce':'normalize',
  204. 'remaindernear':'remainder_near',
  205. 'samequantum':'same_quantum',
  206. 'squareroot':'sqrt',
  207. 'toeng':'to_eng_string',
  208. 'tointegral':'to_integral_value',
  209. 'tointegralx':'to_integral_exact',
  210. 'tosci':'to_sci_string',
  211. 'xor':'logical_xor'}
  212. # Map test-case names to roundings.
  213. self.RoundingDict = {'ceiling' : ROUND_CEILING,
  214. 'down' : ROUND_DOWN,
  215. 'floor' : ROUND_FLOOR,
  216. 'half_down' : ROUND_HALF_DOWN,
  217. 'half_even' : ROUND_HALF_EVEN,
  218. 'half_up' : ROUND_HALF_UP,
  219. 'up' : ROUND_UP,
  220. '05up' : ROUND_05UP}
  221. # Map the test cases' error names to the actual errors.
  222. self.ErrorNames = {'clamped' : self.decimal.Clamped,
  223. 'conversion_syntax' : self.decimal.InvalidOperation,
  224. 'division_by_zero' : self.decimal.DivisionByZero,
  225. 'division_impossible' : self.decimal.InvalidOperation,
  226. 'division_undefined' : self.decimal.InvalidOperation,
  227. 'inexact' : self.decimal.Inexact,
  228. 'invalid_context' : self.decimal.InvalidOperation,
  229. 'invalid_operation' : self.decimal.InvalidOperation,
  230. 'overflow' : self.decimal.Overflow,
  231. 'rounded' : self.decimal.Rounded,
  232. 'subnormal' : self.decimal.Subnormal,
  233. 'underflow' : self.decimal.Underflow}
  234. # The following functions return True/False rather than a
  235. # Decimal instance.
  236. self.LogicalFunctions = ('is_canonical',
  237. 'is_finite',
  238. 'is_infinite',
  239. 'is_nan',
  240. 'is_normal',
  241. 'is_qnan',
  242. 'is_signed',
  243. 'is_snan',
  244. 'is_subnormal',
  245. 'is_zero',
  246. 'same_quantum')
  247. def read_unlimited(self, v, context):
  248. """Work around the limitations of the 32-bit _decimal version. The
  249. guaranteed maximum values for prec, Emax etc. are 425000000,
  250. but higher values usually work, except for rare corner cases.
  251. In particular, all of the IBM tests pass with maximum values
  252. of 1070000000."""
  253. if self.decimal == C and self.decimal.MAX_EMAX == 425000000:
  254. self.readcontext._unsafe_setprec(1070000000)
  255. self.readcontext._unsafe_setemax(1070000000)
  256. self.readcontext._unsafe_setemin(-1070000000)
  257. return self.readcontext.create_decimal(v)
  258. else:
  259. return self.decimal.Decimal(v, context)
  260. def eval_file(self, file):
  261. global skip_expected
  262. if skip_expected:
  263. raise unittest.SkipTest
  264. with open(file, encoding="utf-8") as f:
  265. for line in f:
  266. line = line.replace('\r\n', '').replace('\n', '')
  267. #print line
  268. try:
  269. t = self.eval_line(line)
  270. except self.decimal.DecimalException as exception:
  271. #Exception raised where there shouldn't have been one.
  272. self.fail('Exception "'+exception.__class__.__name__ + '" raised on line '+line)
  273. def eval_line(self, s):
  274. if s.find(' -> ') >= 0 and s[:2] != '--' and not s.startswith(' --'):
  275. s = (s.split('->')[0] + '->' +
  276. s.split('->')[1].split('--')[0]).strip()
  277. else:
  278. s = s.split('--')[0].strip()
  279. for ignore in self.ignore_list:
  280. if s.find(ignore) >= 0:
  281. #print s.split()[0], 'NotImplemented--', ignore
  282. return
  283. if not s:
  284. return
  285. elif ':' in s:
  286. return self.eval_directive(s)
  287. else:
  288. return self.eval_equation(s)
  289. def eval_directive(self, s):
  290. funct, value = (x.strip().lower() for x in s.split(':'))
  291. if funct == 'rounding':
  292. value = self.RoundingDict[value]
  293. else:
  294. try:
  295. value = int(value)
  296. except ValueError:
  297. pass
  298. funct = self.ChangeDict.get(funct, (lambda *args: None))
  299. funct(value)
  300. def eval_equation(self, s):
  301. if not TEST_ALL and random.random() < 0.90:
  302. return
  303. self.context.clear_flags()
  304. try:
  305. Sides = s.split('->')
  306. L = Sides[0].strip().split()
  307. id = L[0]
  308. if DEBUG:
  309. print("Test ", id, end=" ")
  310. funct = L[1].lower()
  311. valstemp = L[2:]
  312. L = Sides[1].strip().split()
  313. ans = L[0]
  314. exceptions = L[1:]
  315. except (TypeError, AttributeError, IndexError):
  316. raise self.decimal.InvalidOperation
  317. def FixQuotes(val):
  318. val = val.replace("''", 'SingleQuote').replace('""', 'DoubleQuote')
  319. val = val.replace("'", '').replace('"', '')
  320. val = val.replace('SingleQuote', "'").replace('DoubleQuote', '"')
  321. return val
  322. if id in self.skipped_test_ids:
  323. return
  324. fname = self.NameAdapter.get(funct, funct)
  325. if fname == 'rescale':
  326. return
  327. funct = getattr(self.context, fname)
  328. vals = []
  329. conglomerate = ''
  330. quote = 0
  331. theirexceptions = [self.ErrorNames[x.lower()] for x in exceptions]
  332. for exception in Signals[self.decimal]:
  333. self.context.traps[exception] = 1 #Catch these bugs...
  334. for exception in theirexceptions:
  335. self.context.traps[exception] = 0
  336. for i, val in enumerate(valstemp):
  337. if val.count("'") % 2 == 1:
  338. quote = 1 - quote
  339. if quote:
  340. conglomerate = conglomerate + ' ' + val
  341. continue
  342. else:
  343. val = conglomerate + val
  344. conglomerate = ''
  345. v = FixQuotes(val)
  346. if fname in ('to_sci_string', 'to_eng_string'):
  347. if EXTENDEDERRORTEST:
  348. for error in theirexceptions:
  349. self.context.traps[error] = 1
  350. try:
  351. funct(self.context.create_decimal(v))
  352. except error:
  353. pass
  354. except Signals[self.decimal] as e:
  355. self.fail("Raised %s in %s when %s disabled" % \
  356. (e, s, error))
  357. else:
  358. self.fail("Did not raise %s in %s" % (error, s))
  359. self.context.traps[error] = 0
  360. v = self.context.create_decimal(v)
  361. else:
  362. v = self.read_unlimited(v, self.context)
  363. vals.append(v)
  364. ans = FixQuotes(ans)
  365. if EXTENDEDERRORTEST and fname not in ('to_sci_string', 'to_eng_string'):
  366. for error in theirexceptions:
  367. self.context.traps[error] = 1
  368. try:
  369. funct(*vals)
  370. except error:
  371. pass
  372. except Signals[self.decimal] as e:
  373. self.fail("Raised %s in %s when %s disabled" % \
  374. (e, s, error))
  375. else:
  376. self.fail("Did not raise %s in %s" % (error, s))
  377. self.context.traps[error] = 0
  378. # as above, but add traps cumulatively, to check precedence
  379. ordered_errors = [e for e in OrderedSignals[self.decimal] if e in theirexceptions]
  380. for error in ordered_errors:
  381. self.context.traps[error] = 1
  382. try:
  383. funct(*vals)
  384. except error:
  385. pass
  386. except Signals[self.decimal] as e:
  387. self.fail("Raised %s in %s; expected %s" %
  388. (type(e), s, error))
  389. else:
  390. self.fail("Did not raise %s in %s" % (error, s))
  391. # reset traps
  392. for error in ordered_errors:
  393. self.context.traps[error] = 0
  394. if DEBUG:
  395. print("--", self.context)
  396. try:
  397. result = str(funct(*vals))
  398. if fname in self.LogicalFunctions:
  399. result = str(int(eval(result))) # 'True', 'False' -> '1', '0'
  400. except Signals[self.decimal] as error:
  401. self.fail("Raised %s in %s" % (error, s))
  402. except: #Catch any error long enough to state the test case.
  403. print("ERROR:", s)
  404. raise
  405. myexceptions = self.getexceptions()
  406. myexceptions.sort(key=repr)
  407. theirexceptions.sort(key=repr)
  408. self.assertEqual(result, ans,
  409. 'Incorrect answer for ' + s + ' -- got ' + result)
  410. self.assertEqual(myexceptions, theirexceptions,
  411. 'Incorrect flags set in ' + s + ' -- got ' + str(myexceptions))
  412. def getexceptions(self):
  413. return [e for e in Signals[self.decimal] if self.context.flags[e]]
  414. def change_precision(self, prec):
  415. if self.decimal == C and self.decimal.MAX_PREC == 425000000:
  416. self.context._unsafe_setprec(prec)
  417. else:
  418. self.context.prec = prec
  419. def change_rounding_method(self, rounding):
  420. self.context.rounding = rounding
  421. def change_min_exponent(self, exp):
  422. if self.decimal == C and self.decimal.MAX_PREC == 425000000:
  423. self.context._unsafe_setemin(exp)
  424. else:
  425. self.context.Emin = exp
  426. def change_max_exponent(self, exp):
  427. if self.decimal == C and self.decimal.MAX_PREC == 425000000:
  428. self.context._unsafe_setemax(exp)
  429. else:
  430. self.context.Emax = exp
  431. def change_clamp(self, clamp):
  432. self.context.clamp = clamp
  433. class CIBMTestCases(IBMTestCases):
  434. decimal = C
  435. class PyIBMTestCases(IBMTestCases):
  436. decimal = P
  437. # The following classes test the behaviour of Decimal according to PEP 327
  438. class ExplicitConstructionTest(unittest.TestCase):
  439. '''Unit tests for Explicit Construction cases of Decimal.'''
  440. def test_explicit_empty(self):
  441. Decimal = self.decimal.Decimal
  442. self.assertEqual(Decimal(), Decimal("0"))
  443. def test_explicit_from_None(self):
  444. Decimal = self.decimal.Decimal
  445. self.assertRaises(TypeError, Decimal, None)
  446. def test_explicit_from_int(self):
  447. Decimal = self.decimal.Decimal
  448. #positive
  449. d = Decimal(45)
  450. self.assertEqual(str(d), '45')
  451. #very large positive
  452. d = Decimal(500000123)
  453. self.assertEqual(str(d), '500000123')
  454. #negative
  455. d = Decimal(-45)
  456. self.assertEqual(str(d), '-45')
  457. #zero
  458. d = Decimal(0)
  459. self.assertEqual(str(d), '0')
  460. # single word longs
  461. for n in range(0, 32):
  462. for sign in (-1, 1):
  463. for x in range(-5, 5):
  464. i = sign * (2**n + x)
  465. d = Decimal(i)
  466. self.assertEqual(str(d), str(i))
  467. def test_explicit_from_string(self):
  468. Decimal = self.decimal.Decimal
  469. InvalidOperation = self.decimal.InvalidOperation
  470. localcontext = self.decimal.localcontext
  471. #empty
  472. self.assertEqual(str(Decimal('')), 'NaN')
  473. #int
  474. self.assertEqual(str(Decimal('45')), '45')
  475. #float
  476. self.assertEqual(str(Decimal('45.34')), '45.34')
  477. #engineer notation
  478. self.assertEqual(str(Decimal('45e2')), '4.5E+3')
  479. #just not a number
  480. self.assertEqual(str(Decimal('ugly')), 'NaN')
  481. #leading and trailing whitespace permitted
  482. self.assertEqual(str(Decimal('1.3E4 \n')), '1.3E+4')
  483. self.assertEqual(str(Decimal(' -7.89')), '-7.89')
  484. self.assertEqual(str(Decimal(" 3.45679 ")), '3.45679')
  485. # underscores
  486. self.assertEqual(str(Decimal('1_3.3e4_0')), '1.33E+41')
  487. self.assertEqual(str(Decimal('1_0_0_0')), '1000')
  488. # unicode whitespace
  489. for lead in ["", ' ', '\u00a0', '\u205f']:
  490. for trail in ["", ' ', '\u00a0', '\u205f']:
  491. self.assertEqual(str(Decimal(lead + '9.311E+28' + trail)),
  492. '9.311E+28')
  493. with localcontext() as c:
  494. c.traps[InvalidOperation] = True
  495. # Invalid string
  496. self.assertRaises(InvalidOperation, Decimal, "xyz")
  497. # Two arguments max
  498. self.assertRaises(TypeError, Decimal, "1234", "x", "y")
  499. # space within the numeric part
  500. self.assertRaises(InvalidOperation, Decimal, "1\u00a02\u00a03")
  501. self.assertRaises(InvalidOperation, Decimal, "\u00a01\u00a02\u00a0")
  502. # unicode whitespace
  503. self.assertRaises(InvalidOperation, Decimal, "\u00a0")
  504. self.assertRaises(InvalidOperation, Decimal, "\u00a0\u00a0")
  505. # embedded NUL
  506. self.assertRaises(InvalidOperation, Decimal, "12\u00003")
  507. # underscores don't prevent errors
  508. self.assertRaises(InvalidOperation, Decimal, "1_2_\u00003")
  509. @cpython_only
  510. @requires_legacy_unicode_capi
  511. @warnings_helper.ignore_warnings(category=DeprecationWarning)
  512. def test_from_legacy_strings(self):
  513. import _testcapi
  514. Decimal = self.decimal.Decimal
  515. context = self.decimal.Context()
  516. s = _testcapi.unicode_legacy_string('9.999999')
  517. self.assertEqual(str(Decimal(s)), '9.999999')
  518. self.assertEqual(str(context.create_decimal(s)), '9.999999')
  519. def test_explicit_from_tuples(self):
  520. Decimal = self.decimal.Decimal
  521. #zero
  522. d = Decimal( (0, (0,), 0) )
  523. self.assertEqual(str(d), '0')
  524. #int
  525. d = Decimal( (1, (4, 5), 0) )
  526. self.assertEqual(str(d), '-45')
  527. #float
  528. d = Decimal( (0, (4, 5, 3, 4), -2) )
  529. self.assertEqual(str(d), '45.34')
  530. #weird
  531. d = Decimal( (1, (4, 3, 4, 9, 1, 3, 5, 3, 4), -25) )
  532. self.assertEqual(str(d), '-4.34913534E-17')
  533. #inf
  534. d = Decimal( (0, (), "F") )
  535. self.assertEqual(str(d), 'Infinity')
  536. #wrong number of items
  537. self.assertRaises(ValueError, Decimal, (1, (4, 3, 4, 9, 1)) )
  538. #bad sign
  539. self.assertRaises(ValueError, Decimal, (8, (4, 3, 4, 9, 1), 2) )
  540. self.assertRaises(ValueError, Decimal, (0., (4, 3, 4, 9, 1), 2) )
  541. self.assertRaises(ValueError, Decimal, (Decimal(1), (4, 3, 4, 9, 1), 2))
  542. #bad exp
  543. self.assertRaises(ValueError, Decimal, (1, (4, 3, 4, 9, 1), 'wrong!') )
  544. self.assertRaises(ValueError, Decimal, (1, (4, 3, 4, 9, 1), 0.) )
  545. self.assertRaises(ValueError, Decimal, (1, (4, 3, 4, 9, 1), '1') )
  546. #bad coefficients
  547. self.assertRaises(ValueError, Decimal, (1, "xyz", 2) )
  548. self.assertRaises(ValueError, Decimal, (1, (4, 3, 4, None, 1), 2) )
  549. self.assertRaises(ValueError, Decimal, (1, (4, -3, 4, 9, 1), 2) )
  550. self.assertRaises(ValueError, Decimal, (1, (4, 10, 4, 9, 1), 2) )
  551. self.assertRaises(ValueError, Decimal, (1, (4, 3, 4, 'a', 1), 2) )
  552. def test_explicit_from_list(self):
  553. Decimal = self.decimal.Decimal
  554. d = Decimal([0, [0], 0])
  555. self.assertEqual(str(d), '0')
  556. d = Decimal([1, [4, 3, 4, 9, 1, 3, 5, 3, 4], -25])
  557. self.assertEqual(str(d), '-4.34913534E-17')
  558. d = Decimal([1, (4, 3, 4, 9, 1, 3, 5, 3, 4), -25])
  559. self.assertEqual(str(d), '-4.34913534E-17')
  560. d = Decimal((1, [4, 3, 4, 9, 1, 3, 5, 3, 4], -25))
  561. self.assertEqual(str(d), '-4.34913534E-17')
  562. def test_explicit_from_bool(self):
  563. Decimal = self.decimal.Decimal
  564. self.assertIs(bool(Decimal(0)), False)
  565. self.assertIs(bool(Decimal(1)), True)
  566. self.assertEqual(Decimal(False), Decimal(0))
  567. self.assertEqual(Decimal(True), Decimal(1))
  568. def test_explicit_from_Decimal(self):
  569. Decimal = self.decimal.Decimal
  570. #positive
  571. d = Decimal(45)
  572. e = Decimal(d)
  573. self.assertEqual(str(e), '45')
  574. #very large positive
  575. d = Decimal(500000123)
  576. e = Decimal(d)
  577. self.assertEqual(str(e), '500000123')
  578. #negative
  579. d = Decimal(-45)
  580. e = Decimal(d)
  581. self.assertEqual(str(e), '-45')
  582. #zero
  583. d = Decimal(0)
  584. e = Decimal(d)
  585. self.assertEqual(str(e), '0')
  586. @requires_IEEE_754
  587. def test_explicit_from_float(self):
  588. Decimal = self.decimal.Decimal
  589. r = Decimal(0.1)
  590. self.assertEqual(type(r), Decimal)
  591. self.assertEqual(str(r),
  592. '0.1000000000000000055511151231257827021181583404541015625')
  593. self.assertTrue(Decimal(float('nan')).is_qnan())
  594. self.assertTrue(Decimal(float('inf')).is_infinite())
  595. self.assertTrue(Decimal(float('-inf')).is_infinite())
  596. self.assertEqual(str(Decimal(float('nan'))),
  597. str(Decimal('NaN')))
  598. self.assertEqual(str(Decimal(float('inf'))),
  599. str(Decimal('Infinity')))
  600. self.assertEqual(str(Decimal(float('-inf'))),
  601. str(Decimal('-Infinity')))
  602. self.assertEqual(str(Decimal(float('-0.0'))),
  603. str(Decimal('-0')))
  604. for i in range(200):
  605. x = random.expovariate(0.01) * (random.random() * 2.0 - 1.0)
  606. self.assertEqual(x, float(Decimal(x))) # roundtrip
  607. def test_explicit_context_create_decimal(self):
  608. Decimal = self.decimal.Decimal
  609. InvalidOperation = self.decimal.InvalidOperation
  610. Rounded = self.decimal.Rounded
  611. nc = copy.copy(self.decimal.getcontext())
  612. nc.prec = 3
  613. # empty
  614. d = Decimal()
  615. self.assertEqual(str(d), '0')
  616. d = nc.create_decimal()
  617. self.assertEqual(str(d), '0')
  618. # from None
  619. self.assertRaises(TypeError, nc.create_decimal, None)
  620. # from int
  621. d = nc.create_decimal(456)
  622. self.assertIsInstance(d, Decimal)
  623. self.assertEqual(nc.create_decimal(45678),
  624. nc.create_decimal('457E+2'))
  625. # from string
  626. d = Decimal('456789')
  627. self.assertEqual(str(d), '456789')
  628. d = nc.create_decimal('456789')
  629. self.assertEqual(str(d), '4.57E+5')
  630. # leading and trailing whitespace should result in a NaN;
  631. # spaces are already checked in Cowlishaw's test-suite, so
  632. # here we just check that a trailing newline results in a NaN
  633. self.assertEqual(str(nc.create_decimal('3.14\n')), 'NaN')
  634. # from tuples
  635. d = Decimal( (1, (4, 3, 4, 9, 1, 3, 5, 3, 4), -25) )
  636. self.assertEqual(str(d), '-4.34913534E-17')
  637. d = nc.create_decimal( (1, (4, 3, 4, 9, 1, 3, 5, 3, 4), -25) )
  638. self.assertEqual(str(d), '-4.35E-17')
  639. # from Decimal
  640. prevdec = Decimal(500000123)
  641. d = Decimal(prevdec)
  642. self.assertEqual(str(d), '500000123')
  643. d = nc.create_decimal(prevdec)
  644. self.assertEqual(str(d), '5.00E+8')
  645. # more integers
  646. nc.prec = 28
  647. nc.traps[InvalidOperation] = True
  648. for v in [-2**63-1, -2**63, -2**31-1, -2**31, 0,
  649. 2**31-1, 2**31, 2**63-1, 2**63]:
  650. d = nc.create_decimal(v)
  651. self.assertTrue(isinstance(d, Decimal))
  652. self.assertEqual(int(d), v)
  653. nc.prec = 3
  654. nc.traps[Rounded] = True
  655. self.assertRaises(Rounded, nc.create_decimal, 1234)
  656. # from string
  657. nc.prec = 28
  658. self.assertEqual(str(nc.create_decimal('0E-017')), '0E-17')
  659. self.assertEqual(str(nc.create_decimal('45')), '45')
  660. self.assertEqual(str(nc.create_decimal('-Inf')), '-Infinity')
  661. self.assertEqual(str(nc.create_decimal('NaN123')), 'NaN123')
  662. # invalid arguments
  663. self.assertRaises(InvalidOperation, nc.create_decimal, "xyz")
  664. self.assertRaises(ValueError, nc.create_decimal, (1, "xyz", -25))
  665. self.assertRaises(TypeError, nc.create_decimal, "1234", "5678")
  666. # no whitespace and underscore stripping is done with this method
  667. self.assertRaises(InvalidOperation, nc.create_decimal, " 1234")
  668. self.assertRaises(InvalidOperation, nc.create_decimal, "12_34")
  669. # too many NaN payload digits
  670. nc.prec = 3
  671. self.assertRaises(InvalidOperation, nc.create_decimal, 'NaN12345')
  672. self.assertRaises(InvalidOperation, nc.create_decimal,
  673. Decimal('NaN12345'))
  674. nc.traps[InvalidOperation] = False
  675. self.assertEqual(str(nc.create_decimal('NaN12345')), 'NaN')
  676. self.assertTrue(nc.flags[InvalidOperation])
  677. nc.flags[InvalidOperation] = False
  678. self.assertEqual(str(nc.create_decimal(Decimal('NaN12345'))), 'NaN')
  679. self.assertTrue(nc.flags[InvalidOperation])
  680. def test_explicit_context_create_from_float(self):
  681. Decimal = self.decimal.Decimal
  682. nc = self.decimal.Context()
  683. r = nc.create_decimal(0.1)
  684. self.assertEqual(type(r), Decimal)
  685. self.assertEqual(str(r), '0.1000000000000000055511151231')
  686. self.assertTrue(nc.create_decimal(float('nan')).is_qnan())
  687. self.assertTrue(nc.create_decimal(float('inf')).is_infinite())
  688. self.assertTrue(nc.create_decimal(float('-inf')).is_infinite())
  689. self.assertEqual(str(nc.create_decimal(float('nan'))),
  690. str(nc.create_decimal('NaN')))
  691. self.assertEqual(str(nc.create_decimal(float('inf'))),
  692. str(nc.create_decimal('Infinity')))
  693. self.assertEqual(str(nc.create_decimal(float('-inf'))),
  694. str(nc.create_decimal('-Infinity')))
  695. self.assertEqual(str(nc.create_decimal(float('-0.0'))),
  696. str(nc.create_decimal('-0')))
  697. nc.prec = 100
  698. for i in range(200):
  699. x = random.expovariate(0.01) * (random.random() * 2.0 - 1.0)
  700. self.assertEqual(x, float(nc.create_decimal(x))) # roundtrip
  701. def test_unicode_digits(self):
  702. Decimal = self.decimal.Decimal
  703. test_values = {
  704. '\uff11': '1',
  705. '\u0660.\u0660\u0663\u0667\u0662e-\u0663' : '0.0000372',
  706. '-nan\u0c68\u0c6a\u0c66\u0c66' : '-NaN2400',
  707. }
  708. for input, expected in test_values.items():
  709. self.assertEqual(str(Decimal(input)), expected)
  710. class CExplicitConstructionTest(ExplicitConstructionTest):
  711. decimal = C
  712. class PyExplicitConstructionTest(ExplicitConstructionTest):
  713. decimal = P
  714. class ImplicitConstructionTest(unittest.TestCase):
  715. '''Unit tests for Implicit Construction cases of Decimal.'''
  716. def test_implicit_from_None(self):
  717. Decimal = self.decimal.Decimal
  718. self.assertRaises(TypeError, eval, 'Decimal(5) + None', locals())
  719. def test_implicit_from_int(self):
  720. Decimal = self.decimal.Decimal
  721. #normal
  722. self.assertEqual(str(Decimal(5) + 45), '50')
  723. #exceeding precision
  724. self.assertEqual(Decimal(5) + 123456789000, Decimal(123456789000))
  725. def test_implicit_from_string(self):
  726. Decimal = self.decimal.Decimal
  727. self.assertRaises(TypeError, eval, 'Decimal(5) + "3"', locals())
  728. def test_implicit_from_float(self):
  729. Decimal = self.decimal.Decimal
  730. self.assertRaises(TypeError, eval, 'Decimal(5) + 2.2', locals())
  731. def test_implicit_from_Decimal(self):
  732. Decimal = self.decimal.Decimal
  733. self.assertEqual(Decimal(5) + Decimal(45), Decimal(50))
  734. def test_rop(self):
  735. Decimal = self.decimal.Decimal
  736. # Allow other classes to be trained to interact with Decimals
  737. class E:
  738. def __divmod__(self, other):
  739. return 'divmod ' + str(other)
  740. def __rdivmod__(self, other):
  741. return str(other) + ' rdivmod'
  742. def __lt__(self, other):
  743. return 'lt ' + str(other)
  744. def __gt__(self, other):
  745. return 'gt ' + str(other)
  746. def __le__(self, other):
  747. return 'le ' + str(other)
  748. def __ge__(self, other):
  749. return 'ge ' + str(other)
  750. def __eq__(self, other):
  751. return 'eq ' + str(other)
  752. def __ne__(self, other):
  753. return 'ne ' + str(other)
  754. self.assertEqual(divmod(E(), Decimal(10)), 'divmod 10')
  755. self.assertEqual(divmod(Decimal(10), E()), '10 rdivmod')
  756. self.assertEqual(eval('Decimal(10) < E()'), 'gt 10')
  757. self.assertEqual(eval('Decimal(10) > E()'), 'lt 10')
  758. self.assertEqual(eval('Decimal(10) <= E()'), 'ge 10')
  759. self.assertEqual(eval('Decimal(10) >= E()'), 'le 10')
  760. self.assertEqual(eval('Decimal(10) == E()'), 'eq 10')
  761. self.assertEqual(eval('Decimal(10) != E()'), 'ne 10')
  762. # insert operator methods and then exercise them
  763. oplist = [
  764. ('+', '__add__', '__radd__'),
  765. ('-', '__sub__', '__rsub__'),
  766. ('*', '__mul__', '__rmul__'),
  767. ('/', '__truediv__', '__rtruediv__'),
  768. ('%', '__mod__', '__rmod__'),
  769. ('//', '__floordiv__', '__rfloordiv__'),
  770. ('**', '__pow__', '__rpow__')
  771. ]
  772. for sym, lop, rop in oplist:
  773. setattr(E, lop, lambda self, other: 'str' + lop + str(other))
  774. setattr(E, rop, lambda self, other: str(other) + rop + 'str')
  775. self.assertEqual(eval('E()' + sym + 'Decimal(10)'),
  776. 'str' + lop + '10')
  777. self.assertEqual(eval('Decimal(10)' + sym + 'E()'),
  778. '10' + rop + 'str')
  779. class CImplicitConstructionTest(ImplicitConstructionTest):
  780. decimal = C
  781. class PyImplicitConstructionTest(ImplicitConstructionTest):
  782. decimal = P
  783. class FormatTest(unittest.TestCase):
  784. '''Unit tests for the format function.'''
  785. def test_formatting(self):
  786. Decimal = self.decimal.Decimal
  787. # triples giving a format, a Decimal, and the expected result
  788. test_values = [
  789. ('e', '0E-15', '0e-15'),
  790. ('e', '2.3E-15', '2.3e-15'),
  791. ('e', '2.30E+2', '2.30e+2'), # preserve significant zeros
  792. ('e', '2.30000E-15', '2.30000e-15'),
  793. ('e', '1.23456789123456789e40', '1.23456789123456789e+40'),
  794. ('e', '1.5', '1.5e+0'),
  795. ('e', '0.15', '1.5e-1'),
  796. ('e', '0.015', '1.5e-2'),
  797. ('e', '0.0000000000015', '1.5e-12'),
  798. ('e', '15.0', '1.50e+1'),
  799. ('e', '-15', '-1.5e+1'),
  800. ('e', '0', '0e+0'),
  801. ('e', '0E1', '0e+1'),
  802. ('e', '0.0', '0e-1'),
  803. ('e', '0.00', '0e-2'),
  804. ('.6e', '0E-15', '0.000000e-9'),
  805. ('.6e', '0', '0.000000e+6'),
  806. ('.6e', '9.999999', '9.999999e+0'),
  807. ('.6e', '9.9999999', '1.000000e+1'),
  808. ('.6e', '-1.23e5', '-1.230000e+5'),
  809. ('.6e', '1.23456789e-3', '1.234568e-3'),
  810. ('f', '0', '0'),
  811. ('f', '0.0', '0.0'),
  812. ('f', '0E-2', '0.00'),
  813. ('f', '0.00E-8', '0.0000000000'),
  814. ('f', '0E1', '0'), # loses exponent information
  815. ('f', '3.2E1', '32'),
  816. ('f', '3.2E2', '320'),
  817. ('f', '3.20E2', '320'),
  818. ('f', '3.200E2', '320.0'),
  819. ('f', '3.2E-6', '0.0000032'),
  820. ('.6f', '0E-15', '0.000000'), # all zeros treated equally
  821. ('.6f', '0E1', '0.000000'),
  822. ('.6f', '0', '0.000000'),
  823. ('.0f', '0', '0'), # no decimal point
  824. ('.0f', '0e-2', '0'),
  825. ('.0f', '3.14159265', '3'),
  826. ('.1f', '3.14159265', '3.1'),
  827. ('.4f', '3.14159265', '3.1416'),
  828. ('.6f', '3.14159265', '3.141593'),
  829. ('.7f', '3.14159265', '3.1415926'), # round-half-even!
  830. ('.8f', '3.14159265', '3.14159265'),
  831. ('.9f', '3.14159265', '3.141592650'),
  832. ('g', '0', '0'),
  833. ('g', '0.0', '0.0'),
  834. ('g', '0E1', '0e+1'),
  835. ('G', '0E1', '0E+1'),
  836. ('g', '0E-5', '0.00000'),
  837. ('g', '0E-6', '0.000000'),
  838. ('g', '0E-7', '0e-7'),
  839. ('g', '-0E2', '-0e+2'),
  840. ('.0g', '3.14159265', '3'), # 0 sig fig -> 1 sig fig
  841. ('.0n', '3.14159265', '3'), # same for 'n'
  842. ('.1g', '3.14159265', '3'),
  843. ('.2g', '3.14159265', '3.1'),
  844. ('.5g', '3.14159265', '3.1416'),
  845. ('.7g', '3.14159265', '3.141593'),
  846. ('.8g', '3.14159265', '3.1415926'), # round-half-even!
  847. ('.9g', '3.14159265', '3.14159265'),
  848. ('.10g', '3.14159265', '3.14159265'), # don't pad
  849. ('%', '0E1', '0%'),
  850. ('%', '0E0', '0%'),
  851. ('%', '0E-1', '0%'),
  852. ('%', '0E-2', '0%'),
  853. ('%', '0E-3', '0.0%'),
  854. ('%', '0E-4', '0.00%'),
  855. ('.3%', '0', '0.000%'), # all zeros treated equally
  856. ('.3%', '0E10', '0.000%'),
  857. ('.3%', '0E-10', '0.000%'),
  858. ('.3%', '2.34', '234.000%'),
  859. ('.3%', '1.234567', '123.457%'),
  860. ('.0%', '1.23', '123%'),
  861. ('e', 'NaN', 'NaN'),
  862. ('f', '-NaN123', '-NaN123'),
  863. ('+g', 'NaN456', '+NaN456'),
  864. ('.3e', 'Inf', 'Infinity'),
  865. ('.16f', '-Inf', '-Infinity'),
  866. ('.0g', '-sNaN', '-sNaN'),
  867. ('', '1.00', '1.00'),
  868. # test alignment and padding
  869. ('6', '123', ' 123'),
  870. ('<6', '123', '123 '),
  871. ('>6', '123', ' 123'),
  872. ('^6', '123', ' 123 '),
  873. ('=+6', '123', '+ 123'),
  874. ('#<10', 'NaN', 'NaN#######'),
  875. ('#<10', '-4.3', '-4.3######'),
  876. ('#<+10', '0.0130', '+0.0130###'),
  877. ('#< 10', '0.0130', ' 0.0130###'),
  878. ('@>10', '-Inf', '@-Infinity'),
  879. ('#>5', '-Inf', '-Infinity'),
  880. ('?^5', '123', '?123?'),
  881. ('%^6', '123', '%123%%'),
  882. (' ^6', '-45.6', '-45.6 '),
  883. ('/=10', '-45.6', '-/////45.6'),
  884. ('/=+10', '45.6', '+/////45.6'),
  885. ('/= 10', '45.6', ' /////45.6'),
  886. ('\x00=10', '-inf', '-\x00Infinity'),
  887. ('\x00^16', '-inf', '\x00\x00\x00-Infinity\x00\x00\x00\x00'),
  888. ('\x00>10', '1.2345', '\x00\x00\x00\x001.2345'),
  889. ('\x00<10', '1.2345', '1.2345\x00\x00\x00\x00'),
  890. # thousands separator
  891. (',', '1234567', '1,234,567'),
  892. (',', '123456', '123,456'),
  893. (',', '12345', '12,345'),
  894. (',', '1234', '1,234'),
  895. (',', '123', '123'),
  896. (',', '12', '12'),
  897. (',', '1', '1'),
  898. (',', '0', '0'),
  899. (',', '-1234567', '-1,234,567'),
  900. (',', '-123456', '-123,456'),
  901. ('7,', '123456', '123,456'),
  902. ('8,', '123456', ' 123,456'),
  903. ('08,', '123456', '0,123,456'), # special case: extra 0 needed
  904. ('+08,', '123456', '+123,456'), # but not if there's a sign
  905. (' 08,', '123456', ' 123,456'),
  906. ('08,', '-123456', '-123,456'),
  907. ('+09,', '123456', '+0,123,456'),
  908. # ... with fractional part...
  909. ('07,', '1234.56', '1,234.56'),
  910. ('08,', '1234.56', '1,234.56'),
  911. ('09,', '1234.56', '01,234.56'),
  912. ('010,', '1234.56', '001,234.56'),
  913. ('011,', '1234.56', '0,001,234.56'),
  914. ('012,', '1234.56', '0,001,234.56'),
  915. ('08,.1f', '1234.5', '01,234.5'),
  916. # no thousands separators in fraction part
  917. (',', '1.23456789', '1.23456789'),
  918. (',%', '123.456789', '12,345.6789%'),
  919. (',e', '123456', '1.23456e+5'),
  920. (',E', '123456', '1.23456E+5'),
  921. # negative zero: default behavior
  922. ('.1f', '-0', '-0.0'),
  923. ('.1f', '-.0', '-0.0'),
  924. ('.1f', '-.01', '-0.0'),
  925. # negative zero: z option
  926. ('z.1f', '0.', '0.0'),
  927. ('z6.1f', '0.', ' 0.0'),
  928. ('z6.1f', '-1.', ' -1.0'),
  929. ('z.1f', '-0.', '0.0'),
  930. ('z.1f', '.01', '0.0'),
  931. ('z.1f', '-.01', '0.0'),
  932. ('z.2f', '0.', '0.00'),
  933. ('z.2f', '-0.', '0.00'),
  934. ('z.2f', '.001', '0.00'),
  935. ('z.2f', '-.001', '0.00'),
  936. ('z.1e', '0.', '0.0e+1'),
  937. ('z.1e', '-0.', '0.0e+1'),
  938. ('z.1E', '0.', '0.0E+1'),
  939. ('z.1E', '-0.', '0.0E+1'),
  940. ('z.2e', '-0.001', '-1.00e-3'), # tests for mishandled rounding
  941. ('z.2g', '-0.001', '-0.001'),
  942. ('z.2%', '-0.001', '-0.10%'),
  943. ('zf', '-0.0000', '0.0000'), # non-normalized form is preserved
  944. ('z.1f', '-00000.000001', '0.0'),
  945. ('z.1f', '-00000.', '0.0'),
  946. ('z.1f', '-.0000000000', '0.0'),
  947. ('z.2f', '-00000.000001', '0.00'),
  948. ('z.2f', '-00000.', '0.00'),
  949. ('z.2f', '-.0000000000', '0.00'),
  950. ('z.1f', '.09', '0.1'),
  951. ('z.1f', '-.09', '-0.1'),
  952. (' z.0f', '-0.', ' 0'),
  953. ('+z.0f', '-0.', '+0'),
  954. ('-z.0f', '-0.', '0'),
  955. (' z.0f', '-1.', '-1'),
  956. ('+z.0f', '-1.', '-1'),
  957. ('-z.0f', '-1.', '-1'),
  958. ('z>6.1f', '-0.', 'zz-0.0'),
  959. ('z>z6.1f', '-0.', 'zzz0.0'),
  960. ('x>z6.1f', '-0.', 'xxx0.0'),
  961. ('🖤>z6.1f', '-0.', '🖤🖤🖤0.0'), # multi-byte fill char
  962. # issue 6850
  963. ('a=-7.0', '0.12345', 'aaaa0.1'),
  964. # issue 22090
  965. ('<^+15.20%', 'inf', '<<+Infinity%<<<'),
  966. ('\x07>,%', 'sNaN1234567', 'sNaN1234567%'),
  967. ('=10.10%', 'NaN123', ' NaN123%'),
  968. ]
  969. for fmt, d, result in test_values:
  970. self.assertEqual(format(Decimal(d), fmt), result)
  971. # bytes format argument
  972. self.assertRaises(TypeError, Decimal(1).__format__, b'-020')
  973. def test_negative_zero_format_directed_rounding(self):
  974. with self.decimal.localcontext() as ctx:
  975. ctx.rounding = ROUND_CEILING
  976. self.assertEqual(format(self.decimal.Decimal('-0.001'), 'z.2f'),
  977. '0.00')
  978. def test_negative_zero_bad_format(self):
  979. self.assertRaises(ValueError, format, self.decimal.Decimal('1.23'), 'fz')
  980. def test_n_format(self):
  981. Decimal = self.decimal.Decimal
  982. try:
  983. from locale import CHAR_MAX
  984. except ImportError:
  985. self.skipTest('locale.CHAR_MAX not available')
  986. def make_grouping(lst):
  987. return ''.join([chr(x) for x in lst]) if self.decimal == C else lst
  988. def get_fmt(x, override=None, fmt='n'):
  989. if self.decimal == C:
  990. return Decimal(x).__format__(fmt, override)
  991. else:
  992. return Decimal(x).__format__(fmt, _localeconv=override)
  993. # Set up some localeconv-like dictionaries
  994. en_US = {
  995. 'decimal_point' : '.',
  996. 'grouping' : make_grouping([3, 3, 0]),
  997. 'thousands_sep' : ','
  998. }
  999. fr_FR = {
  1000. 'decimal_point' : ',',
  1001. 'grouping' : make_grouping([CHAR_MAX]),
  1002. 'thousands_sep' : ''
  1003. }
  1004. ru_RU = {
  1005. 'decimal_point' : ',',
  1006. 'grouping': make_grouping([3, 3, 0]),
  1007. 'thousands_sep' : ' '
  1008. }
  1009. crazy = {
  1010. 'decimal_point' : '&',
  1011. 'grouping': make_grouping([1, 4, 2, CHAR_MAX]),
  1012. 'thousands_sep' : '-'
  1013. }
  1014. dotsep_wide = {
  1015. 'decimal_point' : b'\xc2\xbf'.decode('utf-8'),
  1016. 'grouping': make_grouping([3, 3, 0]),
  1017. 'thousands_sep' : b'\xc2\xb4'.decode('utf-8')
  1018. }
  1019. self.assertEqual(get_fmt(Decimal('12.7'), en_US), '12.7')
  1020. self.assertEqual(get_fmt(Decimal('12.7'), fr_FR), '12,7')
  1021. self.assertEqual(get_fmt(Decimal('12.7'), ru_RU), '12,7')
  1022. self.assertEqual(get_fmt(Decimal('12.7'), crazy), '1-2&7')
  1023. self.assertEqual(get_fmt(123456789, en_US), '123,456,789')
  1024. self.assertEqual(get_fmt(123456789, fr_FR), '123456789')
  1025. self.assertEqual(get_fmt(123456789, ru_RU), '123 456 789')
  1026. self.assertEqual(get_fmt(1234567890123, crazy), '123456-78-9012-3')
  1027. self.assertEqual(get_fmt(123456789, en_US, '.6n'), '1.23457e+8')
  1028. self.assertEqual(get_fmt(123456789, fr_FR, '.6n'), '1,23457e+8')
  1029. self.assertEqual(get_fmt(123456789, ru_RU, '.6n'), '1,23457e+8')
  1030. self.assertEqual(get_fmt(123456789, crazy, '.6n'), '1&23457e+8')
  1031. # zero padding
  1032. self.assertEqual(get_fmt(1234, fr_FR, '03n'), '1234')
  1033. self.assertEqual(get_fmt(1234, fr_FR, '04n'), '1234')
  1034. self.assertEqual(get_fmt(1234, fr_FR, '05n'), '01234')
  1035. self.assertEqual(get_fmt(1234, fr_FR, '06n'), '001234')
  1036. self.assertEqual(get_fmt(12345, en_US, '05n'), '12,345')
  1037. self.assertEqual(get_fmt(12345, en_US, '06n'), '12,345')
  1038. self.assertEqual(get_fmt(12345, en_US, '07n'), '012,345')
  1039. self.assertEqual(get_fmt(12345, en_US, '08n'), '0,012,345')
  1040. self.assertEqual(get_fmt(12345, en_US, '09n'), '0,012,345')
  1041. self.assertEqual(get_fmt(12345, en_US, '010n'), '00,012,345')
  1042. self.assertEqual(get_fmt(123456, crazy, '06n'), '1-2345-6')
  1043. self.assertEqual(get_fmt(123456, crazy, '07n'), '1-2345-6')
  1044. self.assertEqual(get_fmt(123456, crazy, '08n'), '1-2345-6')
  1045. self.assertEqual(get_fmt(123456, crazy, '09n'), '01-2345-6')
  1046. self.assertEqual(get_fmt(123456, crazy, '010n'), '0-01-2345-6')
  1047. self.assertEqual(get_fmt(123456, crazy, '011n'), '0-01-2345-6')
  1048. self.assertEqual(get_fmt(123456, crazy, '012n'), '00-01-2345-6')
  1049. self.assertEqual(get_fmt(123456, crazy, '013n'), '000-01-2345-6')
  1050. # wide char separator and decimal point
  1051. self.assertEqual(get_fmt(Decimal('-1.5'), dotsep_wide, '020n'),
  1052. '-0\u00b4000\u00b4000\u00b4000\u00b4001\u00bf5')
  1053. @run_with_locale('LC_ALL', 'ps_AF')
  1054. def test_wide_char_separator_decimal_point(self):
  1055. # locale with wide char separator and decimal point
  1056. Decimal = self.decimal.Decimal
  1057. decimal_point = locale.localeconv()['decimal_point']
  1058. thousands_sep = locale.localeconv()['thousands_sep']
  1059. if decimal_point != '\u066b':
  1060. self.skipTest('inappropriate decimal point separator '
  1061. '({!a} not {!a})'.format(decimal_point, '\u066b'))
  1062. if thousands_sep != '\u066c':
  1063. self.skipTest('inappropriate thousands separator '
  1064. '({!a} not {!a})'.format(thousands_sep, '\u066c'))
  1065. self.assertEqual(format(Decimal('100000000.123'), 'n'),
  1066. '100\u066c000\u066c000\u066b123')
  1067. def test_decimal_from_float_argument_type(self):
  1068. class A(self.decimal.Decimal):
  1069. def __init__(self, a):
  1070. self.a_type = type(a)
  1071. a = A.from_float(42.5)
  1072. self.assertEqual(self.decimal.Decimal, a.a_type)
  1073. a = A.from_float(42)
  1074. self.assertEqual(self.decimal.Decimal, a.a_type)
  1075. class CFormatTest(FormatTest):
  1076. decimal = C
  1077. class PyFormatTest(FormatTest):
  1078. decimal = P
  1079. class ArithmeticOperatorsTest(unittest.TestCase):
  1080. '''Unit tests for all arithmetic operators, binary and unary.'''
  1081. def test_addition(self):
  1082. Decimal = self.decimal.Decimal
  1083. d1 = Decimal('-11.1')
  1084. d2 = Decimal('22.2')
  1085. #two Decimals
  1086. self.assertEqual(d1+d2, Decimal('11.1'))
  1087. self.assertEqual(d2+d1, Decimal('11.1'))
  1088. #with other type, left
  1089. c = d1 + 5
  1090. self.assertEqual(c, Decimal('-6.1'))
  1091. self.assertEqual(type(c), type(d1))
  1092. #with other type, right
  1093. c = 5 + d1
  1094. self.assertEqual(c, Decimal('-6.1'))
  1095. self.assertEqual(type(c), type(d1))
  1096. #inline with decimal
  1097. d1 += d2
  1098. self.assertEqual(d1, Decimal('11.1'))
  1099. #inline with other type
  1100. d1 += 5
  1101. self.assertEqual(d1, Decimal('16.1'))
  1102. def test_subtraction(self):
  1103. Decimal = self.decimal.Decimal
  1104. d1 = Decimal('-11.1')
  1105. d2 = Decimal('22.2')
  1106. #two Decimals
  1107. self.assertEqual(d1-d2, Decimal('-33.3'))
  1108. self.assertEqual(d2-d1, Decimal('33.3'))
  1109. #with other type, left
  1110. c = d1 - 5
  1111. self.assertEqual(c, Decimal('-16.1'))
  1112. self.assertEqual(type(c), type(d1))
  1113. #with other type, right
  1114. c = 5 - d1
  1115. self.assertEqual(c, Decimal('16.1'))
  1116. self.assertEqual(type(c), type(d1))
  1117. #inline with decimal
  1118. d1 -= d2
  1119. self.assertEqual(d1, Decimal('-33.3'))
  1120. #inline with other type
  1121. d1 -= 5
  1122. self.assertEqual(d1, Decimal('-38.3'))
  1123. def test_multiplication(self):
  1124. Decimal = self.decimal.Decimal
  1125. d1 = Decimal('-5')
  1126. d2 = Decimal('3')
  1127. #two Decimals
  1128. self.assertEqual(d1*d2, Decimal('-15'))
  1129. self.assertEqual(d2*d1, Decimal('-15'))
  1130. #with other type, left
  1131. c = d1 * 5
  1132. self.assertEqual(c, Decimal('-25'))
  1133. self.assertEqual(type(c), type(d1))
  1134. #with other type, right
  1135. c = 5 * d1
  1136. self.assertEqual(c, Decimal('-25'))
  1137. self.assertEqual(type(c), type(d1))
  1138. #inline with decimal
  1139. d1 *= d2
  1140. self.assertEqual(d1, Decimal('-15'))
  1141. #inline with other type
  1142. d1 *= 5
  1143. self.assertEqual(d1, Decimal('-75'))
  1144. def test_division(self):
  1145. Decimal = self.decimal.Decimal
  1146. d1 = Decimal('-5')
  1147. d2 = Decimal('2')
  1148. #two Decimals
  1149. self.assertEqual(d1/d2, Decimal('-2.5'))
  1150. self.assertEqual(d2/d1, Decimal('-0.4'))
  1151. #with other type, left
  1152. c = d1 / 4
  1153. self.assertEqual(c, Decimal('-1.25'))
  1154. self.assertEqual(type(c), type(d1))
  1155. #with other type, right
  1156. c = 4 / d1
  1157. self.assertEqual(c, Decimal('-0.8'))
  1158. self.assertEqual(type(c), type(d1))
  1159. #inline with decimal
  1160. d1 /= d2
  1161. self.assertEqual(d1, Decimal('-2.5'))
  1162. #inline with other type
  1163. d1 /= 4
  1164. self.assertEqual(d1, Decimal('-0.625'))
  1165. def test_floor_division(self):
  1166. Decimal = self.decimal.Decimal
  1167. d1 = Decimal('5')
  1168. d2 = Decimal('2')
  1169. #two Decimals
  1170. self.assertEqual(d1//d2, Decimal('2'))
  1171. self.assertEqual(d2//d1, Decimal('0'))
  1172. #with other type, left
  1173. c = d1 // 4
  1174. self.assertEqual(c, Decimal('1'))
  1175. self.assertEqual(type(c), type(d1))
  1176. #with other type, right
  1177. c = 7 // d1
  1178. self.assertEqual(c, Decimal('1'))
  1179. self.assertEqual(type(c), type(d1))
  1180. #inline with decimal
  1181. d1 //= d2
  1182. self.assertEqual(d1, Decimal('2'))
  1183. #inline with other type
  1184. d1 //= 2
  1185. self.assertEqual(d1, Decimal('1'))
  1186. def test_powering(self):
  1187. Decimal = self.decimal.Decimal
  1188. d1 = Decimal('5')
  1189. d2 = Decimal('2')
  1190. #two Decimals
  1191. self.assertEqual(d1**d2, Decimal('25'))
  1192. self.assertEqual(d2**d1, Decimal('32'))
  1193. #with other type, left
  1194. c = d1 ** 4
  1195. self.assertEqual(c, Decimal('625'))
  1196. self.assertEqual(type(c), type(d1))
  1197. #with other type, right
  1198. c = 7 ** d1
  1199. self.assertEqual(c, Decimal('16807'))
  1200. self.assertEqual(type(c), type(d1))
  1201. #inline with decimal
  1202. d1 **= d2
  1203. self.assertEqual(d1, Decimal('25'))
  1204. #inline with other type
  1205. d1 **= 4
  1206. self.assertEqual(d1, Decimal('390625'))
  1207. def test_module(self):
  1208. Decimal = self.decimal.Decimal
  1209. d1 = Decimal('5')
  1210. d2 = Decimal('2')
  1211. #two Decimals
  1212. self.assertEqual(d1%d2, Decimal('1'))
  1213. self.assertEqual(d2%d1, Decimal('2'))
  1214. #with other type, left
  1215. c = d1 % 4
  1216. self.assertEqual(c, Decimal('1'))
  1217. self.assertEqual(type(c), type(d1))
  1218. #with other type, right
  1219. c = 7 % d1
  1220. self.assertEqual(c, Decimal('2'))
  1221. self.assertEqual(type(c), type(d1))
  1222. #inline with decimal
  1223. d1 %= d2
  1224. self.assertEqual(d1, Decimal('1'))
  1225. #inline with other type
  1226. d1 %= 4
  1227. self.assertEqual(d1, Decimal('1'))
  1228. def test_floor_div_module(self):
  1229. Decimal = self.decimal.Decimal
  1230. d1 = Decimal('5')
  1231. d2 = Decimal('2')
  1232. #two Decimals
  1233. (p, q) = divmod(d1, d2)
  1234. self.assertEqual(p, Decimal('2'))
  1235. self.assertEqual(q, Decimal('1'))
  1236. self.assertEqual(type(p), type(d1))
  1237. self.assertEqual(type(q), type(d1))
  1238. #with other type, left
  1239. (p, q) = divmod(d1, 4)
  1240. self.assertEqual(p, Decimal('1'))
  1241. self.assertEqual(q, Decimal('1'))
  1242. self.assertEqual(type(p), type(d1))
  1243. self.assertEqual(type(q), type(d1))
  1244. #with other type, right
  1245. (p, q) = divmod(7, d1)
  1246. self.assertEqual(p, Decimal('1'))
  1247. self.assertEqual(q, Decimal('2'))
  1248. self.assertEqual(type(p), type(d1))
  1249. self.assertEqual(type(q), type(d1))
  1250. def test_unary_operators(self):
  1251. Decimal = self.decimal.Decimal
  1252. self.assertEqual(+Decimal(45), Decimal(+45)) # +
  1253. self.assertEqual(-Decimal(45), Decimal(-45)) # -
  1254. self.assertEqual(abs(Decimal(45)), abs(Decimal(-45))) # abs
  1255. def test_nan_comparisons(self):
  1256. # comparisons involving signaling nans signal InvalidOperation
  1257. # order comparisons (<, <=, >, >=) involving only quiet nans
  1258. # also signal InvalidOperation
  1259. # equality comparisons (==, !=) involving only quiet nans
  1260. # don't signal, but return False or True respectively.
  1261. Decimal = self.decimal.Decimal
  1262. InvalidOperation = self.decimal.InvalidOperation
  1263. localcontext = self.decimal.localcontext
  1264. n = Decimal('NaN')
  1265. s = Decimal('sNaN')
  1266. i = Decimal('Inf')
  1267. f = Decimal('2')
  1268. qnan_pairs = (n, n), (n, i), (i, n), (n, f), (f, n)
  1269. snan_pairs = (s, n), (n, s), (s, i), (i, s), (s, f), (f, s), (s, s)
  1270. order_ops = operator.lt, operator.le, operator.gt, operator.ge
  1271. equality_ops = operator.eq, operator.ne
  1272. # results when InvalidOperation is not trapped
  1273. for x, y in qnan_pairs + snan_pairs:
  1274. for op in order_ops + equality_ops:
  1275. got = op(x, y)
  1276. expected = True if op is operator.ne else False
  1277. self.assertIs(expected, got,
  1278. "expected {0!r} for operator.{1}({2!r}, {3!r}); "
  1279. "got {4!r}".format(
  1280. expected, op.__name__, x, y, got))
  1281. # repeat the above, but this time trap the InvalidOperation
  1282. with localcontext() as ctx:
  1283. ctx.traps[InvalidOperation] = 1
  1284. for x, y in qnan_pairs:
  1285. for op in equality_ops:
  1286. got = op(x, y)
  1287. expected = True if op is operator.ne else False
  1288. self.assertIs(expected, got,
  1289. "expected {0!r} for "
  1290. "operator.{1}({2!r}, {3!r}); "
  1291. "got {4!r}".format(
  1292. expected, op.__name__, x, y, got))
  1293. for x, y in snan_pairs:
  1294. for op in equality_ops:
  1295. self.assertRaises(InvalidOperation, operator.eq, x, y)
  1296. self.assertRaises(InvalidOperation, operator.ne, x, y)
  1297. for x, y in qnan_pairs + snan_pairs:
  1298. for op in order_ops:
  1299. self.assertRaises(InvalidOperation, op, x, y)
  1300. def test_copy_sign(self):
  1301. Decimal = self.decimal.Decimal
  1302. d = Decimal(1).copy_sign(Decimal(-2))
  1303. self.assertEqual(Decimal(1).copy_sign(-2), d)
  1304. self.assertRaises(TypeError, Decimal(1).copy_sign, '-2')
  1305. class CArithmeticOperatorsTest(ArithmeticOperatorsTest):
  1306. decimal = C
  1307. class PyArithmeticOperatorsTest(ArithmeticOperatorsTest):
  1308. decimal = P
  1309. # The following are two functions used to test threading in the next class
  1310. def thfunc1(cls):
  1311. Decimal = cls.decimal.Decimal
  1312. InvalidOperation = cls.decimal.InvalidOperation
  1313. DivisionByZero = cls.decimal.DivisionByZero
  1314. Overflow = cls.decimal.Overflow
  1315. Underflow = cls.decimal.Underflow
  1316. Inexact = cls.decimal.Inexact
  1317. getcontext = cls.decimal.getcontext
  1318. localcontext = cls.decimal.localcontext
  1319. d1 = Decimal(1)
  1320. d3 = Decimal(3)
  1321. test1 = d1/d3
  1322. cls.finish1.set()
  1323. cls.synchro.wait()
  1324. test2 = d1/d3
  1325. with localcontext() as c2:
  1326. cls.assertTrue(c2.flags[Inexact])
  1327. cls.assertRaises(DivisionByZero, c2.divide, d1, 0)
  1328. cls.assertTrue(c2.flags[DivisionByZero])
  1329. with localcontext() as c3:
  1330. cls.assertTrue(c3.flags[Inexact])
  1331. cls.assertTrue(c3.flags[DivisionByZero])
  1332. cls.assertRaises(InvalidOperation, c3.compare, d1, Decimal('sNaN'))
  1333. cls.assertTrue(c3.flags[InvalidOperation])
  1334. del c3
  1335. cls.assertFalse(c2.flags[InvalidOperation])
  1336. del c2
  1337. cls.assertEqual(test1, Decimal('0.333333333333333333333333'))
  1338. cls.assertEqual(test2, Decimal('0.333333333333333333333333'))
  1339. c1 = getcontext()
  1340. cls.assertTrue(c1.flags[Inexact])
  1341. for sig in Overflow, Underflow, DivisionByZero, InvalidOperation:
  1342. cls.assertFalse(c1.flags[sig])
  1343. def thfunc2(cls):
  1344. Decimal = cls.decimal.Decimal
  1345. InvalidOperation = cls.decimal.InvalidOperation
  1346. DivisionByZero = cls.decimal.DivisionByZero
  1347. Overflow = cls.decimal.Overflow
  1348. Underflow = cls.decimal.Underflow
  1349. Inexact = cls.decimal.Inexact
  1350. getcontext = cls.decimal.getcontext
  1351. localcontext = cls.decimal.localcontext
  1352. d1 = Decimal(1)
  1353. d3 = Decimal(3)
  1354. test1 = d1/d3
  1355. thiscontext = getcontext()
  1356. thiscontext.prec = 18
  1357. test2 = d1/d3
  1358. with localcontext() as c2:
  1359. cls.assertTrue(c2.flags[Inexact])
  1360. cls.assertRaises(Overflow, c2.multiply, Decimal('1e425000000'), 999)
  1361. cls.assertTrue(c2.flags[Overflow])
  1362. with localcontext(thiscontext) as c3:
  1363. cls.assertTrue(c3.flags[Inexact])
  1364. cls.assertFalse(c3.flags[Overflow])
  1365. c3.traps[Underflow] = True
  1366. cls.assertRaises(Underflow, c3.divide, Decimal('1e-425000000'), 999)
  1367. cls.assertTrue(c3.flags[Underflow])
  1368. del c3
  1369. cls.assertFalse(c2.flags[Underflow])
  1370. cls.assertFalse(c2.traps[Underflow])
  1371. del c2
  1372. cls.synchro.set()
  1373. cls.finish2.set()
  1374. cls.assertEqual(test1, Decimal('0.333333333333333333333333'))
  1375. cls.assertEqual(test2, Decimal('0.333333333333333333'))
  1376. cls.assertFalse(thiscontext.traps[Underflow])
  1377. cls.assertTrue(thiscontext.flags[Inexact])
  1378. for sig in Overflow, Underflow, DivisionByZero, InvalidOperation:
  1379. cls.assertFalse(thiscontext.flags[sig])
  1380. @threading_helper.requires_working_threading()
  1381. class ThreadingTest(unittest.TestCase):
  1382. '''Unit tests for thread local contexts in Decimal.'''
  1383. # Take care executing this test from IDLE, there's an issue in threading
  1384. # that hangs IDLE and I couldn't find it
  1385. def test_threading(self):
  1386. DefaultContext = self.decimal.DefaultContext
  1387. if self.decimal == C and not self.decimal.HAVE_THREADS:
  1388. self.skipTest("compiled without threading")
  1389. # Test the "threading isolation" of a Context. Also test changing
  1390. # the DefaultContext, which acts as a template for the thread-local
  1391. # contexts.
  1392. save_prec = DefaultContext.prec
  1393. save_emax = DefaultContext.Emax
  1394. save_emin = DefaultContext.Emin
  1395. DefaultContext.prec = 24
  1396. DefaultContext.Emax = 425000000
  1397. DefaultContext.Emin = -425000000
  1398. self.synchro = threading.Event()
  1399. self.finish1 = threading.Event()
  1400. self.finish2 = threading.Event()
  1401. th1 = threading.Thread(target=thfunc1, args=(self,))
  1402. th2 = threading.Thread(target=thfunc2, args=(self,))
  1403. th1.start()
  1404. th2.start()
  1405. self.finish1.wait()
  1406. self.finish2.wait()
  1407. for sig in Signals[self.decimal]:
  1408. self.assertFalse(DefaultContext.flags[sig])
  1409. th1.join()
  1410. th2.join()
  1411. DefaultContext.prec = save_prec
  1412. DefaultContext.Emax = save_emax
  1413. DefaultContext.Emin = save_emin
  1414. class CThreadingTest(ThreadingTest):
  1415. decimal = C
  1416. class PyThreadingTest(ThreadingTest):
  1417. decimal = P
  1418. class UsabilityTest(unittest.TestCase):
  1419. '''Unit tests for Usability cases of Decimal.'''
  1420. def test_comparison_operators(self):
  1421. Decimal = self.decimal.Decimal
  1422. da = Decimal('23.42')
  1423. db = Decimal('23.42')
  1424. dc = Decimal('45')
  1425. #two Decimals
  1426. self.assertGreater(dc, da)
  1427. self.assertGreaterEqual(dc, da)
  1428. self.assertLess(da, dc)
  1429. self.assertLessEqual(da, dc)
  1430. self.assertEqual(da, db)
  1431. self.assertNotEqual(da, dc)
  1432. self.assertLessEqual(da, db)
  1433. self.assertGreaterEqual(da, db)
  1434. #a Decimal and an int
  1435. self.assertGreater(dc, 23)
  1436. self.assertLess(23, dc)
  1437. self.assertEqual(dc, 45)
  1438. #a Decimal and uncomparable
  1439. self.assertNotEqual(da, 'ugly')
  1440. self.assertNotEqual(da, 32.7)
  1441. self.assertNotEqual(da, object())
  1442. self.assertNotEqual(da, object)
  1443. # sortable
  1444. a = list(map(Decimal, range(100)))
  1445. b = a[:]
  1446. random.shuffle(a)
  1447. a.sort()
  1448. self.assertEqual(a, b)
  1449. def test_decimal_float_comparison(self):
  1450. Decimal = self.decimal.Decimal
  1451. da = Decimal('0.25')
  1452. db = Decimal('3.0')
  1453. self.assertLess(da, 3.0)
  1454. self.assertLessEqual(da, 3.0)
  1455. self.assertGreater(db, 0.25)
  1456. self.assertGreaterEqual(db, 0.25)
  1457. self.assertNotEqual(da, 1.5)
  1458. self.assertEqual(da, 0.25)
  1459. self.assertGreater(3.0, da)
  1460. self.assertGreaterEqual(3.0, da)
  1461. self.assertLess(0.25, db)
  1462. self.assertLessEqual(0.25, db)
  1463. self.assertNotEqual(0.25, db)
  1464. self.assertEqual(3.0, db)
  1465. self.assertNotEqual(0.1, Decimal('0.1'))
  1466. def test_decimal_complex_comparison(self):
  1467. Decimal = self.decimal.Decimal
  1468. da = Decimal('0.25')
  1469. db = Decimal('3.0')
  1470. self.assertNotEqual(da, (1.5+0j))
  1471. self.assertNotEqual((1.5+0j), da)
  1472. self.assertEqual(da, (0.25+0j))
  1473. self.assertEqual((0.25+0j), da)
  1474. self.assertEqual((3.0+0j), db)
  1475. self.assertEqual(db, (3.0+0j))
  1476. self.assertNotEqual(db, (3.0+1j))
  1477. self.assertNotEqual((3.0+1j), db)
  1478. self.assertIs(db.__lt__(3.0+0j), NotImplemented)
  1479. self.assertIs(db.__le__(3.0+0j), NotImplemented)
  1480. self.assertIs(db.__gt__(3.0+0j), NotImplemented)
  1481. self.assertIs(db.__le__(3.0+0j), NotImplemented)
  1482. def test_decimal_fraction_comparison(self):
  1483. D = self.decimal.Decimal
  1484. F = fractions[self.decimal].Fraction
  1485. Context = self.decimal.Context
  1486. localcontext = self.decimal.localcontext
  1487. InvalidOperation = self.decimal.InvalidOperation
  1488. emax = C.MAX_EMAX if C else 999999999
  1489. emin = C.MIN_EMIN if C else -999999999
  1490. etiny = C.MIN_ETINY if C else -1999999997
  1491. c = Context(Emax=emax, Emin=emin)
  1492. with localcontext(c):
  1493. c.prec = emax
  1494. self.assertLess(D(0), F(1,9999999999999999999999999999999999999))
  1495. self.assertLess(F(-1,9999999999999999999999999999999999999), D(0))
  1496. self.assertLess(F(0,1), D("1e" + str(etiny)))
  1497. self.assertLess(D("-1e" + str(etiny)), F(0,1))
  1498. self.assertLess(F(0,9999999999999999999999999), D("1e" + str(etiny)))
  1499. self.assertLess(D("-1e" + str(etiny)), F(0,9999999999999999999999999))
  1500. self.assertEqual(D("0.1"), F(1,10))
  1501. self.assertEqual(F(1,10), D("0.1"))
  1502. c.prec = 300
  1503. self.assertNotEqual(D(1)/3, F(1,3))
  1504. self.assertNotEqual(F(1,3), D(1)/3)
  1505. self.assertLessEqual(F(120984237, 9999999999), D("9e" + str(emax)))
  1506. self.assertGreaterEqual(D("9e" + str(emax)), F(120984237, 9999999999))
  1507. self.assertGreater(D('inf'), F(99999999999,123))
  1508. self.assertGreater(D('inf'), F(-99999999999,123))
  1509. self.assertLess(D('-inf'), F(99999999999,123))
  1510. self.assertLess(D('-inf'), F(-99999999999,123))
  1511. self.assertRaises(InvalidOperation, D('nan').__gt__, F(-9,123))
  1512. self.assertIs(NotImplemented, F(-9,123).__lt__(D('nan')))
  1513. self.assertNotEqual(D('nan'), F(-9,123))
  1514. self.assertNotEqual(F(-9,123), D('nan'))
  1515. def test_copy_and_deepcopy_methods(self):
  1516. Decimal = self.decimal.Decimal
  1517. d = Decimal('43.24')
  1518. c = copy.copy(d)
  1519. self.assertEqual(id(c), id(d))
  1520. dc = copy.deepcopy(d)
  1521. self.assertEqual(id(dc), id(d))
  1522. def test_hash_method(self):
  1523. Decimal = self.decimal.Decimal
  1524. localcontext = self.decimal.localcontext
  1525. def hashit(d):
  1526. a = hash(d)
  1527. b = d.__hash__()
  1528. self.assertEqual(a, b)
  1529. return a
  1530. #just that it's hashable
  1531. hashit(Decimal(23))
  1532. hashit(Decimal('Infinity'))
  1533. hashit(Decimal('-Infinity'))
  1534. hashit(Decimal('nan123'))
  1535. hashit(Decimal('-NaN'))
  1536. test_values = [Decimal(sign*(2**m + n))
  1537. for m in [0, 14, 15, 16, 17, 30, 31,
  1538. 32, 33, 61, 62, 63, 64, 65, 66]
  1539. for n in range(-10, 10)
  1540. for sign in [-1, 1]]
  1541. test_values.extend([
  1542. Decimal("-1"), # ==> -2
  1543. Decimal("-0"), # zeros
  1544. Decimal("0.00"),
  1545. Decimal("-0.000"),
  1546. Decimal("0E10"),
  1547. Decimal("-0E12"),
  1548. Decimal("10.0"), # negative exponent
  1549. Decimal("-23.00000"),
  1550. Decimal("1230E100"), # positive exponent
  1551. Decimal("-4.5678E50"),
  1552. # a value for which hash(n) != hash(n % (2**64-1))
  1553. # in Python pre-2.6
  1554. Decimal(2**64 + 2**32 - 1),
  1555. # selection of values which fail with the old (before
  1556. # version 2.6) long.__hash__
  1557. Decimal("1.634E100"),
  1558. Decimal("90.697E100"),
  1559. Decimal("188.83E100"),
  1560. Decimal("1652.9E100"),
  1561. Decimal("56531E100"),
  1562. ])
  1563. # check that hash(d) == hash(int(d)) for integral values
  1564. for value in test_values:
  1565. self.assertEqual(hashit(value), hash(int(value)))
  1566. # check that the hashes of a Decimal float match when they
  1567. # represent exactly the same values
  1568. test_strings = ['inf', '-Inf', '0.0', '-.0e1',
  1569. '34.0', '2.5', '112390.625', '-0.515625']
  1570. for s in test_strings:
  1571. f = float(s)
  1572. d = Decimal(s)
  1573. self.assertEqual(hashit(d), hash(f))
  1574. with localcontext() as c:
  1575. # check that the value of the hash doesn't depend on the
  1576. # current context (issue #1757)
  1577. x = Decimal("123456789.1")
  1578. c.prec = 6
  1579. h1 = hashit(x)
  1580. c.prec = 10
  1581. h2 = hashit(x)
  1582. c.prec = 16
  1583. h3 = hashit(x)
  1584. self.assertEqual(h1, h2)
  1585. self.assertEqual(h1, h3)
  1586. c.prec = 10000
  1587. x = 1100 ** 1248
  1588. self.assertEqual(hashit(Decimal(x)), hashit(x))
  1589. def test_hash_method_nan(self):
  1590. Decimal = self.decimal.Decimal
  1591. self.assertRaises(TypeError, hash, Decimal('sNaN'))
  1592. value = Decimal('NaN')
  1593. self.assertEqual(hash(value), object.__hash__(value))
  1594. class H:
  1595. def __hash__(self):
  1596. return 42
  1597. class D(Decimal, H):
  1598. pass
  1599. value = D('NaN')
  1600. self.assertEqual(hash(value), object.__hash__(value))
  1601. def test_min_and_max_methods(self):
  1602. Decimal = self.decimal.Decimal
  1603. d1 = Decimal('15.32')
  1604. d2 = Decimal('28.5')
  1605. l1 = 15
  1606. l2 = 28
  1607. #between Decimals
  1608. self.assertIs(min(d1,d2), d1)
  1609. self.assertIs(min(d2,d1), d1)
  1610. self.assertIs(max(d1,d2), d2)
  1611. self.assertIs(max(d2,d1), d2)
  1612. #between Decimal and int
  1613. self.assertIs(min(d1,l2), d1)
  1614. self.assertIs(min(l2,d1), d1)
  1615. self.assertIs(max(l1,d2), d2)
  1616. self.assertIs(max(d2,l1), d2)
  1617. def test_as_nonzero(self):
  1618. Decimal = self.decimal.Decimal
  1619. #as false
  1620. self.assertFalse(Decimal(0))
  1621. #as true
  1622. self.assertTrue(Decimal('0.372'))
  1623. def test_tostring_methods(self):
  1624. #Test str and repr methods.
  1625. Decimal = self.decimal.Decimal
  1626. d = Decimal('15.32')
  1627. self.assertEqual(str(d), '15.32') # str
  1628. self.assertEqual(repr(d), "Decimal('15.32')") # repr
  1629. def test_tonum_methods(self):
  1630. #Test float and int methods.
  1631. Decimal = self.decimal.Decimal
  1632. d1 = Decimal('66')
  1633. d2 = Decimal('15.32')
  1634. #int
  1635. self.assertEqual(int(d1), 66)
  1636. self.assertEqual(int(d2), 15)
  1637. #float
  1638. self.assertEqual(float(d1), 66)
  1639. self.assertEqual(float(d2), 15.32)
  1640. #floor
  1641. test_pairs = [
  1642. ('123.00', 123),
  1643. ('3.2', 3),
  1644. ('3.54', 3),
  1645. ('3.899', 3),
  1646. ('-2.3', -3),
  1647. ('-11.0', -11),
  1648. ('0.0', 0),
  1649. ('-0E3', 0),
  1650. ('89891211712379812736.1', 89891211712379812736),
  1651. ]
  1652. for d, i in test_pairs:
  1653. self.assertEqual(math.floor(Decimal(d)), i)
  1654. self.assertRaises(ValueError, math.floor, Decimal('-NaN'))
  1655. self.assertRaises(ValueError, math.floor, Decimal('sNaN'))
  1656. self.assertRaises(ValueError, math.floor, Decimal('NaN123'))
  1657. self.assertRaises(OverflowError, math.floor, Decimal('Inf'))
  1658. self.assertRaises(OverflowError, math.floor, Decimal('-Inf'))
  1659. #ceiling
  1660. test_pairs = [
  1661. ('123.00', 123),
  1662. ('3.2', 4),
  1663. ('3.54', 4),
  1664. ('3.899', 4),
  1665. ('-2.3', -2),
  1666. ('-11.0', -11),
  1667. ('0.0', 0),
  1668. ('-0E3', 0),
  1669. ('89891211712379812736.1', 89891211712379812737),
  1670. ]
  1671. for d, i in test_pairs:
  1672. self.assertEqual(math.ceil(Decimal(d)), i)
  1673. self.assertRaises(ValueError, math.ceil, Decimal('-NaN'))
  1674. self.assertRaises(ValueError, math.ceil, Decimal('sNaN'))
  1675. self.assertRaises(ValueError, math.ceil, Decimal('NaN123'))
  1676. self.assertRaises(OverflowError, math.ceil, Decimal('Inf'))
  1677. self.assertRaises(OverflowError, math.ceil, Decimal('-Inf'))
  1678. #round, single argument
  1679. test_pairs = [
  1680. ('123.00', 123),
  1681. ('3.2', 3),
  1682. ('3.54', 4),
  1683. ('3.899', 4),
  1684. ('-2.3', -2),
  1685. ('-11.0', -11),
  1686. ('0.0', 0),
  1687. ('-0E3', 0),
  1688. ('-3.5', -4),
  1689. ('-2.5', -2),
  1690. ('-1.5', -2),
  1691. ('-0.5', 0),
  1692. ('0.5', 0),
  1693. ('1.5', 2),
  1694. ('2.5', 2),
  1695. ('3.5', 4),
  1696. ]
  1697. for d, i in test_pairs:
  1698. self.assertEqual(round(Decimal(d)), i)
  1699. self.assertRaises(ValueError, round, Decimal('-NaN'))
  1700. self.assertRaises(ValueError, round, Decimal('sNaN'))
  1701. self.assertRaises(ValueError, round, Decimal('NaN123'))
  1702. self.assertRaises(OverflowError, round, Decimal('Inf'))
  1703. self.assertRaises(OverflowError, round, Decimal('-Inf'))
  1704. #round, two arguments; this is essentially equivalent
  1705. #to quantize, which is already extensively tested
  1706. test_triples = [
  1707. ('123.456', -4, '0E+4'),
  1708. ('123.456', -3, '0E+3'),
  1709. ('123.456', -2, '1E+2'),
  1710. ('123.456', -1, '1.2E+2'),
  1711. ('123.456', 0, '123'),
  1712. ('123.456', 1, '123.5'),
  1713. ('123.456', 2, '123.46'),
  1714. ('123.456', 3, '123.456'),
  1715. ('123.456', 4, '123.4560'),
  1716. ('123.455', 2, '123.46'),
  1717. ('123.445', 2, '123.44'),
  1718. ('Inf', 4, 'NaN'),
  1719. ('-Inf', -23, 'NaN'),
  1720. ('sNaN314', 3, 'NaN314'),
  1721. ]
  1722. for d, n, r in test_triples:
  1723. self.assertEqual(str(round(Decimal(d), n)), r)
  1724. def test_nan_to_float(self):
  1725. # Test conversions of decimal NANs to float.
  1726. # See http://bugs.python.org/issue15544
  1727. Decimal = self.decimal.Decimal
  1728. for s in ('nan', 'nan1234', '-nan', '-nan2468'):
  1729. f = float(Decimal(s))
  1730. self.assertTrue(math.isnan(f))
  1731. sign = math.copysign(1.0, f)
  1732. self.assertEqual(sign, -1.0 if s.startswith('-') else 1.0)
  1733. def test_snan_to_float(self):
  1734. Decimal = self.decimal.Decimal
  1735. for s in ('snan', '-snan', 'snan1357', '-snan1234'):
  1736. d = Decimal(s)
  1737. self.assertRaises(ValueError, float, d)
  1738. def test_eval_round_trip(self):
  1739. Decimal = self.decimal.Decimal
  1740. #with zero
  1741. d = Decimal( (0, (0,), 0) )
  1742. self.assertEqual(d, eval(repr(d)))
  1743. #int
  1744. d = Decimal( (1, (4, 5), 0) )
  1745. self.assertEqual(d, eval(repr(d)))
  1746. #float
  1747. d = Decimal( (0, (4, 5, 3, 4), -2) )
  1748. self.assertEqual(d, eval(repr(d)))
  1749. #weird
  1750. d = Decimal( (1, (4, 3, 4, 9, 1, 3, 5, 3, 4), -25) )
  1751. self.assertEqual(d, eval(repr(d)))
  1752. def test_as_tuple(self):
  1753. Decimal = self.decimal.Decimal
  1754. #with zero
  1755. d = Decimal(0)
  1756. self.assertEqual(d.as_tuple(), (0, (0,), 0) )
  1757. #int
  1758. d = Decimal(-45)
  1759. self.assertEqual(d.as_tuple(), (1, (4, 5), 0) )
  1760. #complicated string
  1761. d = Decimal("-4.34913534E-17")
  1762. self.assertEqual(d.as_tuple(), (1, (4, 3, 4, 9, 1, 3, 5, 3, 4), -25) )
  1763. # The '0' coefficient is implementation specific to decimal.py.
  1764. # It has no meaning in the C-version and is ignored there.
  1765. d = Decimal("Infinity")
  1766. self.assertEqual(d.as_tuple(), (0, (0,), 'F') )
  1767. #leading zeros in coefficient should be stripped
  1768. d = Decimal( (0, (0, 0, 4, 0, 5, 3, 4), -2) )
  1769. self.assertEqual(d.as_tuple(), (0, (4, 0, 5, 3, 4), -2) )
  1770. d = Decimal( (1, (0, 0, 0), 37) )
  1771. self.assertEqual(d.as_tuple(), (1, (0,), 37))
  1772. d = Decimal( (1, (), 37) )
  1773. self.assertEqual(d.as_tuple(), (1, (0,), 37))
  1774. #leading zeros in NaN diagnostic info should be stripped
  1775. d = Decimal( (0, (0, 0, 4, 0, 5, 3, 4), 'n') )
  1776. self.assertEqual(d.as_tuple(), (0, (4, 0, 5, 3, 4), 'n') )
  1777. d = Decimal( (1, (0, 0, 0), 'N') )
  1778. self.assertEqual(d.as_tuple(), (1, (), 'N') )
  1779. d = Decimal( (1, (), 'n') )
  1780. self.assertEqual(d.as_tuple(), (1, (), 'n') )
  1781. # For infinities, decimal.py has always silently accepted any
  1782. # coefficient tuple.
  1783. d = Decimal( (0, (0,), 'F') )
  1784. self.assertEqual(d.as_tuple(), (0, (0,), 'F'))
  1785. d = Decimal( (0, (4, 5, 3, 4), 'F') )
  1786. self.assertEqual(d.as_tuple(), (0, (0,), 'F'))
  1787. d = Decimal( (1, (0, 2, 7, 1), 'F') )
  1788. self.assertEqual(d.as_tuple(), (1, (0,), 'F'))
  1789. def test_as_integer_ratio(self):
  1790. Decimal = self.decimal.Decimal
  1791. # exceptional cases
  1792. self.assertRaises(OverflowError,
  1793. Decimal.as_integer_ratio, Decimal('inf'))
  1794. self.assertRaises(OverflowError,
  1795. Decimal.as_integer_ratio, Decimal('-inf'))
  1796. self.assertRaises(ValueError,
  1797. Decimal.as_integer_ratio, Decimal('-nan'))
  1798. self.assertRaises(ValueError,
  1799. Decimal.as_integer_ratio, Decimal('snan123'))
  1800. for exp in range(-4, 2):
  1801. for coeff in range(1000):
  1802. for sign in '+', '-':
  1803. d = Decimal('%s%dE%d' % (sign, coeff, exp))
  1804. pq = d.as_integer_ratio()
  1805. p, q = pq
  1806. # check return type
  1807. self.assertIsInstance(pq, tuple)
  1808. self.assertIsInstance(p, int)
  1809. self.assertIsInstance(q, int)
  1810. # check normalization: q should be positive;
  1811. # p should be relatively prime to q.
  1812. self.assertGreater(q, 0)
  1813. self.assertEqual(math.gcd(p, q), 1)
  1814. # check that p/q actually gives the correct value
  1815. self.assertEqual(Decimal(p) / Decimal(q), d)
  1816. def test_subclassing(self):
  1817. # Different behaviours when subclassing Decimal
  1818. Decimal = self.decimal.Decimal
  1819. class MyDecimal(Decimal):
  1820. y = None
  1821. d1 = MyDecimal(1)
  1822. d2 = MyDecimal(2)
  1823. d = d1 + d2
  1824. self.assertIs(type(d), Decimal)
  1825. d = d1.max(d2)
  1826. self.assertIs(type(d), Decimal)
  1827. d = copy.copy(d1)
  1828. self.assertIs(type(d), MyDecimal)
  1829. self.assertEqual(d, d1)
  1830. d = copy.deepcopy(d1)
  1831. self.assertIs(type(d), MyDecimal)
  1832. self.assertEqual(d, d1)
  1833. # Decimal(Decimal)
  1834. d = Decimal('1.0')
  1835. x = Decimal(d)
  1836. self.assertIs(type(x), Decimal)
  1837. self.assertEqual(x, d)
  1838. # MyDecimal(Decimal)
  1839. m = MyDecimal(d)
  1840. self.assertIs(type(m), MyDecimal)
  1841. self.assertEqual(m, d)
  1842. self.assertIs(m.y, None)
  1843. # Decimal(MyDecimal)
  1844. x = Decimal(m)
  1845. self.assertIs(type(x), Decimal)
  1846. self.assertEqual(x, d)
  1847. # MyDecimal(MyDecimal)
  1848. m.y = 9
  1849. x = MyDecimal(m)
  1850. self.assertIs(type(x), MyDecimal)
  1851. self.assertEqual(x, d)
  1852. self.assertIs(x.y, None)
  1853. def test_implicit_context(self):
  1854. Decimal = self.decimal.Decimal
  1855. getcontext = self.decimal.getcontext
  1856. # Check results when context given implicitly. (Issue 2478)
  1857. c = getcontext()
  1858. self.assertEqual(str(Decimal(0).sqrt()),
  1859. str(c.sqrt(Decimal(0))))
  1860. def test_none_args(self):
  1861. Decimal = self.decimal.Decimal
  1862. Context = self.decimal.Context
  1863. localcontext = self.decimal.localcontext
  1864. InvalidOperation = self.decimal.InvalidOperation
  1865. DivisionByZero = self.decimal.DivisionByZero
  1866. Overflow = self.decimal.Overflow
  1867. Underflow = self.decimal.Underflow
  1868. Subnormal = self.decimal.Subnormal
  1869. Inexact = self.decimal.Inexact
  1870. Rounded = self.decimal.Rounded
  1871. Clamped = self.decimal.Clamped
  1872. with localcontext(Context()) as c:
  1873. c.prec = 7
  1874. c.Emax = 999
  1875. c.Emin = -999
  1876. x = Decimal("111")
  1877. y = Decimal("1e9999")
  1878. z = Decimal("1e-9999")
  1879. ##### Unary functions
  1880. c.clear_flags()
  1881. self.assertEqual(str(x.exp(context=None)), '1.609487E+48')
  1882. self.assertTrue(c.flags[Inexact])
  1883. self.assertTrue(c.flags[Rounded])
  1884. c.clear_flags()
  1885. self.assertRaises(Overflow, y.exp, context=None)
  1886. self.assertTrue(c.flags[Overflow])
  1887. self.assertIs(z.is_normal(context=None), False)
  1888. self.assertIs(z.is_subnormal(context=None), True)
  1889. c.clear_flags()
  1890. self.assertEqual(str(x.ln(context=None)), '4.709530')
  1891. self.assertTrue(c.flags[Inexact])
  1892. self.assertTrue(c.flags[Rounded])
  1893. c.clear_flags()
  1894. self.assertRaises(InvalidOperation, Decimal(-1).ln, context=None)
  1895. self.assertTrue(c.flags[InvalidOperation])
  1896. c.clear_flags()
  1897. self.assertEqual(str(x.log10(context=None)), '2.045323')
  1898. self.assertTrue(c.flags[Inexact])
  1899. self.assertTrue(c.flags[Rounded])
  1900. c.clear_flags()
  1901. self.assertRaises(InvalidOperation, Decimal(-1).log10, context=None)
  1902. self.assertTrue(c.flags[InvalidOperation])
  1903. c.clear_flags()
  1904. self.assertEqual(str(x.logb(context=None)), '2')
  1905. self.assertRaises(DivisionByZero, Decimal(0).logb, context=None)
  1906. self.assertTrue(c.flags[DivisionByZero])
  1907. c.clear_flags()
  1908. self.assertEqual(str(x.logical_invert(context=None)), '1111000')
  1909. self.assertRaises(InvalidOperation, y.logical_invert, context=None)
  1910. self.assertTrue(c.flags[InvalidOperation])
  1911. c.clear_flags()
  1912. self.assertEqual(str(y.next_minus(context=None)), '9.999999E+999')
  1913. self.assertRaises(InvalidOperation, Decimal('sNaN').next_minus, context=None)
  1914. self.assertTrue(c.flags[InvalidOperation])
  1915. c.clear_flags()
  1916. self.assertEqual(str(y.next_plus(context=None)), 'Infinity')
  1917. self.assertRaises(InvalidOperation, Decimal('sNaN').next_plus, context=None)
  1918. self.assertTrue(c.flags[InvalidOperation])
  1919. c.clear_flags()
  1920. self.assertEqual(str(z.normalize(context=None)), '0')
  1921. self.assertRaises(Overflow, y.normalize, context=None)
  1922. self.assertTrue(c.flags[Overflow])
  1923. self.assertEqual(str(z.number_class(context=None)), '+Subnormal')
  1924. c.clear_flags()
  1925. self.assertEqual(str(z.sqrt(context=None)), '0E-1005')
  1926. self.assertTrue(c.flags[Clamped])
  1927. self.assertTrue(c.flags[Inexact])
  1928. self.assertTrue(c.flags[Rounded])
  1929. self.assertTrue(c.flags[Subnormal])
  1930. self.assertTrue(c.flags[Underflow])
  1931. c.clear_flags()
  1932. self.assertRaises(Overflow, y.sqrt, context=None)
  1933. self.assertTrue(c.flags[Overflow])
  1934. c.capitals = 0
  1935. self.assertEqual(str(z.to_eng_string(context=None)), '1e-9999')
  1936. c.capitals = 1
  1937. ##### Binary functions
  1938. c.clear_flags()
  1939. ans = str(x.compare(Decimal('Nan891287828'), context=None))
  1940. self.assertEqual(ans, 'NaN1287828')
  1941. self.assertRaises(InvalidOperation, x.compare, Decimal('sNaN'), context=None)
  1942. self.assertTrue(c.flags[InvalidOperation])
  1943. c.clear_flags()
  1944. ans = str(x.compare_signal(8224, context=None))
  1945. self.assertEqual(ans, '-1')
  1946. self.assertRaises(InvalidOperation, x.compare_signal, Decimal('NaN'), context=None)
  1947. self.assertTrue(c.flags[InvalidOperation])
  1948. c.clear_flags()
  1949. ans = str(x.logical_and(101, context=None))
  1950. self.assertEqual(ans, '101')
  1951. self.assertRaises(InvalidOperation, x.logical_and, 123, context=None)
  1952. self.assertTrue(c.flags[InvalidOperation])
  1953. c.clear_flags()
  1954. ans = str(x.logical_or(101, context=None))
  1955. self.assertEqual(ans, '111')
  1956. self.assertRaises(InvalidOperation, x.logical_or, 123, context=None)
  1957. self.assertTrue(c.flags[InvalidOperation])
  1958. c.clear_flags()
  1959. ans = str(x.logical_xor(101, context=None))
  1960. self.assertEqual(ans, '10')
  1961. self.assertRaises(InvalidOperation, x.logical_xor, 123, context=None)
  1962. self.assertTrue(c.flags[InvalidOperation])
  1963. c.clear_flags()
  1964. ans = str(x.max(101, context=None))
  1965. self.assertEqual(ans, '111')
  1966. self.assertRaises(InvalidOperation, x.max, Decimal('sNaN'), context=None)
  1967. self.assertTrue(c.flags[InvalidOperation])
  1968. c.clear_flags()
  1969. ans = str(x.max_mag(101, context=None))
  1970. self.assertEqual(ans, '111')
  1971. self.assertRaises(InvalidOperation, x.max_mag, Decimal('sNaN'), context=None)
  1972. self.assertTrue(c.flags[InvalidOperation])
  1973. c.clear_flags()
  1974. ans = str(x.min(101, context=None))
  1975. self.assertEqual(ans, '101')
  1976. self.assertRaises(InvalidOperation, x.min, Decimal('sNaN'), context=None)
  1977. self.assertTrue(c.flags[InvalidOperation])
  1978. c.clear_flags()
  1979. ans = str(x.min_mag(101, context=None))
  1980. self.assertEqual(ans, '101')
  1981. self.assertRaises(InvalidOperation, x.min_mag, Decimal('sNaN'), context=None)
  1982. self.assertTrue(c.flags[InvalidOperation])
  1983. c.clear_flags()
  1984. ans = str(x.remainder_near(101, context=None))
  1985. self.assertEqual(ans, '10')
  1986. self.assertRaises(InvalidOperation, y.remainder_near, 101, context=None)
  1987. self.assertTrue(c.flags[InvalidOperation])
  1988. c.clear_flags()
  1989. ans = str(x.rotate(2, context=None))
  1990. self.assertEqual(ans, '11100')
  1991. self.assertRaises(InvalidOperation, x.rotate, 101, context=None)
  1992. self.assertTrue(c.flags[InvalidOperation])
  1993. c.clear_flags()
  1994. ans = str(x.scaleb(7, context=None))
  1995. self.assertEqual(ans, '1.11E+9')
  1996. self.assertRaises(InvalidOperation, x.scaleb, 10000, context=None)
  1997. self.assertTrue(c.flags[InvalidOperation])
  1998. c.clear_flags()
  1999. ans = str(x.shift(2, context=None))
  2000. self.assertEqual(ans, '11100')
  2001. self.assertRaises(InvalidOperation, x.shift, 10000, context=None)
  2002. self.assertTrue(c.flags[InvalidOperation])
  2003. ##### Ternary functions
  2004. c.clear_flags()
  2005. ans = str(x.fma(2, 3, context=None))
  2006. self.assertEqual(ans, '225')
  2007. self.assertRaises(Overflow, x.fma, Decimal('1e9999'), 3, context=None)
  2008. self.assertTrue(c.flags[Overflow])
  2009. ##### Special cases
  2010. c.rounding = ROUND_HALF_EVEN
  2011. ans = str(Decimal('1.5').to_integral(rounding=None, context=None))
  2012. self.assertEqual(ans, '2')
  2013. c.rounding = ROUND_DOWN
  2014. ans = str(Decimal('1.5').to_integral(rounding=None, context=None))
  2015. self.assertEqual(ans, '1')
  2016. ans = str(Decimal('1.5').to_integral(rounding=ROUND_UP, context=None))
  2017. self.assertEqual(ans, '2')
  2018. c.clear_flags()
  2019. self.assertRaises(InvalidOperation, Decimal('sNaN').to_integral, context=None)
  2020. self.assertTrue(c.flags[InvalidOperation])
  2021. c.rounding = ROUND_HALF_EVEN
  2022. ans = str(Decimal('1.5').to_integral_value(rounding=None, context=None))
  2023. self.assertEqual(ans, '2')
  2024. c.rounding = ROUND_DOWN
  2025. ans = str(Decimal('1.5').to_integral_value(rounding=None, context=None))
  2026. self.assertEqual(ans, '1')
  2027. ans = str(Decimal('1.5').to_integral_value(rounding=ROUND_UP, context=None))
  2028. self.assertEqual(ans, '2')
  2029. c.clear_flags()
  2030. self.assertRaises(InvalidOperation, Decimal('sNaN').to_integral_value, context=None)
  2031. self.assertTrue(c.flags[InvalidOperation])
  2032. c.rounding = ROUND_HALF_EVEN
  2033. ans = str(Decimal('1.5').to_integral_exact(rounding=None, context=None))
  2034. self.assertEqual(ans, '2')
  2035. c.rounding = ROUND_DOWN
  2036. ans = str(Decimal('1.5').to_integral_exact(rounding=None, context=None))
  2037. self.assertEqual(ans, '1')
  2038. ans = str(Decimal('1.5').to_integral_exact(rounding=ROUND_UP, context=None))
  2039. self.assertEqual(ans, '2')
  2040. c.clear_flags()
  2041. self.assertRaises(InvalidOperation, Decimal('sNaN').to_integral_exact, context=None)
  2042. self.assertTrue(c.flags[InvalidOperation])
  2043. c.rounding = ROUND_UP
  2044. ans = str(Decimal('1.50001').quantize(exp=Decimal('1e-3'), rounding=None, context=None))
  2045. self.assertEqual(ans, '1.501')
  2046. c.rounding = ROUND_DOWN
  2047. ans = str(Decimal('1.50001').quantize(exp=Decimal('1e-3'), rounding=None, context=None))
  2048. self.assertEqual(ans, '1.500')
  2049. ans = str(Decimal('1.50001').quantize(exp=Decimal('1e-3'), rounding=ROUND_UP, context=None))
  2050. self.assertEqual(ans, '1.501')
  2051. c.clear_flags()
  2052. self.assertRaises(InvalidOperation, y.quantize, Decimal('1e-10'), rounding=ROUND_UP, context=None)
  2053. self.assertTrue(c.flags[InvalidOperation])
  2054. with localcontext(Context()) as context:
  2055. context.prec = 7
  2056. context.Emax = 999
  2057. context.Emin = -999
  2058. with localcontext(ctx=None) as c:
  2059. self.assertEqual(c.prec, 7)
  2060. self.assertEqual(c.Emax, 999)
  2061. self.assertEqual(c.Emin, -999)
  2062. def test_conversions_from_int(self):
  2063. # Check that methods taking a second Decimal argument will
  2064. # always accept an integer in place of a Decimal.
  2065. Decimal = self.decimal.Decimal
  2066. self.assertEqual(Decimal(4).compare(3),
  2067. Decimal(4).compare(Decimal(3)))
  2068. self.assertEqual(Decimal(4).compare_signal(3),
  2069. Decimal(4).compare_signal(Decimal(3)))
  2070. self.assertEqual(Decimal(4).compare_total(3),
  2071. Decimal(4).compare_total(Decimal(3)))
  2072. self.assertEqual(Decimal(4).compare_total_mag(3),
  2073. Decimal(4).compare_total_mag(Decimal(3)))
  2074. self.assertEqual(Decimal(10101).logical_and(1001),
  2075. Decimal(10101).logical_and(Decimal(1001)))
  2076. self.assertEqual(Decimal(10101).logical_or(1001),
  2077. Decimal(10101).logical_or(Decimal(1001)))
  2078. self.assertEqual(Decimal(10101).logical_xor(1001),
  2079. Decimal(10101).logical_xor(Decimal(1001)))
  2080. self.assertEqual(Decimal(567).max(123),
  2081. Decimal(567).max(Decimal(123)))
  2082. self.assertEqual(Decimal(567).max_mag(123),
  2083. Decimal(567).max_mag(Decimal(123)))
  2084. self.assertEqual(Decimal(567).min(123),
  2085. Decimal(567).min(Decimal(123)))
  2086. self.assertEqual(Decimal(567).min_mag(123),
  2087. Decimal(567).min_mag(Decimal(123)))
  2088. self.assertEqual(Decimal(567).next_toward(123),
  2089. Decimal(567).next_toward(Decimal(123)))
  2090. self.assertEqual(Decimal(1234).quantize(100),
  2091. Decimal(1234).quantize(Decimal(100)))
  2092. self.assertEqual(Decimal(768).remainder_near(1234),
  2093. Decimal(768).remainder_near(Decimal(1234)))
  2094. self.assertEqual(Decimal(123).rotate(1),
  2095. Decimal(123).rotate(Decimal(1)))
  2096. self.assertEqual(Decimal(1234).same_quantum(1000),
  2097. Decimal(1234).same_quantum(Decimal(1000)))
  2098. self.assertEqual(Decimal('9.123').scaleb(-100),
  2099. Decimal('9.123').scaleb(Decimal(-100)))
  2100. self.assertEqual(Decimal(456).shift(-1),
  2101. Decimal(456).shift(Decimal(-1)))
  2102. self.assertEqual(Decimal(-12).fma(Decimal(45), 67),
  2103. Decimal(-12).fma(Decimal(45), Decimal(67)))
  2104. self.assertEqual(Decimal(-12).fma(45, 67),
  2105. Decimal(-12).fma(Decimal(45), Decimal(67)))
  2106. self.assertEqual(Decimal(-12).fma(45, Decimal(67)),
  2107. Decimal(-12).fma(Decimal(45), Decimal(67)))
  2108. class CUsabilityTest(UsabilityTest):
  2109. decimal = C
  2110. class PyUsabilityTest(UsabilityTest):
  2111. decimal = P
  2112. def setUp(self):
  2113. super().setUp()
  2114. self._previous_int_limit = sys.get_int_max_str_digits()
  2115. sys.set_int_max_str_digits(7000)
  2116. def tearDown(self):
  2117. sys.set_int_max_str_digits(self._previous_int_limit)
  2118. super().tearDown()
  2119. class PythonAPItests(unittest.TestCase):
  2120. def test_abc(self):
  2121. Decimal = self.decimal.Decimal
  2122. self.assertTrue(issubclass(Decimal, numbers.Number))
  2123. self.assertFalse(issubclass(Decimal, numbers.Real))
  2124. self.assertIsInstance(Decimal(0), numbers.Number)
  2125. self.assertNotIsInstance(Decimal(0), numbers.Real)
  2126. def test_pickle(self):
  2127. for proto in range(pickle.HIGHEST_PROTOCOL + 1):
  2128. Decimal = self.decimal.Decimal
  2129. savedecimal = sys.modules['decimal']
  2130. # Round trip
  2131. sys.modules['decimal'] = self.decimal
  2132. d = Decimal('-3.141590000')
  2133. p = pickle.dumps(d, proto)
  2134. e = pickle.loads(p)
  2135. self.assertEqual(d, e)
  2136. if C:
  2137. # Test interchangeability
  2138. x = C.Decimal('-3.123e81723')
  2139. y = P.Decimal('-3.123e81723')
  2140. sys.modules['decimal'] = C
  2141. sx = pickle.dumps(x, proto)
  2142. sys.modules['decimal'] = P
  2143. r = pickle.loads(sx)
  2144. self.assertIsInstance(r, P.Decimal)
  2145. self.assertEqual(r, y)
  2146. sys.modules['decimal'] = P
  2147. sy = pickle.dumps(y, proto)
  2148. sys.modules['decimal'] = C
  2149. r = pickle.loads(sy)
  2150. self.assertIsInstance(r, C.Decimal)
  2151. self.assertEqual(r, x)
  2152. x = C.Decimal('-3.123e81723').as_tuple()
  2153. y = P.Decimal('-3.123e81723').as_tuple()
  2154. sys.modules['decimal'] = C
  2155. sx = pickle.dumps(x, proto)
  2156. sys.modules['decimal'] = P
  2157. r = pickle.loads(sx)
  2158. self.assertIsInstance(r, P.DecimalTuple)
  2159. self.assertEqual(r, y)
  2160. sys.modules['decimal'] = P
  2161. sy = pickle.dumps(y, proto)
  2162. sys.modules['decimal'] = C
  2163. r = pickle.loads(sy)
  2164. self.assertIsInstance(r, C.DecimalTuple)
  2165. self.assertEqual(r, x)
  2166. sys.modules['decimal'] = savedecimal
  2167. def test_int(self):
  2168. Decimal = self.decimal.Decimal
  2169. for x in range(-250, 250):
  2170. s = '%0.2f' % (x / 100.0)
  2171. # should work the same as for floats
  2172. self.assertEqual(int(Decimal(s)), int(float(s)))
  2173. # should work the same as to_integral in the ROUND_DOWN mode
  2174. d = Decimal(s)
  2175. r = d.to_integral(ROUND_DOWN)
  2176. self.assertEqual(Decimal(int(d)), r)
  2177. self.assertRaises(ValueError, int, Decimal('-nan'))
  2178. self.assertRaises(ValueError, int, Decimal('snan'))
  2179. self.assertRaises(OverflowError, int, Decimal('inf'))
  2180. self.assertRaises(OverflowError, int, Decimal('-inf'))
  2181. @cpython_only
  2182. def test_small_ints(self):
  2183. Decimal = self.decimal.Decimal
  2184. # bpo-46361
  2185. for x in range(-5, 257):
  2186. self.assertIs(int(Decimal(x)), x)
  2187. def test_trunc(self):
  2188. Decimal = self.decimal.Decimal
  2189. for x in range(-250, 250):
  2190. s = '%0.2f' % (x / 100.0)
  2191. # should work the same as for floats
  2192. self.assertEqual(int(Decimal(s)), int(float(s)))
  2193. # should work the same as to_integral in the ROUND_DOWN mode
  2194. d = Decimal(s)
  2195. r = d.to_integral(ROUND_DOWN)
  2196. self.assertEqual(Decimal(math.trunc(d)), r)
  2197. def test_from_float(self):
  2198. Decimal = self.decimal.Decimal
  2199. class MyDecimal(Decimal):
  2200. def __init__(self, _):
  2201. self.x = 'y'
  2202. self.assertTrue(issubclass(MyDecimal, Decimal))
  2203. r = MyDecimal.from_float(0.1)
  2204. self.assertEqual(type(r), MyDecimal)
  2205. self.assertEqual(str(r),
  2206. '0.1000000000000000055511151231257827021181583404541015625')
  2207. self.assertEqual(r.x, 'y')
  2208. bigint = 12345678901234567890123456789
  2209. self.assertEqual(MyDecimal.from_float(bigint), MyDecimal(bigint))
  2210. self.assertTrue(MyDecimal.from_float(float('nan')).is_qnan())
  2211. self.assertTrue(MyDecimal.from_float(float('inf')).is_infinite())
  2212. self.assertTrue(MyDecimal.from_float(float('-inf')).is_infinite())
  2213. self.assertEqual(str(MyDecimal.from_float(float('nan'))),
  2214. str(Decimal('NaN')))
  2215. self.assertEqual(str(MyDecimal.from_float(float('inf'))),
  2216. str(Decimal('Infinity')))
  2217. self.assertEqual(str(MyDecimal.from_float(float('-inf'))),
  2218. str(Decimal('-Infinity')))
  2219. self.assertRaises(TypeError, MyDecimal.from_float, 'abc')
  2220. for i in range(200):
  2221. x = random.expovariate(0.01) * (random.random() * 2.0 - 1.0)
  2222. self.assertEqual(x, float(MyDecimal.from_float(x))) # roundtrip
  2223. def test_create_decimal_from_float(self):
  2224. Decimal = self.decimal.Decimal
  2225. Context = self.decimal.Context
  2226. Inexact = self.decimal.Inexact
  2227. context = Context(prec=5, rounding=ROUND_DOWN)
  2228. self.assertEqual(
  2229. context.create_decimal_from_float(math.pi),
  2230. Decimal('3.1415')
  2231. )
  2232. context = Context(prec=5, rounding=ROUND_UP)
  2233. self.assertEqual(
  2234. context.create_decimal_from_float(math.pi),
  2235. Decimal('3.1416')
  2236. )
  2237. context = Context(prec=5, traps=[Inexact])
  2238. self.assertRaises(
  2239. Inexact,
  2240. context.create_decimal_from_float,
  2241. math.pi
  2242. )
  2243. self.assertEqual(repr(context.create_decimal_from_float(-0.0)),
  2244. "Decimal('-0')")
  2245. self.assertEqual(repr(context.create_decimal_from_float(1.0)),
  2246. "Decimal('1')")
  2247. self.assertEqual(repr(context.create_decimal_from_float(10)),
  2248. "Decimal('10')")
  2249. def test_quantize(self):
  2250. Decimal = self.decimal.Decimal
  2251. Context = self.decimal.Context
  2252. InvalidOperation = self.decimal.InvalidOperation
  2253. c = Context(Emax=99999, Emin=-99999)
  2254. self.assertEqual(
  2255. Decimal('7.335').quantize(Decimal('.01')),
  2256. Decimal('7.34')
  2257. )
  2258. self.assertEqual(
  2259. Decimal('7.335').quantize(Decimal('.01'), rounding=ROUND_DOWN),
  2260. Decimal('7.33')
  2261. )
  2262. self.assertRaises(
  2263. InvalidOperation,
  2264. Decimal("10e99999").quantize, Decimal('1e100000'), context=c
  2265. )
  2266. c = Context()
  2267. d = Decimal("0.871831e800")
  2268. x = d.quantize(context=c, exp=Decimal("1e797"), rounding=ROUND_DOWN)
  2269. self.assertEqual(x, Decimal('8.71E+799'))
  2270. def test_complex(self):
  2271. Decimal = self.decimal.Decimal
  2272. x = Decimal("9.8182731e181273")
  2273. self.assertEqual(x.real, x)
  2274. self.assertEqual(x.imag, 0)
  2275. self.assertEqual(x.conjugate(), x)
  2276. x = Decimal("1")
  2277. self.assertEqual(complex(x), complex(float(1)))
  2278. self.assertRaises(AttributeError, setattr, x, 'real', 100)
  2279. self.assertRaises(AttributeError, setattr, x, 'imag', 100)
  2280. self.assertRaises(AttributeError, setattr, x, 'conjugate', 100)
  2281. self.assertRaises(AttributeError, setattr, x, '__complex__', 100)
  2282. def test_named_parameters(self):
  2283. D = self.decimal.Decimal
  2284. Context = self.decimal.Context
  2285. localcontext = self.decimal.localcontext
  2286. InvalidOperation = self.decimal.InvalidOperation
  2287. Overflow = self.decimal.Overflow
  2288. xc = Context()
  2289. xc.prec = 1
  2290. xc.Emax = 1
  2291. xc.Emin = -1
  2292. with localcontext() as c:
  2293. c.clear_flags()
  2294. self.assertEqual(D(9, xc), 9)
  2295. self.assertEqual(D(9, context=xc), 9)
  2296. self.assertEqual(D(context=xc, value=9), 9)
  2297. self.assertEqual(D(context=xc), 0)
  2298. xc.clear_flags()
  2299. self.assertRaises(InvalidOperation, D, "xyz", context=xc)
  2300. self.assertTrue(xc.flags[InvalidOperation])
  2301. self.assertFalse(c.flags[InvalidOperation])
  2302. xc.clear_flags()
  2303. self.assertEqual(D(2).exp(context=xc), 7)
  2304. self.assertRaises(Overflow, D(8).exp, context=xc)
  2305. self.assertTrue(xc.flags[Overflow])
  2306. self.assertFalse(c.flags[Overflow])
  2307. xc.clear_flags()
  2308. self.assertEqual(D(2).ln(context=xc), D('0.7'))
  2309. self.assertRaises(InvalidOperation, D(-1).ln, context=xc)
  2310. self.assertTrue(xc.flags[InvalidOperation])
  2311. self.assertFalse(c.flags[InvalidOperation])
  2312. self.assertEqual(D(0).log10(context=xc), D('-inf'))
  2313. self.assertEqual(D(-1).next_minus(context=xc), -2)
  2314. self.assertEqual(D(-1).next_plus(context=xc), D('-0.9'))
  2315. self.assertEqual(D("9.73").normalize(context=xc), D('1E+1'))
  2316. self.assertEqual(D("9999").to_integral(context=xc), 9999)
  2317. self.assertEqual(D("-2000").to_integral_exact(context=xc), -2000)
  2318. self.assertEqual(D("123").to_integral_value(context=xc), 123)
  2319. self.assertEqual(D("0.0625").sqrt(context=xc), D('0.2'))
  2320. self.assertEqual(D("0.0625").compare(context=xc, other=3), -1)
  2321. xc.clear_flags()
  2322. self.assertRaises(InvalidOperation,
  2323. D("0").compare_signal, D('nan'), context=xc)
  2324. self.assertTrue(xc.flags[InvalidOperation])
  2325. self.assertFalse(c.flags[InvalidOperation])
  2326. self.assertEqual(D("0.01").max(D('0.0101'), context=xc), D('0.0'))
  2327. self.assertEqual(D("0.01").max(D('0.0101'), context=xc), D('0.0'))
  2328. self.assertEqual(D("0.2").max_mag(D('-0.3'), context=xc),
  2329. D('-0.3'))
  2330. self.assertEqual(D("0.02").min(D('-0.03'), context=xc), D('-0.0'))
  2331. self.assertEqual(D("0.02").min_mag(D('-0.03'), context=xc),
  2332. D('0.0'))
  2333. self.assertEqual(D("0.2").next_toward(D('-1'), context=xc), D('0.1'))
  2334. xc.clear_flags()
  2335. self.assertRaises(InvalidOperation,
  2336. D("0.2").quantize, D('1e10'), context=xc)
  2337. self.assertTrue(xc.flags[InvalidOperation])
  2338. self.assertFalse(c.flags[InvalidOperation])
  2339. self.assertEqual(D("9.99").remainder_near(D('1.5'), context=xc),
  2340. D('-0.5'))
  2341. self.assertEqual(D("9.9").fma(third=D('0.9'), context=xc, other=7),
  2342. D('7E+1'))
  2343. self.assertRaises(TypeError, D(1).is_canonical, context=xc)
  2344. self.assertRaises(TypeError, D(1).is_finite, context=xc)
  2345. self.assertRaises(TypeError, D(1).is_infinite, context=xc)
  2346. self.assertRaises(TypeError, D(1).is_nan, context=xc)
  2347. self.assertRaises(TypeError, D(1).is_qnan, context=xc)
  2348. self.assertRaises(TypeError, D(1).is_snan, context=xc)
  2349. self.assertRaises(TypeError, D(1).is_signed, context=xc)
  2350. self.assertRaises(TypeError, D(1).is_zero, context=xc)
  2351. self.assertFalse(D("0.01").is_normal(context=xc))
  2352. self.assertTrue(D("0.01").is_subnormal(context=xc))
  2353. self.assertRaises(TypeError, D(1).adjusted, context=xc)
  2354. self.assertRaises(TypeError, D(1).conjugate, context=xc)
  2355. self.assertRaises(TypeError, D(1).radix, context=xc)
  2356. self.assertEqual(D(-111).logb(context=xc), 2)
  2357. self.assertEqual(D(0).logical_invert(context=xc), 1)
  2358. self.assertEqual(D('0.01').number_class(context=xc), '+Subnormal')
  2359. self.assertEqual(D('0.21').to_eng_string(context=xc), '0.21')
  2360. self.assertEqual(D('11').logical_and(D('10'), context=xc), 0)
  2361. self.assertEqual(D('11').logical_or(D('10'), context=xc), 1)
  2362. self.assertEqual(D('01').logical_xor(D('10'), context=xc), 1)
  2363. self.assertEqual(D('23').rotate(1, context=xc), 3)
  2364. self.assertEqual(D('23').rotate(1, context=xc), 3)
  2365. xc.clear_flags()
  2366. self.assertRaises(Overflow,
  2367. D('23').scaleb, 1, context=xc)
  2368. self.assertTrue(xc.flags[Overflow])
  2369. self.assertFalse(c.flags[Overflow])
  2370. self.assertEqual(D('23').shift(-1, context=xc), 0)
  2371. self.assertRaises(TypeError, D.from_float, 1.1, context=xc)
  2372. self.assertRaises(TypeError, D(0).as_tuple, context=xc)
  2373. self.assertEqual(D(1).canonical(), 1)
  2374. self.assertRaises(TypeError, D("-1").copy_abs, context=xc)
  2375. self.assertRaises(TypeError, D("-1").copy_negate, context=xc)
  2376. self.assertRaises(TypeError, D(1).canonical, context="x")
  2377. self.assertRaises(TypeError, D(1).canonical, xyz="x")
  2378. def test_exception_hierarchy(self):
  2379. decimal = self.decimal
  2380. DecimalException = decimal.DecimalException
  2381. InvalidOperation = decimal.InvalidOperation
  2382. FloatOperation = decimal.FloatOperation
  2383. DivisionByZero = decimal.DivisionByZero
  2384. Overflow = decimal.Overflow
  2385. Underflow = decimal.Underflow
  2386. Subnormal = decimal.Subnormal
  2387. Inexact = decimal.Inexact
  2388. Rounded = decimal.Rounded
  2389. Clamped = decimal.Clamped
  2390. self.assertTrue(issubclass(DecimalException, ArithmeticError))
  2391. self.assertTrue(issubclass(InvalidOperation, DecimalException))
  2392. self.assertTrue(issubclass(FloatOperation, DecimalException))
  2393. self.assertTrue(issubclass(FloatOperation, TypeError))
  2394. self.assertTrue(issubclass(DivisionByZero, DecimalException))
  2395. self.assertTrue(issubclass(DivisionByZero, ZeroDivisionError))
  2396. self.assertTrue(issubclass(Overflow, Rounded))
  2397. self.assertTrue(issubclass(Overflow, Inexact))
  2398. self.assertTrue(issubclass(Overflow, DecimalException))
  2399. self.assertTrue(issubclass(Underflow, Inexact))
  2400. self.assertTrue(issubclass(Underflow, Rounded))
  2401. self.assertTrue(issubclass(Underflow, Subnormal))
  2402. self.assertTrue(issubclass(Underflow, DecimalException))
  2403. self.assertTrue(issubclass(Subnormal, DecimalException))
  2404. self.assertTrue(issubclass(Inexact, DecimalException))
  2405. self.assertTrue(issubclass(Rounded, DecimalException))
  2406. self.assertTrue(issubclass(Clamped, DecimalException))
  2407. self.assertTrue(issubclass(decimal.ConversionSyntax, InvalidOperation))
  2408. self.assertTrue(issubclass(decimal.DivisionImpossible, InvalidOperation))
  2409. self.assertTrue(issubclass(decimal.DivisionUndefined, InvalidOperation))
  2410. self.assertTrue(issubclass(decimal.DivisionUndefined, ZeroDivisionError))
  2411. self.assertTrue(issubclass(decimal.InvalidContext, InvalidOperation))
  2412. class CPythonAPItests(PythonAPItests):
  2413. decimal = C
  2414. class PyPythonAPItests(PythonAPItests):
  2415. decimal = P
  2416. class ContextAPItests(unittest.TestCase):
  2417. def test_none_args(self):
  2418. Context = self.decimal.Context
  2419. InvalidOperation = self.decimal.InvalidOperation
  2420. DivisionByZero = self.decimal.DivisionByZero
  2421. Overflow = self.decimal.Overflow
  2422. c1 = Context()
  2423. c2 = Context(prec=None, rounding=None, Emax=None, Emin=None,
  2424. capitals=None, clamp=None, flags=None, traps=None)
  2425. for c in [c1, c2]:
  2426. self.assertEqual(c.prec, 28)
  2427. self.assertEqual(c.rounding, ROUND_HALF_EVEN)
  2428. self.assertEqual(c.Emax, 999999)
  2429. self.assertEqual(c.Emin, -999999)
  2430. self.assertEqual(c.capitals, 1)
  2431. self.assertEqual(c.clamp, 0)
  2432. assert_signals(self, c, 'flags', [])
  2433. assert_signals(self, c, 'traps', [InvalidOperation, DivisionByZero,
  2434. Overflow])
  2435. @cpython_only
  2436. @requires_legacy_unicode_capi
  2437. @warnings_helper.ignore_warnings(category=DeprecationWarning)
  2438. def test_from_legacy_strings(self):
  2439. import _testcapi
  2440. c = self.decimal.Context()
  2441. for rnd in RoundingModes:
  2442. c.rounding = _testcapi.unicode_legacy_string(rnd)
  2443. self.assertEqual(c.rounding, rnd)
  2444. s = _testcapi.unicode_legacy_string('')
  2445. self.assertRaises(TypeError, setattr, c, 'rounding', s)
  2446. s = _testcapi.unicode_legacy_string('ROUND_\x00UP')
  2447. self.assertRaises(TypeError, setattr, c, 'rounding', s)
  2448. def test_pickle(self):
  2449. for proto in range(pickle.HIGHEST_PROTOCOL + 1):
  2450. Context = self.decimal.Context
  2451. savedecimal = sys.modules['decimal']
  2452. # Round trip
  2453. sys.modules['decimal'] = self.decimal
  2454. c = Context()
  2455. e = pickle.loads(pickle.dumps(c, proto))
  2456. self.assertEqual(c.prec, e.prec)
  2457. self.assertEqual(c.Emin, e.Emin)
  2458. self.assertEqual(c.Emax, e.Emax)
  2459. self.assertEqual(c.rounding, e.rounding)
  2460. self.assertEqual(c.capitals, e.capitals)
  2461. self.assertEqual(c.clamp, e.clamp)
  2462. self.assertEqual(c.flags, e.flags)
  2463. self.assertEqual(c.traps, e.traps)
  2464. # Test interchangeability
  2465. combinations = [(C, P), (P, C)] if C else [(P, P)]
  2466. for dumper, loader in combinations:
  2467. for ri, _ in enumerate(RoundingModes):
  2468. for fi, _ in enumerate(OrderedSignals[dumper]):
  2469. for ti, _ in enumerate(OrderedSignals[dumper]):
  2470. prec = random.randrange(1, 100)
  2471. emin = random.randrange(-100, 0)
  2472. emax = random.randrange(1, 100)
  2473. caps = random.randrange(2)
  2474. clamp = random.randrange(2)
  2475. # One module dumps
  2476. sys.modules['decimal'] = dumper
  2477. c = dumper.Context(
  2478. prec=prec, Emin=emin, Emax=emax,
  2479. rounding=RoundingModes[ri],
  2480. capitals=caps, clamp=clamp,
  2481. flags=OrderedSignals[dumper][:fi],
  2482. traps=OrderedSignals[dumper][:ti]
  2483. )
  2484. s = pickle.dumps(c, proto)
  2485. # The other module loads
  2486. sys.modules['decimal'] = loader
  2487. d = pickle.loads(s)
  2488. self.assertIsInstance(d, loader.Context)
  2489. self.assertEqual(d.prec, prec)
  2490. self.assertEqual(d.Emin, emin)
  2491. self.assertEqual(d.Emax, emax)
  2492. self.assertEqual(d.rounding, RoundingModes[ri])
  2493. self.assertEqual(d.capitals, caps)
  2494. self.assertEqual(d.clamp, clamp)
  2495. assert_signals(self, d, 'flags', OrderedSignals[loader][:fi])
  2496. assert_signals(self, d, 'traps', OrderedSignals[loader][:ti])
  2497. sys.modules['decimal'] = savedecimal
  2498. def test_equality_with_other_types(self):
  2499. Decimal = self.decimal.Decimal
  2500. self.assertIn(Decimal(10), ['a', 1.0, Decimal(10), (1,2), {}])
  2501. self.assertNotIn(Decimal(10), ['a', 1.0, (1,2), {}])
  2502. def test_copy(self):
  2503. # All copies should be deep
  2504. Decimal = self.decimal.Decimal
  2505. Context = self.decimal.Context
  2506. c = Context()
  2507. d = c.copy()
  2508. self.assertNotEqual(id(c), id(d))
  2509. self.assertNotEqual(id(c.flags), id(d.flags))
  2510. self.assertNotEqual(id(c.traps), id(d.traps))
  2511. k1 = set(c.flags.keys())
  2512. k2 = set(d.flags.keys())
  2513. self.assertEqual(k1, k2)
  2514. self.assertEqual(c.flags, d.flags)
  2515. def test__clamp(self):
  2516. # In Python 3.2, the private attribute `_clamp` was made
  2517. # public (issue 8540), with the old `_clamp` becoming a
  2518. # property wrapping `clamp`. For the duration of Python 3.2
  2519. # only, the attribute should be gettable/settable via both
  2520. # `clamp` and `_clamp`; in Python 3.3, `_clamp` should be
  2521. # removed.
  2522. Context = self.decimal.Context
  2523. c = Context()
  2524. self.assertRaises(AttributeError, getattr, c, '_clamp')
  2525. def test_abs(self):
  2526. Decimal = self.decimal.Decimal
  2527. Context = self.decimal.Context
  2528. c = Context()
  2529. d = c.abs(Decimal(-1))
  2530. self.assertEqual(c.abs(-1), d)
  2531. self.assertRaises(TypeError, c.abs, '-1')
  2532. def test_add(self):
  2533. Decimal = self.decimal.Decimal
  2534. Context = self.decimal.Context
  2535. c = Context()
  2536. d = c.add(Decimal(1), Decimal(1))
  2537. self.assertEqual(c.add(1, 1), d)
  2538. self.assertEqual(c.add(Decimal(1), 1), d)
  2539. self.assertEqual(c.add(1, Decimal(1)), d)
  2540. self.assertRaises(TypeError, c.add, '1', 1)
  2541. self.assertRaises(TypeError, c.add, 1, '1')
  2542. def test_compare(self):
  2543. Decimal = self.decimal.Decimal
  2544. Context = self.decimal.Context
  2545. c = Context()
  2546. d = c.compare(Decimal(1), Decimal(1))
  2547. self.assertEqual(c.compare(1, 1), d)
  2548. self.assertEqual(c.compare(Decimal(1), 1), d)
  2549. self.assertEqual(c.compare(1, Decimal(1)), d)
  2550. self.assertRaises(TypeError, c.compare, '1', 1)
  2551. self.assertRaises(TypeError, c.compare, 1, '1')
  2552. def test_compare_signal(self):
  2553. Decimal = self.decimal.Decimal
  2554. Context = self.decimal.Context
  2555. c = Context()
  2556. d = c.compare_signal(Decimal(1), Decimal(1))
  2557. self.assertEqual(c.compare_signal(1, 1), d)
  2558. self.assertEqual(c.compare_signal(Decimal(1), 1), d)
  2559. self.assertEqual(c.compare_signal(1, Decimal(1)), d)
  2560. self.assertRaises(TypeError, c.compare_signal, '1', 1)
  2561. self.assertRaises(TypeError, c.compare_signal, 1, '1')
  2562. def test_compare_total(self):
  2563. Decimal = self.decimal.Decimal
  2564. Context = self.decimal.Context
  2565. c = Context()
  2566. d = c.compare_total(Decimal(1), Decimal(1))
  2567. self.assertEqual(c.compare_total(1, 1), d)
  2568. self.assertEqual(c.compare_total(Decimal(1), 1), d)
  2569. self.assertEqual(c.compare_total(1, Decimal(1)), d)
  2570. self.assertRaises(TypeError, c.compare_total, '1', 1)
  2571. self.assertRaises(TypeError, c.compare_total, 1, '1')
  2572. def test_compare_total_mag(self):
  2573. Decimal = self.decimal.Decimal
  2574. Context = self.decimal.Context
  2575. c = Context()
  2576. d = c.compare_total_mag(Decimal(1), Decimal(1))
  2577. self.assertEqual(c.compare_total_mag(1, 1), d)
  2578. self.assertEqual(c.compare_total_mag(Decimal(1), 1), d)
  2579. self.assertEqual(c.compare_total_mag(1, Decimal(1)), d)
  2580. self.assertRaises(TypeError, c.compare_total_mag, '1', 1)
  2581. self.assertRaises(TypeError, c.compare_total_mag, 1, '1')
  2582. def test_copy_abs(self):
  2583. Decimal = self.decimal.Decimal
  2584. Context = self.decimal.Context
  2585. c = Context()
  2586. d = c.copy_abs(Decimal(-1))
  2587. self.assertEqual(c.copy_abs(-1), d)
  2588. self.assertRaises(TypeError, c.copy_abs, '-1')
  2589. def test_copy_decimal(self):
  2590. Decimal = self.decimal.Decimal
  2591. Context = self.decimal.Context
  2592. c = Context()
  2593. d = c.copy_decimal(Decimal(-1))
  2594. self.assertEqual(c.copy_decimal(-1), d)
  2595. self.assertRaises(TypeError, c.copy_decimal, '-1')
  2596. def test_copy_negate(self):
  2597. Decimal = self.decimal.Decimal
  2598. Context = self.decimal.Context
  2599. c = Context()
  2600. d = c.copy_negate(Decimal(-1))
  2601. self.assertEqual(c.copy_negate(-1), d)
  2602. self.assertRaises(TypeError, c.copy_negate, '-1')
  2603. def test_copy_sign(self):
  2604. Decimal = self.decimal.Decimal
  2605. Context = self.decimal.Context
  2606. c = Context()
  2607. d = c.copy_sign(Decimal(1), Decimal(-2))
  2608. self.assertEqual(c.copy_sign(1, -2), d)
  2609. self.assertEqual(c.copy_sign(Decimal(1), -2), d)
  2610. self.assertEqual(c.copy_sign(1, Decimal(-2)), d)
  2611. self.assertRaises(TypeError, c.copy_sign, '1', -2)
  2612. self.assertRaises(TypeError, c.copy_sign, 1, '-2')
  2613. def test_divide(self):
  2614. Decimal = self.decimal.Decimal
  2615. Context = self.decimal.Context
  2616. c = Context()
  2617. d = c.divide(Decimal(1), Decimal(2))
  2618. self.assertEqual(c.divide(1, 2), d)
  2619. self.assertEqual(c.divide(Decimal(1), 2), d)
  2620. self.assertEqual(c.divide(1, Decimal(2)), d)
  2621. self.assertRaises(TypeError, c.divide, '1', 2)
  2622. self.assertRaises(TypeError, c.divide, 1, '2')
  2623. def test_divide_int(self):
  2624. Decimal = self.decimal.Decimal
  2625. Context = self.decimal.Context
  2626. c = Context()
  2627. d = c.divide_int(Decimal(1), Decimal(2))
  2628. self.assertEqual(c.divide_int(1, 2), d)
  2629. self.assertEqual(c.divide_int(Decimal(1), 2), d)
  2630. self.assertEqual(c.divide_int(1, Decimal(2)), d)
  2631. self.assertRaises(TypeError, c.divide_int, '1', 2)
  2632. self.assertRaises(TypeError, c.divide_int, 1, '2')
  2633. def test_divmod(self):
  2634. Decimal = self.decimal.Decimal
  2635. Context = self.decimal.Context
  2636. c = Context()
  2637. d = c.divmod(Decimal(1), Decimal(2))
  2638. self.assertEqual(c.divmod(1, 2), d)
  2639. self.assertEqual(c.divmod(Decimal(1), 2), d)
  2640. self.assertEqual(c.divmod(1, Decimal(2)), d)
  2641. self.assertRaises(TypeError, c.divmod, '1', 2)
  2642. self.assertRaises(TypeError, c.divmod, 1, '2')
  2643. def test_exp(self):
  2644. Decimal = self.decimal.Decimal
  2645. Context = self.decimal.Context
  2646. c = Context()
  2647. d = c.exp(Decimal(10))
  2648. self.assertEqual(c.exp(10), d)
  2649. self.assertRaises(TypeError, c.exp, '10')
  2650. def test_fma(self):
  2651. Decimal = self.decimal.Decimal
  2652. Context = self.decimal.Context
  2653. c = Context()
  2654. d = c.fma(Decimal(2), Decimal(3), Decimal(4))
  2655. self.assertEqual(c.fma(2, 3, 4), d)
  2656. self.assertEqual(c.fma(Decimal(2), 3, 4), d)
  2657. self.assertEqual(c.fma(2, Decimal(3), 4), d)
  2658. self.assertEqual(c.fma(2, 3, Decimal(4)), d)
  2659. self.assertEqual(c.fma(Decimal(2), Decimal(3), 4), d)
  2660. self.assertRaises(TypeError, c.fma, '2', 3, 4)
  2661. self.assertRaises(TypeError, c.fma, 2, '3', 4)
  2662. self.assertRaises(TypeError, c.fma, 2, 3, '4')
  2663. # Issue 12079 for Context.fma ...
  2664. self.assertRaises(TypeError, c.fma,
  2665. Decimal('Infinity'), Decimal(0), "not a decimal")
  2666. self.assertRaises(TypeError, c.fma,
  2667. Decimal(1), Decimal('snan'), 1.222)
  2668. # ... and for Decimal.fma.
  2669. self.assertRaises(TypeError, Decimal('Infinity').fma,
  2670. Decimal(0), "not a decimal")
  2671. self.assertRaises(TypeError, Decimal(1).fma,
  2672. Decimal('snan'), 1.222)
  2673. def test_is_finite(self):
  2674. Decimal = self.decimal.Decimal
  2675. Context = self.decimal.Context
  2676. c = Context()
  2677. d = c.is_finite(Decimal(10))
  2678. self.assertEqual(c.is_finite(10), d)
  2679. self.assertRaises(TypeError, c.is_finite, '10')
  2680. def test_is_infinite(self):
  2681. Decimal = self.decimal.Decimal
  2682. Context = self.decimal.Context
  2683. c = Context()
  2684. d = c.is_infinite(Decimal(10))
  2685. self.assertEqual(c.is_infinite(10), d)
  2686. self.assertRaises(TypeError, c.is_infinite, '10')
  2687. def test_is_nan(self):
  2688. Decimal = self.decimal.Decimal
  2689. Context = self.decimal.Context
  2690. c = Context()
  2691. d = c.is_nan(Decimal(10))
  2692. self.assertEqual(c.is_nan(10), d)
  2693. self.assertRaises(TypeError, c.is_nan, '10')
  2694. def test_is_normal(self):
  2695. Decimal = self.decimal.Decimal
  2696. Context = self.decimal.Context
  2697. c = Context()
  2698. d = c.is_normal(Decimal(10))
  2699. self.assertEqual(c.is_normal(10), d)
  2700. self.assertRaises(TypeError, c.is_normal, '10')
  2701. def test_is_qnan(self):
  2702. Decimal = self.decimal.Decimal
  2703. Context = self.decimal.Context
  2704. c = Context()
  2705. d = c.is_qnan(Decimal(10))
  2706. self.assertEqual(c.is_qnan(10), d)
  2707. self.assertRaises(TypeError, c.is_qnan, '10')
  2708. def test_is_signed(self):
  2709. Decimal = self.decimal.Decimal
  2710. Context = self.decimal.Context
  2711. c = Context()
  2712. d = c.is_signed(Decimal(10))
  2713. self.assertEqual(c.is_signed(10), d)
  2714. self.assertRaises(TypeError, c.is_signed, '10')
  2715. def test_is_snan(self):
  2716. Decimal = self.decimal.Decimal
  2717. Context = self.decimal.Context
  2718. c = Context()
  2719. d = c.is_snan(Decimal(10))
  2720. self.assertEqual(c.is_snan(10), d)
  2721. self.assertRaises(TypeError, c.is_snan, '10')
  2722. def test_is_subnormal(self):
  2723. Decimal = self.decimal.Decimal
  2724. Context = self.decimal.Context
  2725. c = Context()
  2726. d = c.is_subnormal(Decimal(10))
  2727. self.assertEqual(c.is_subnormal(10), d)
  2728. self.assertRaises(TypeError, c.is_subnormal, '10')
  2729. def test_is_zero(self):
  2730. Decimal = self.decimal.Decimal
  2731. Context = self.decimal.Context
  2732. c = Context()
  2733. d = c.is_zero(Decimal(10))
  2734. self.assertEqual(c.is_zero(10), d)
  2735. self.assertRaises(TypeError, c.is_zero, '10')
  2736. def test_ln(self):
  2737. Decimal = self.decimal.Decimal
  2738. Context = self.decimal.Context
  2739. c = Context()
  2740. d = c.ln(Decimal(10))
  2741. self.assertEqual(c.ln(10), d)
  2742. self.assertRaises(TypeError, c.ln, '10')
  2743. def test_log10(self):
  2744. Decimal = self.decimal.Decimal
  2745. Context = self.decimal.Context
  2746. c = Context()
  2747. d = c.log10(Decimal(10))
  2748. self.assertEqual(c.log10(10), d)
  2749. self.assertRaises(TypeError, c.log10, '10')
  2750. def test_logb(self):
  2751. Decimal = self.decimal.Decimal
  2752. Context = self.decimal.Context
  2753. c = Context()
  2754. d = c.logb(Decimal(10))
  2755. self.assertEqual(c.logb(10), d)
  2756. self.assertRaises(TypeError, c.logb, '10')
  2757. def test_logical_and(self):
  2758. Decimal = self.decimal.Decimal
  2759. Context = self.decimal.Context
  2760. c = Context()
  2761. d = c.logical_and(Decimal(1), Decimal(1))
  2762. self.assertEqual(c.logical_and(1, 1), d)
  2763. self.assertEqual(c.logical_and(Decimal(1), 1), d)
  2764. self.assertEqual(c.logical_and(1, Decimal(1)), d)
  2765. self.assertRaises(TypeError, c.logical_and, '1', 1)
  2766. self.assertRaises(TypeError, c.logical_and, 1, '1')
  2767. def test_logical_invert(self):
  2768. Decimal = self.decimal.Decimal
  2769. Context = self.decimal.Context
  2770. c = Context()
  2771. d = c.logical_invert(Decimal(1000))
  2772. self.assertEqual(c.logical_invert(1000), d)
  2773. self.assertRaises(TypeError, c.logical_invert, '1000')
  2774. def test_logical_or(self):
  2775. Decimal = self.decimal.Decimal
  2776. Context = self.decimal.Context
  2777. c = Context()
  2778. d = c.logical_or(Decimal(1), Decimal(1))
  2779. self.assertEqual(c.logical_or(1, 1), d)
  2780. self.assertEqual(c.logical_or(Decimal(1), 1), d)
  2781. self.assertEqual(c.logical_or(1, Decimal(1)), d)
  2782. self.assertRaises(TypeError, c.logical_or, '1', 1)
  2783. self.assertRaises(TypeError, c.logical_or, 1, '1')
  2784. def test_logical_xor(self):
  2785. Decimal = self.decimal.Decimal
  2786. Context = self.decimal.Context
  2787. c = Context()
  2788. d = c.logical_xor(Decimal(1), Decimal(1))
  2789. self.assertEqual(c.logical_xor(1, 1), d)
  2790. self.assertEqual(c.logical_xor(Decimal(1), 1), d)
  2791. self.assertEqual(c.logical_xor(1, Decimal(1)), d)
  2792. self.assertRaises(TypeError, c.logical_xor, '1', 1)
  2793. self.assertRaises(TypeError, c.logical_xor, 1, '1')
  2794. def test_max(self):
  2795. Decimal = self.decimal.Decimal
  2796. Context = self.decimal.Context
  2797. c = Context()
  2798. d = c.max(Decimal(1), Decimal(2))
  2799. self.assertEqual(c.max(1, 2), d)
  2800. self.assertEqual(c.max(Decimal(1), 2), d)
  2801. self.assertEqual(c.max(1, Decimal(2)), d)
  2802. self.assertRaises(TypeError, c.max, '1', 2)
  2803. self.assertRaises(TypeError, c.max, 1, '2')
  2804. def test_max_mag(self):
  2805. Decimal = self.decimal.Decimal
  2806. Context = self.decimal.Context
  2807. c = Context()
  2808. d = c.max_mag(Decimal(1), Decimal(2))
  2809. self.assertEqual(c.max_mag(1, 2), d)
  2810. self.assertEqual(c.max_mag(Decimal(1), 2), d)
  2811. self.assertEqual(c.max_mag(1, Decimal(2)), d)
  2812. self.assertRaises(TypeError, c.max_mag, '1', 2)
  2813. self.assertRaises(TypeError, c.max_mag, 1, '2')
  2814. def test_min(self):
  2815. Decimal = self.decimal.Decimal
  2816. Context = self.decimal.Context
  2817. c = Context()
  2818. d = c.min(Decimal(1), Decimal(2))
  2819. self.assertEqual(c.min(1, 2), d)
  2820. self.assertEqual(c.min(Decimal(1), 2), d)
  2821. self.assertEqual(c.min(1, Decimal(2)), d)
  2822. self.assertRaises(TypeError, c.min, '1', 2)
  2823. self.assertRaises(TypeError, c.min, 1, '2')
  2824. def test_min_mag(self):
  2825. Decimal = self.decimal.Decimal
  2826. Context = self.decimal.Context
  2827. c = Context()
  2828. d = c.min_mag(Decimal(1), Decimal(2))
  2829. self.assertEqual(c.min_mag(1, 2), d)
  2830. self.assertEqual(c.min_mag(Decimal(1), 2), d)
  2831. self.assertEqual(c.min_mag(1, Decimal(2)), d)
  2832. self.assertRaises(TypeError, c.min_mag, '1', 2)
  2833. self.assertRaises(TypeError, c.min_mag, 1, '2')
  2834. def test_minus(self):
  2835. Decimal = self.decimal.Decimal
  2836. Context = self.decimal.Context
  2837. c = Context()
  2838. d = c.minus(Decimal(10))
  2839. self.assertEqual(c.minus(10), d)
  2840. self.assertRaises(TypeError, c.minus, '10')
  2841. def test_multiply(self):
  2842. Decimal = self.decimal.Decimal
  2843. Context = self.decimal.Context
  2844. c = Context()
  2845. d = c.multiply(Decimal(1), Decimal(2))
  2846. self.assertEqual(c.multiply(1, 2), d)
  2847. self.assertEqual(c.multiply(Decimal(1), 2), d)
  2848. self.assertEqual(c.multiply(1, Decimal(2)), d)
  2849. self.assertRaises(TypeError, c.multiply, '1', 2)
  2850. self.assertRaises(TypeError, c.multiply, 1, '2')
  2851. def test_next_minus(self):
  2852. Decimal = self.decimal.Decimal
  2853. Context = self.decimal.Context
  2854. c = Context()
  2855. d = c.next_minus(Decimal(10))
  2856. self.assertEqual(c.next_minus(10), d)
  2857. self.assertRaises(TypeError, c.next_minus, '10')
  2858. def test_next_plus(self):
  2859. Decimal = self.decimal.Decimal
  2860. Context = self.decimal.Context
  2861. c = Context()
  2862. d = c.next_plus(Decimal(10))
  2863. self.assertEqual(c.next_plus(10), d)
  2864. self.assertRaises(TypeError, c.next_plus, '10')
  2865. def test_next_toward(self):
  2866. Decimal = self.decimal.Decimal
  2867. Context = self.decimal.Context
  2868. c = Context()
  2869. d = c.next_toward(Decimal(1), Decimal(2))
  2870. self.assertEqual(c.next_toward(1, 2), d)
  2871. self.assertEqual(c.next_toward(Decimal(1), 2), d)
  2872. self.assertEqual(c.next_toward(1, Decimal(2)), d)
  2873. self.assertRaises(TypeError, c.next_toward, '1', 2)
  2874. self.assertRaises(TypeError, c.next_toward, 1, '2')
  2875. def test_normalize(self):
  2876. Decimal = self.decimal.Decimal
  2877. Context = self.decimal.Context
  2878. c = Context()
  2879. d = c.normalize(Decimal(10))
  2880. self.assertEqual(c.normalize(10), d)
  2881. self.assertRaises(TypeError, c.normalize, '10')
  2882. def test_number_class(self):
  2883. Decimal = self.decimal.Decimal
  2884. Context = self.decimal.Context
  2885. c = Context()
  2886. self.assertEqual(c.number_class(123), c.number_class(Decimal(123)))
  2887. self.assertEqual(c.number_class(0), c.number_class(Decimal(0)))
  2888. self.assertEqual(c.number_class(-45), c.number_class(Decimal(-45)))
  2889. def test_plus(self):
  2890. Decimal = self.decimal.Decimal
  2891. Context = self.decimal.Context
  2892. c = Context()
  2893. d = c.plus(Decimal(10))
  2894. self.assertEqual(c.plus(10), d)
  2895. self.assertRaises(TypeError, c.plus, '10')
  2896. def test_power(self):
  2897. Decimal = self.decimal.Decimal
  2898. Context = self.decimal.Context
  2899. c = Context()
  2900. d = c.power(Decimal(1), Decimal(4))
  2901. self.assertEqual(c.power(1, 4), d)
  2902. self.assertEqual(c.power(Decimal(1), 4), d)
  2903. self.assertEqual(c.power(1, Decimal(4)), d)
  2904. self.assertEqual(c.power(Decimal(1), Decimal(4)), d)
  2905. self.assertRaises(TypeError, c.power, '1', 4)
  2906. self.assertRaises(TypeError, c.power, 1, '4')
  2907. self.assertEqual(c.power(modulo=5, b=8, a=2), 1)
  2908. def test_quantize(self):
  2909. Decimal = self.decimal.Decimal
  2910. Context = self.decimal.Context
  2911. c = Context()
  2912. d = c.quantize(Decimal(1), Decimal(2))
  2913. self.assertEqual(c.quantize(1, 2), d)
  2914. self.assertEqual(c.quantize(Decimal(1), 2), d)
  2915. self.assertEqual(c.quantize(1, Decimal(2)), d)
  2916. self.assertRaises(TypeError, c.quantize, '1', 2)
  2917. self.assertRaises(TypeError, c.quantize, 1, '2')
  2918. def test_remainder(self):
  2919. Decimal = self.decimal.Decimal
  2920. Context = self.decimal.Context
  2921. c = Context()
  2922. d = c.remainder(Decimal(1), Decimal(2))
  2923. self.assertEqual(c.remainder(1, 2), d)
  2924. self.assertEqual(c.remainder(Decimal(1), 2), d)
  2925. self.assertEqual(c.remainder(1, Decimal(2)), d)
  2926. self.assertRaises(TypeError, c.remainder, '1', 2)
  2927. self.assertRaises(TypeError, c.remainder, 1, '2')
  2928. def test_remainder_near(self):
  2929. Decimal = self.decimal.Decimal
  2930. Context = self.decimal.Context
  2931. c = Context()
  2932. d = c.remainder_near(Decimal(1), Decimal(2))
  2933. self.assertEqual(c.remainder_near(1, 2), d)
  2934. self.assertEqual(c.remainder_near(Decimal(1), 2), d)
  2935. self.assertEqual(c.remainder_near(1, Decimal(2)), d)
  2936. self.assertRaises(TypeError, c.remainder_near, '1', 2)
  2937. self.assertRaises(TypeError, c.remainder_near, 1, '2')
  2938. def test_rotate(self):
  2939. Decimal = self.decimal.Decimal
  2940. Context = self.decimal.Context
  2941. c = Context()
  2942. d = c.rotate(Decimal(1), Decimal(2))
  2943. self.assertEqual(c.rotate(1, 2), d)
  2944. self.assertEqual(c.rotate(Decimal(1), 2), d)
  2945. self.assertEqual(c.rotate(1, Decimal(2)), d)
  2946. self.assertRaises(TypeError, c.rotate, '1', 2)
  2947. self.assertRaises(TypeError, c.rotate, 1, '2')
  2948. def test_sqrt(self):
  2949. Decimal = self.decimal.Decimal
  2950. Context = self.decimal.Context
  2951. c = Context()
  2952. d = c.sqrt(Decimal(10))
  2953. self.assertEqual(c.sqrt(10), d)
  2954. self.assertRaises(TypeError, c.sqrt, '10')
  2955. def test_same_quantum(self):
  2956. Decimal = self.decimal.Decimal
  2957. Context = self.decimal.Context
  2958. c = Context()
  2959. d = c.same_quantum(Decimal(1), Decimal(2))
  2960. self.assertEqual(c.same_quantum(1, 2), d)
  2961. self.assertEqual(c.same_quantum(Decimal(1), 2), d)
  2962. self.assertEqual(c.same_quantum(1, Decimal(2)), d)
  2963. self.assertRaises(TypeError, c.same_quantum, '1', 2)
  2964. self.assertRaises(TypeError, c.same_quantum, 1, '2')
  2965. def test_scaleb(self):
  2966. Decimal = self.decimal.Decimal
  2967. Context = self.decimal.Context
  2968. c = Context()
  2969. d = c.scaleb(Decimal(1), Decimal(2))
  2970. self.assertEqual(c.scaleb(1, 2), d)
  2971. self.assertEqual(c.scaleb(Decimal(1), 2), d)
  2972. self.assertEqual(c.scaleb(1, Decimal(2)), d)
  2973. self.assertRaises(TypeError, c.scaleb, '1', 2)
  2974. self.assertRaises(TypeError, c.scaleb, 1, '2')
  2975. def test_shift(self):
  2976. Decimal = self.decimal.Decimal
  2977. Context = self.decimal.Context
  2978. c = Context()
  2979. d = c.shift(Decimal(1), Decimal(2))
  2980. self.assertEqual(c.shift(1, 2), d)
  2981. self.assertEqual(c.shift(Decimal(1), 2), d)
  2982. self.assertEqual(c.shift(1, Decimal(2)), d)
  2983. self.assertRaises(TypeError, c.shift, '1', 2)
  2984. self.assertRaises(TypeError, c.shift, 1, '2')
  2985. def test_subtract(self):
  2986. Decimal = self.decimal.Decimal
  2987. Context = self.decimal.Context
  2988. c = Context()
  2989. d = c.subtract(Decimal(1), Decimal(2))
  2990. self.assertEqual(c.subtract(1, 2), d)
  2991. self.assertEqual(c.subtract(Decimal(1), 2), d)
  2992. self.assertEqual(c.subtract(1, Decimal(2)), d)
  2993. self.assertRaises(TypeError, c.subtract, '1', 2)
  2994. self.assertRaises(TypeError, c.subtract, 1, '2')
  2995. def test_to_eng_string(self):
  2996. Decimal = self.decimal.Decimal
  2997. Context = self.decimal.Context
  2998. c = Context()
  2999. d = c.to_eng_string(Decimal(10))
  3000. self.assertEqual(c.to_eng_string(10), d)
  3001. self.assertRaises(TypeError, c.to_eng_string, '10')
  3002. def test_to_sci_string(self):
  3003. Decimal = self.decimal.Decimal
  3004. Context = self.decimal.Context
  3005. c = Context()
  3006. d = c.to_sci_string(Decimal(10))
  3007. self.assertEqual(c.to_sci_string(10), d)
  3008. self.assertRaises(TypeError, c.to_sci_string, '10')
  3009. def test_to_integral_exact(self):
  3010. Decimal = self.decimal.Decimal
  3011. Context = self.decimal.Context
  3012. c = Context()
  3013. d = c.to_integral_exact(Decimal(10))
  3014. self.assertEqual(c.to_integral_exact(10), d)
  3015. self.assertRaises(TypeError, c.to_integral_exact, '10')
  3016. def test_to_integral_value(self):
  3017. Decimal = self.decimal.Decimal
  3018. Context = self.decimal.Context
  3019. c = Context()
  3020. d = c.to_integral_value(Decimal(10))
  3021. self.assertEqual(c.to_integral_value(10), d)
  3022. self.assertRaises(TypeError, c.to_integral_value, '10')
  3023. self.assertRaises(TypeError, c.to_integral_value, 10, 'x')
  3024. class CContextAPItests(ContextAPItests):
  3025. decimal = C
  3026. class PyContextAPItests(ContextAPItests):
  3027. decimal = P
  3028. class ContextWithStatement(unittest.TestCase):
  3029. # Can't do these as docstrings until Python 2.6
  3030. # as doctest can't handle __future__ statements
  3031. def test_localcontext(self):
  3032. # Use a copy of the current context in the block
  3033. getcontext = self.decimal.getcontext
  3034. localcontext = self.decimal.localcontext
  3035. orig_ctx = getcontext()
  3036. with localcontext() as enter_ctx:
  3037. set_ctx = getcontext()
  3038. final_ctx = getcontext()
  3039. self.assertIs(orig_ctx, final_ctx, 'did not restore context correctly')
  3040. self.assertIsNot(orig_ctx, set_ctx, 'did not copy the context')
  3041. self.assertIs(set_ctx, enter_ctx, '__enter__ returned wrong context')
  3042. def test_localcontextarg(self):
  3043. # Use a copy of the supplied context in the block
  3044. Context = self.decimal.Context
  3045. getcontext = self.decimal.getcontext
  3046. localcontext = self.decimal.localcontext
  3047. localcontext = self.decimal.localcontext
  3048. orig_ctx = getcontext()
  3049. new_ctx = Context(prec=42)
  3050. with localcontext(new_ctx) as enter_ctx:
  3051. set_ctx = getcontext()
  3052. final_ctx = getcontext()
  3053. self.assertIs(orig_ctx, final_ctx, 'did not restore context correctly')
  3054. self.assertEqual(set_ctx.prec, new_ctx.prec, 'did not set correct context')
  3055. self.assertIsNot(new_ctx, set_ctx, 'did not copy the context')
  3056. self.assertIs(set_ctx, enter_ctx, '__enter__ returned wrong context')
  3057. def test_localcontext_kwargs(self):
  3058. with self.decimal.localcontext(
  3059. prec=10, rounding=ROUND_HALF_DOWN,
  3060. Emin=-20, Emax=20, capitals=0,
  3061. clamp=1
  3062. ) as ctx:
  3063. self.assertEqual(ctx.prec, 10)
  3064. self.assertEqual(ctx.rounding, self.decimal.ROUND_HALF_DOWN)
  3065. self.assertEqual(ctx.Emin, -20)
  3066. self.assertEqual(ctx.Emax, 20)
  3067. self.assertEqual(ctx.capitals, 0)
  3068. self.assertEqual(ctx.clamp, 1)
  3069. self.assertRaises(TypeError, self.decimal.localcontext, precision=10)
  3070. self.assertRaises(ValueError, self.decimal.localcontext, Emin=1)
  3071. self.assertRaises(ValueError, self.decimal.localcontext, Emax=-1)
  3072. self.assertRaises(ValueError, self.decimal.localcontext, capitals=2)
  3073. self.assertRaises(ValueError, self.decimal.localcontext, clamp=2)
  3074. self.assertRaises(TypeError, self.decimal.localcontext, rounding="")
  3075. self.assertRaises(TypeError, self.decimal.localcontext, rounding=1)
  3076. self.assertRaises(TypeError, self.decimal.localcontext, flags="")
  3077. self.assertRaises(TypeError, self.decimal.localcontext, traps="")
  3078. self.assertRaises(TypeError, self.decimal.localcontext, Emin="")
  3079. self.assertRaises(TypeError, self.decimal.localcontext, Emax="")
  3080. def test_local_context_kwargs_does_not_overwrite_existing_argument(self):
  3081. ctx = self.decimal.getcontext()
  3082. ctx.prec = 28
  3083. with self.decimal.localcontext(prec=10) as ctx2:
  3084. self.assertEqual(ctx.prec, 28)
  3085. def test_nested_with_statements(self):
  3086. # Use a copy of the supplied context in the block
  3087. Decimal = self.decimal.Decimal
  3088. Context = self.decimal.Context
  3089. getcontext = self.decimal.getcontext
  3090. localcontext = self.decimal.localcontext
  3091. Clamped = self.decimal.Clamped
  3092. Overflow = self.decimal.Overflow
  3093. orig_ctx = getcontext()
  3094. orig_ctx.clear_flags()
  3095. new_ctx = Context(Emax=384)
  3096. with localcontext() as c1:
  3097. self.assertEqual(c1.flags, orig_ctx.flags)
  3098. self.assertEqual(c1.traps, orig_ctx.traps)
  3099. c1.traps[Clamped] = True
  3100. c1.Emin = -383
  3101. self.assertNotEqual(orig_ctx.Emin, -383)
  3102. self.assertRaises(Clamped, c1.create_decimal, '0e-999')
  3103. self.assertTrue(c1.flags[Clamped])
  3104. with localcontext(new_ctx) as c2:
  3105. self.assertEqual(c2.flags, new_ctx.flags)
  3106. self.assertEqual(c2.traps, new_ctx.traps)
  3107. self.assertRaises(Overflow, c2.power, Decimal('3.4e200'), 2)
  3108. self.assertFalse(c2.flags[Clamped])
  3109. self.assertTrue(c2.flags[Overflow])
  3110. del c2
  3111. self.assertFalse(c1.flags[Overflow])
  3112. del c1
  3113. self.assertNotEqual(orig_ctx.Emin, -383)
  3114. self.assertFalse(orig_ctx.flags[Clamped])
  3115. self.assertFalse(orig_ctx.flags[Overflow])
  3116. self.assertFalse(new_ctx.flags[Clamped])
  3117. self.assertFalse(new_ctx.flags[Overflow])
  3118. def test_with_statements_gc1(self):
  3119. localcontext = self.decimal.localcontext
  3120. with localcontext() as c1:
  3121. del c1
  3122. with localcontext() as c2:
  3123. del c2
  3124. with localcontext() as c3:
  3125. del c3
  3126. with localcontext() as c4:
  3127. del c4
  3128. def test_with_statements_gc2(self):
  3129. localcontext = self.decimal.localcontext
  3130. with localcontext() as c1:
  3131. with localcontext(c1) as c2:
  3132. del c1
  3133. with localcontext(c2) as c3:
  3134. del c2
  3135. with localcontext(c3) as c4:
  3136. del c3
  3137. del c4
  3138. def test_with_statements_gc3(self):
  3139. Context = self.decimal.Context
  3140. localcontext = self.decimal.localcontext
  3141. getcontext = self.decimal.getcontext
  3142. setcontext = self.decimal.setcontext
  3143. with localcontext() as c1:
  3144. del c1
  3145. n1 = Context(prec=1)
  3146. setcontext(n1)
  3147. with localcontext(n1) as c2:
  3148. del n1
  3149. self.assertEqual(c2.prec, 1)
  3150. del c2
  3151. n2 = Context(prec=2)
  3152. setcontext(n2)
  3153. del n2
  3154. self.assertEqual(getcontext().prec, 2)
  3155. n3 = Context(prec=3)
  3156. setcontext(n3)
  3157. self.assertEqual(getcontext().prec, 3)
  3158. with localcontext(n3) as c3:
  3159. del n3
  3160. self.assertEqual(c3.prec, 3)
  3161. del c3
  3162. n4 = Context(prec=4)
  3163. setcontext(n4)
  3164. del n4
  3165. self.assertEqual(getcontext().prec, 4)
  3166. with localcontext() as c4:
  3167. self.assertEqual(c4.prec, 4)
  3168. del c4
  3169. class CContextWithStatement(ContextWithStatement):
  3170. decimal = C
  3171. class PyContextWithStatement(ContextWithStatement):
  3172. decimal = P
  3173. class ContextFlags(unittest.TestCase):
  3174. def test_flags_irrelevant(self):
  3175. # check that the result (numeric result + flags raised) of an
  3176. # arithmetic operation doesn't depend on the current flags
  3177. Decimal = self.decimal.Decimal
  3178. Context = self.decimal.Context
  3179. Inexact = self.decimal.Inexact
  3180. Rounded = self.decimal.Rounded
  3181. Underflow = self.decimal.Underflow
  3182. Clamped = self.decimal.Clamped
  3183. Subnormal = self.decimal.Subnormal
  3184. def raise_error(context, flag):
  3185. if self.decimal == C:
  3186. context.flags[flag] = True
  3187. if context.traps[flag]:
  3188. raise flag
  3189. else:
  3190. context._raise_error(flag)
  3191. context = Context(prec=9, Emin = -425000000, Emax = 425000000,
  3192. rounding=ROUND_HALF_EVEN, traps=[], flags=[])
  3193. # operations that raise various flags, in the form (function, arglist)
  3194. operations = [
  3195. (context._apply, [Decimal("100E-425000010")]),
  3196. (context.sqrt, [Decimal(2)]),
  3197. (context.add, [Decimal("1.23456789"), Decimal("9.87654321")]),
  3198. (context.multiply, [Decimal("1.23456789"), Decimal("9.87654321")]),
  3199. (context.subtract, [Decimal("1.23456789"), Decimal("9.87654321")]),
  3200. ]
  3201. # try various flags individually, then a whole lot at once
  3202. flagsets = [[Inexact], [Rounded], [Underflow], [Clamped], [Subnormal],
  3203. [Inexact, Rounded, Underflow, Clamped, Subnormal]]
  3204. for fn, args in operations:
  3205. # find answer and flags raised using a clean context
  3206. context.clear_flags()
  3207. ans = fn(*args)
  3208. flags = [k for k, v in context.flags.items() if v]
  3209. for extra_flags in flagsets:
  3210. # set flags, before calling operation
  3211. context.clear_flags()
  3212. for flag in extra_flags:
  3213. raise_error(context, flag)
  3214. new_ans = fn(*args)
  3215. # flags that we expect to be set after the operation
  3216. expected_flags = list(flags)
  3217. for flag in extra_flags:
  3218. if flag not in expected_flags:
  3219. expected_flags.append(flag)
  3220. expected_flags.sort(key=id)
  3221. # flags we actually got
  3222. new_flags = [k for k,v in context.flags.items() if v]
  3223. new_flags.sort(key=id)
  3224. self.assertEqual(ans, new_ans,
  3225. "operation produces different answers depending on flags set: " +
  3226. "expected %s, got %s." % (ans, new_ans))
  3227. self.assertEqual(new_flags, expected_flags,
  3228. "operation raises different flags depending on flags set: " +
  3229. "expected %s, got %s" % (expected_flags, new_flags))
  3230. def test_flag_comparisons(self):
  3231. Context = self.decimal.Context
  3232. Inexact = self.decimal.Inexact
  3233. Rounded = self.decimal.Rounded
  3234. c = Context()
  3235. # Valid SignalDict
  3236. self.assertNotEqual(c.flags, c.traps)
  3237. self.assertNotEqual(c.traps, c.flags)
  3238. c.flags = c.traps
  3239. self.assertEqual(c.flags, c.traps)
  3240. self.assertEqual(c.traps, c.flags)
  3241. c.flags[Rounded] = True
  3242. c.traps = c.flags
  3243. self.assertEqual(c.flags, c.traps)
  3244. self.assertEqual(c.traps, c.flags)
  3245. d = {}
  3246. d.update(c.flags)
  3247. self.assertEqual(d, c.flags)
  3248. self.assertEqual(c.flags, d)
  3249. d[Inexact] = True
  3250. self.assertNotEqual(d, c.flags)
  3251. self.assertNotEqual(c.flags, d)
  3252. # Invalid SignalDict
  3253. d = {Inexact:False}
  3254. self.assertNotEqual(d, c.flags)
  3255. self.assertNotEqual(c.flags, d)
  3256. d = ["xyz"]
  3257. self.assertNotEqual(d, c.flags)
  3258. self.assertNotEqual(c.flags, d)
  3259. @requires_IEEE_754
  3260. def test_float_operation(self):
  3261. Decimal = self.decimal.Decimal
  3262. FloatOperation = self.decimal.FloatOperation
  3263. localcontext = self.decimal.localcontext
  3264. with localcontext() as c:
  3265. ##### trap is off by default
  3266. self.assertFalse(c.traps[FloatOperation])
  3267. # implicit conversion sets the flag
  3268. c.clear_flags()
  3269. self.assertEqual(Decimal(7.5), 7.5)
  3270. self.assertTrue(c.flags[FloatOperation])
  3271. c.clear_flags()
  3272. self.assertEqual(c.create_decimal(7.5), 7.5)
  3273. self.assertTrue(c.flags[FloatOperation])
  3274. # explicit conversion does not set the flag
  3275. c.clear_flags()
  3276. x = Decimal.from_float(7.5)
  3277. self.assertFalse(c.flags[FloatOperation])
  3278. # comparison sets the flag
  3279. self.assertEqual(x, 7.5)
  3280. self.assertTrue(c.flags[FloatOperation])
  3281. c.clear_flags()
  3282. x = c.create_decimal_from_float(7.5)
  3283. self.assertFalse(c.flags[FloatOperation])
  3284. self.assertEqual(x, 7.5)
  3285. self.assertTrue(c.flags[FloatOperation])
  3286. ##### set the trap
  3287. c.traps[FloatOperation] = True
  3288. # implicit conversion raises
  3289. c.clear_flags()
  3290. self.assertRaises(FloatOperation, Decimal, 7.5)
  3291. self.assertTrue(c.flags[FloatOperation])
  3292. c.clear_flags()
  3293. self.assertRaises(FloatOperation, c.create_decimal, 7.5)
  3294. self.assertTrue(c.flags[FloatOperation])
  3295. # explicit conversion is silent
  3296. c.clear_flags()
  3297. x = Decimal.from_float(7.5)
  3298. self.assertFalse(c.flags[FloatOperation])
  3299. c.clear_flags()
  3300. x = c.create_decimal_from_float(7.5)
  3301. self.assertFalse(c.flags[FloatOperation])
  3302. def test_float_comparison(self):
  3303. Decimal = self.decimal.Decimal
  3304. Context = self.decimal.Context
  3305. FloatOperation = self.decimal.FloatOperation
  3306. localcontext = self.decimal.localcontext
  3307. def assert_attr(a, b, attr, context, signal=None):
  3308. context.clear_flags()
  3309. f = getattr(a, attr)
  3310. if signal == FloatOperation:
  3311. self.assertRaises(signal, f, b)
  3312. else:
  3313. self.assertIs(f(b), True)
  3314. self.assertTrue(context.flags[FloatOperation])
  3315. small_d = Decimal('0.25')
  3316. big_d = Decimal('3.0')
  3317. small_f = 0.25
  3318. big_f = 3.0
  3319. zero_d = Decimal('0.0')
  3320. neg_zero_d = Decimal('-0.0')
  3321. zero_f = 0.0
  3322. neg_zero_f = -0.0
  3323. inf_d = Decimal('Infinity')
  3324. neg_inf_d = Decimal('-Infinity')
  3325. inf_f = float('inf')
  3326. neg_inf_f = float('-inf')
  3327. def doit(c, signal=None):
  3328. # Order
  3329. for attr in '__lt__', '__le__':
  3330. assert_attr(small_d, big_f, attr, c, signal)
  3331. for attr in '__gt__', '__ge__':
  3332. assert_attr(big_d, small_f, attr, c, signal)
  3333. # Equality
  3334. assert_attr(small_d, small_f, '__eq__', c, None)
  3335. assert_attr(neg_zero_d, neg_zero_f, '__eq__', c, None)
  3336. assert_attr(neg_zero_d, zero_f, '__eq__', c, None)
  3337. assert_attr(zero_d, neg_zero_f, '__eq__', c, None)
  3338. assert_attr(zero_d, zero_f, '__eq__', c, None)
  3339. assert_attr(neg_inf_d, neg_inf_f, '__eq__', c, None)
  3340. assert_attr(inf_d, inf_f, '__eq__', c, None)
  3341. # Inequality
  3342. assert_attr(small_d, big_f, '__ne__', c, None)
  3343. assert_attr(Decimal('0.1'), 0.1, '__ne__', c, None)
  3344. assert_attr(neg_inf_d, inf_f, '__ne__', c, None)
  3345. assert_attr(inf_d, neg_inf_f, '__ne__', c, None)
  3346. assert_attr(Decimal('NaN'), float('nan'), '__ne__', c, None)
  3347. def test_containers(c, signal=None):
  3348. c.clear_flags()
  3349. s = set([100.0, Decimal('100.0')])
  3350. self.assertEqual(len(s), 1)
  3351. self.assertTrue(c.flags[FloatOperation])
  3352. c.clear_flags()
  3353. if signal:
  3354. self.assertRaises(signal, sorted, [1.0, Decimal('10.0')])
  3355. else:
  3356. s = sorted([10.0, Decimal('10.0')])
  3357. self.assertTrue(c.flags[FloatOperation])
  3358. c.clear_flags()
  3359. b = 10.0 in [Decimal('10.0'), 1.0]
  3360. self.assertTrue(c.flags[FloatOperation])
  3361. c.clear_flags()
  3362. b = 10.0 in {Decimal('10.0'):'a', 1.0:'b'}
  3363. self.assertTrue(c.flags[FloatOperation])
  3364. nc = Context()
  3365. with localcontext(nc) as c:
  3366. self.assertFalse(c.traps[FloatOperation])
  3367. doit(c, signal=None)
  3368. test_containers(c, signal=None)
  3369. c.traps[FloatOperation] = True
  3370. doit(c, signal=FloatOperation)
  3371. test_containers(c, signal=FloatOperation)
  3372. def test_float_operation_default(self):
  3373. Decimal = self.decimal.Decimal
  3374. Context = self.decimal.Context
  3375. Inexact = self.decimal.Inexact
  3376. FloatOperation= self.decimal.FloatOperation
  3377. context = Context()
  3378. self.assertFalse(context.flags[FloatOperation])
  3379. self.assertFalse(context.traps[FloatOperation])
  3380. context.clear_traps()
  3381. context.traps[Inexact] = True
  3382. context.traps[FloatOperation] = True
  3383. self.assertTrue(context.traps[FloatOperation])
  3384. self.assertTrue(context.traps[Inexact])
  3385. class CContextFlags(ContextFlags):
  3386. decimal = C
  3387. class PyContextFlags(ContextFlags):
  3388. decimal = P
  3389. class SpecialContexts(unittest.TestCase):
  3390. """Test the context templates."""
  3391. def test_context_templates(self):
  3392. BasicContext = self.decimal.BasicContext
  3393. ExtendedContext = self.decimal.ExtendedContext
  3394. getcontext = self.decimal.getcontext
  3395. setcontext = self.decimal.setcontext
  3396. InvalidOperation = self.decimal.InvalidOperation
  3397. DivisionByZero = self.decimal.DivisionByZero
  3398. Overflow = self.decimal.Overflow
  3399. Underflow = self.decimal.Underflow
  3400. Clamped = self.decimal.Clamped
  3401. assert_signals(self, BasicContext, 'traps',
  3402. [InvalidOperation, DivisionByZero, Overflow, Underflow, Clamped]
  3403. )
  3404. savecontext = getcontext().copy()
  3405. basic_context_prec = BasicContext.prec
  3406. extended_context_prec = ExtendedContext.prec
  3407. ex = None
  3408. try:
  3409. BasicContext.prec = ExtendedContext.prec = 441
  3410. for template in BasicContext, ExtendedContext:
  3411. setcontext(template)
  3412. c = getcontext()
  3413. self.assertIsNot(c, template)
  3414. self.assertEqual(c.prec, 441)
  3415. except Exception as e:
  3416. ex = e.__class__
  3417. finally:
  3418. BasicContext.prec = basic_context_prec
  3419. ExtendedContext.prec = extended_context_prec
  3420. setcontext(savecontext)
  3421. if ex:
  3422. raise ex
  3423. def test_default_context(self):
  3424. DefaultContext = self.decimal.DefaultContext
  3425. BasicContext = self.decimal.BasicContext
  3426. ExtendedContext = self.decimal.ExtendedContext
  3427. getcontext = self.decimal.getcontext
  3428. setcontext = self.decimal.setcontext
  3429. InvalidOperation = self.decimal.InvalidOperation
  3430. DivisionByZero = self.decimal.DivisionByZero
  3431. Overflow = self.decimal.Overflow
  3432. self.assertEqual(BasicContext.prec, 9)
  3433. self.assertEqual(ExtendedContext.prec, 9)
  3434. assert_signals(self, DefaultContext, 'traps',
  3435. [InvalidOperation, DivisionByZero, Overflow]
  3436. )
  3437. savecontext = getcontext().copy()
  3438. default_context_prec = DefaultContext.prec
  3439. ex = None
  3440. try:
  3441. c = getcontext()
  3442. saveprec = c.prec
  3443. DefaultContext.prec = 961
  3444. c = getcontext()
  3445. self.assertEqual(c.prec, saveprec)
  3446. setcontext(DefaultContext)
  3447. c = getcontext()
  3448. self.assertIsNot(c, DefaultContext)
  3449. self.assertEqual(c.prec, 961)
  3450. except Exception as e:
  3451. ex = e.__class__
  3452. finally:
  3453. DefaultContext.prec = default_context_prec
  3454. setcontext(savecontext)
  3455. if ex:
  3456. raise ex
  3457. class CSpecialContexts(SpecialContexts):
  3458. decimal = C
  3459. class PySpecialContexts(SpecialContexts):
  3460. decimal = P
  3461. class ContextInputValidation(unittest.TestCase):
  3462. def test_invalid_context(self):
  3463. Context = self.decimal.Context
  3464. DefaultContext = self.decimal.DefaultContext
  3465. c = DefaultContext.copy()
  3466. # prec, Emax
  3467. for attr in ['prec', 'Emax']:
  3468. setattr(c, attr, 999999)
  3469. self.assertEqual(getattr(c, attr), 999999)
  3470. self.assertRaises(ValueError, setattr, c, attr, -1)
  3471. self.assertRaises(TypeError, setattr, c, attr, 'xyz')
  3472. # Emin
  3473. setattr(c, 'Emin', -999999)
  3474. self.assertEqual(getattr(c, 'Emin'), -999999)
  3475. self.assertRaises(ValueError, setattr, c, 'Emin', 1)
  3476. self.assertRaises(TypeError, setattr, c, 'Emin', (1,2,3))
  3477. self.assertRaises(TypeError, setattr, c, 'rounding', -1)
  3478. self.assertRaises(TypeError, setattr, c, 'rounding', 9)
  3479. self.assertRaises(TypeError, setattr, c, 'rounding', 1.0)
  3480. self.assertRaises(TypeError, setattr, c, 'rounding', 'xyz')
  3481. # capitals, clamp
  3482. for attr in ['capitals', 'clamp']:
  3483. self.assertRaises(ValueError, setattr, c, attr, -1)
  3484. self.assertRaises(ValueError, setattr, c, attr, 2)
  3485. self.assertRaises(TypeError, setattr, c, attr, [1,2,3])
  3486. # Invalid attribute
  3487. self.assertRaises(AttributeError, setattr, c, 'emax', 100)
  3488. # Invalid signal dict
  3489. self.assertRaises(TypeError, setattr, c, 'flags', [])
  3490. self.assertRaises(KeyError, setattr, c, 'flags', {})
  3491. self.assertRaises(KeyError, setattr, c, 'traps',
  3492. {'InvalidOperation':0})
  3493. # Attributes cannot be deleted
  3494. for attr in ['prec', 'Emax', 'Emin', 'rounding', 'capitals', 'clamp',
  3495. 'flags', 'traps']:
  3496. self.assertRaises(AttributeError, c.__delattr__, attr)
  3497. # Invalid attributes
  3498. self.assertRaises(TypeError, getattr, c, 9)
  3499. self.assertRaises(TypeError, setattr, c, 9)
  3500. # Invalid values in constructor
  3501. self.assertRaises(TypeError, Context, rounding=999999)
  3502. self.assertRaises(TypeError, Context, rounding='xyz')
  3503. self.assertRaises(ValueError, Context, clamp=2)
  3504. self.assertRaises(ValueError, Context, capitals=-1)
  3505. self.assertRaises(KeyError, Context, flags=["P"])
  3506. self.assertRaises(KeyError, Context, traps=["Q"])
  3507. # Type error in conversion
  3508. self.assertRaises(TypeError, Context, flags=(0,1))
  3509. self.assertRaises(TypeError, Context, traps=(1,0))
  3510. class CContextInputValidation(ContextInputValidation):
  3511. decimal = C
  3512. class PyContextInputValidation(ContextInputValidation):
  3513. decimal = P
  3514. class ContextSubclassing(unittest.TestCase):
  3515. def test_context_subclassing(self):
  3516. decimal = self.decimal
  3517. Decimal = decimal.Decimal
  3518. Context = decimal.Context
  3519. Clamped = decimal.Clamped
  3520. DivisionByZero = decimal.DivisionByZero
  3521. Inexact = decimal.Inexact
  3522. Overflow = decimal.Overflow
  3523. Rounded = decimal.Rounded
  3524. Subnormal = decimal.Subnormal
  3525. Underflow = decimal.Underflow
  3526. InvalidOperation = decimal.InvalidOperation
  3527. class MyContext(Context):
  3528. def __init__(self, prec=None, rounding=None, Emin=None, Emax=None,
  3529. capitals=None, clamp=None, flags=None,
  3530. traps=None):
  3531. Context.__init__(self)
  3532. if prec is not None:
  3533. self.prec = prec
  3534. if rounding is not None:
  3535. self.rounding = rounding
  3536. if Emin is not None:
  3537. self.Emin = Emin
  3538. if Emax is not None:
  3539. self.Emax = Emax
  3540. if capitals is not None:
  3541. self.capitals = capitals
  3542. if clamp is not None:
  3543. self.clamp = clamp
  3544. if flags is not None:
  3545. if isinstance(flags, list):
  3546. flags = {v:(v in flags) for v in OrderedSignals[decimal] + flags}
  3547. self.flags = flags
  3548. if traps is not None:
  3549. if isinstance(traps, list):
  3550. traps = {v:(v in traps) for v in OrderedSignals[decimal] + traps}
  3551. self.traps = traps
  3552. c = Context()
  3553. d = MyContext()
  3554. for attr in ('prec', 'rounding', 'Emin', 'Emax', 'capitals', 'clamp',
  3555. 'flags', 'traps'):
  3556. self.assertEqual(getattr(c, attr), getattr(d, attr))
  3557. # prec
  3558. self.assertRaises(ValueError, MyContext, **{'prec':-1})
  3559. c = MyContext(prec=1)
  3560. self.assertEqual(c.prec, 1)
  3561. self.assertRaises(InvalidOperation, c.quantize, Decimal('9e2'), 0)
  3562. # rounding
  3563. self.assertRaises(TypeError, MyContext, **{'rounding':'XYZ'})
  3564. c = MyContext(rounding=ROUND_DOWN, prec=1)
  3565. self.assertEqual(c.rounding, ROUND_DOWN)
  3566. self.assertEqual(c.plus(Decimal('9.9')), 9)
  3567. # Emin
  3568. self.assertRaises(ValueError, MyContext, **{'Emin':5})
  3569. c = MyContext(Emin=-1, prec=1)
  3570. self.assertEqual(c.Emin, -1)
  3571. x = c.add(Decimal('1e-99'), Decimal('2.234e-2000'))
  3572. self.assertEqual(x, Decimal('0.0'))
  3573. for signal in (Inexact, Underflow, Subnormal, Rounded, Clamped):
  3574. self.assertTrue(c.flags[signal])
  3575. # Emax
  3576. self.assertRaises(ValueError, MyContext, **{'Emax':-1})
  3577. c = MyContext(Emax=1, prec=1)
  3578. self.assertEqual(c.Emax, 1)
  3579. self.assertRaises(Overflow, c.add, Decimal('1e99'), Decimal('2.234e2000'))
  3580. if self.decimal == C:
  3581. for signal in (Inexact, Overflow, Rounded):
  3582. self.assertTrue(c.flags[signal])
  3583. # capitals
  3584. self.assertRaises(ValueError, MyContext, **{'capitals':-1})
  3585. c = MyContext(capitals=0)
  3586. self.assertEqual(c.capitals, 0)
  3587. x = c.create_decimal('1E222')
  3588. self.assertEqual(c.to_sci_string(x), '1e+222')
  3589. # clamp
  3590. self.assertRaises(ValueError, MyContext, **{'clamp':2})
  3591. c = MyContext(clamp=1, Emax=99)
  3592. self.assertEqual(c.clamp, 1)
  3593. x = c.plus(Decimal('1e99'))
  3594. self.assertEqual(str(x), '1.000000000000000000000000000E+99')
  3595. # flags
  3596. self.assertRaises(TypeError, MyContext, **{'flags':'XYZ'})
  3597. c = MyContext(flags=[Rounded, DivisionByZero])
  3598. for signal in (Rounded, DivisionByZero):
  3599. self.assertTrue(c.flags[signal])
  3600. c.clear_flags()
  3601. for signal in OrderedSignals[decimal]:
  3602. self.assertFalse(c.flags[signal])
  3603. # traps
  3604. self.assertRaises(TypeError, MyContext, **{'traps':'XYZ'})
  3605. c = MyContext(traps=[Rounded, DivisionByZero])
  3606. for signal in (Rounded, DivisionByZero):
  3607. self.assertTrue(c.traps[signal])
  3608. c.clear_traps()
  3609. for signal in OrderedSignals[decimal]:
  3610. self.assertFalse(c.traps[signal])
  3611. class CContextSubclassing(ContextSubclassing):
  3612. decimal = C
  3613. class PyContextSubclassing(ContextSubclassing):
  3614. decimal = P
  3615. @skip_if_extra_functionality
  3616. class CheckAttributes(unittest.TestCase):
  3617. def test_module_attributes(self):
  3618. # Architecture dependent context limits
  3619. self.assertEqual(C.MAX_PREC, P.MAX_PREC)
  3620. self.assertEqual(C.MAX_EMAX, P.MAX_EMAX)
  3621. self.assertEqual(C.MIN_EMIN, P.MIN_EMIN)
  3622. self.assertEqual(C.MIN_ETINY, P.MIN_ETINY)
  3623. self.assertTrue(C.HAVE_THREADS is True or C.HAVE_THREADS is False)
  3624. self.assertTrue(P.HAVE_THREADS is True or P.HAVE_THREADS is False)
  3625. self.assertEqual(C.__version__, P.__version__)
  3626. self.assertEqual(dir(C), dir(P))
  3627. def test_context_attributes(self):
  3628. x = [s for s in dir(C.Context()) if '__' in s or not s.startswith('_')]
  3629. y = [s for s in dir(P.Context()) if '__' in s or not s.startswith('_')]
  3630. self.assertEqual(set(x) - set(y), set())
  3631. def test_decimal_attributes(self):
  3632. x = [s for s in dir(C.Decimal(9)) if '__' in s or not s.startswith('_')]
  3633. y = [s for s in dir(C.Decimal(9)) if '__' in s or not s.startswith('_')]
  3634. self.assertEqual(set(x) - set(y), set())
  3635. class Coverage(unittest.TestCase):
  3636. def test_adjusted(self):
  3637. Decimal = self.decimal.Decimal
  3638. self.assertEqual(Decimal('1234e9999').adjusted(), 10002)
  3639. # XXX raise?
  3640. self.assertEqual(Decimal('nan').adjusted(), 0)
  3641. self.assertEqual(Decimal('inf').adjusted(), 0)
  3642. def test_canonical(self):
  3643. Decimal = self.decimal.Decimal
  3644. getcontext = self.decimal.getcontext
  3645. x = Decimal(9).canonical()
  3646. self.assertEqual(x, 9)
  3647. c = getcontext()
  3648. x = c.canonical(Decimal(9))
  3649. self.assertEqual(x, 9)
  3650. def test_context_repr(self):
  3651. c = self.decimal.DefaultContext.copy()
  3652. c.prec = 425000000
  3653. c.Emax = 425000000
  3654. c.Emin = -425000000
  3655. c.rounding = ROUND_HALF_DOWN
  3656. c.capitals = 0
  3657. c.clamp = 1
  3658. for sig in OrderedSignals[self.decimal]:
  3659. c.flags[sig] = False
  3660. c.traps[sig] = False
  3661. s = c.__repr__()
  3662. t = "Context(prec=425000000, rounding=ROUND_HALF_DOWN, " \
  3663. "Emin=-425000000, Emax=425000000, capitals=0, clamp=1, " \
  3664. "flags=[], traps=[])"
  3665. self.assertEqual(s, t)
  3666. def test_implicit_context(self):
  3667. Decimal = self.decimal.Decimal
  3668. localcontext = self.decimal.localcontext
  3669. with localcontext() as c:
  3670. c.prec = 1
  3671. c.Emax = 1
  3672. c.Emin = -1
  3673. # abs
  3674. self.assertEqual(abs(Decimal("-10")), 10)
  3675. # add
  3676. self.assertEqual(Decimal("7") + 1, 8)
  3677. # divide
  3678. self.assertEqual(Decimal("10") / 5, 2)
  3679. # divide_int
  3680. self.assertEqual(Decimal("10") // 7, 1)
  3681. # fma
  3682. self.assertEqual(Decimal("1.2").fma(Decimal("0.01"), 1), 1)
  3683. self.assertIs(Decimal("NaN").fma(7, 1).is_nan(), True)
  3684. # three arg power
  3685. self.assertEqual(pow(Decimal(10), 2, 7), 2)
  3686. # exp
  3687. self.assertEqual(Decimal("1.01").exp(), 3)
  3688. # is_normal
  3689. self.assertIs(Decimal("0.01").is_normal(), False)
  3690. # is_subnormal
  3691. self.assertIs(Decimal("0.01").is_subnormal(), True)
  3692. # ln
  3693. self.assertEqual(Decimal("20").ln(), 3)
  3694. # log10
  3695. self.assertEqual(Decimal("20").log10(), 1)
  3696. # logb
  3697. self.assertEqual(Decimal("580").logb(), 2)
  3698. # logical_invert
  3699. self.assertEqual(Decimal("10").logical_invert(), 1)
  3700. # minus
  3701. self.assertEqual(-Decimal("-10"), 10)
  3702. # multiply
  3703. self.assertEqual(Decimal("2") * 4, 8)
  3704. # next_minus
  3705. self.assertEqual(Decimal("10").next_minus(), 9)
  3706. # next_plus
  3707. self.assertEqual(Decimal("10").next_plus(), Decimal('2E+1'))
  3708. # normalize
  3709. self.assertEqual(Decimal("-10").normalize(), Decimal('-1E+1'))
  3710. # number_class
  3711. self.assertEqual(Decimal("10").number_class(), '+Normal')
  3712. # plus
  3713. self.assertEqual(+Decimal("-1"), -1)
  3714. # remainder
  3715. self.assertEqual(Decimal("10") % 7, 3)
  3716. # subtract
  3717. self.assertEqual(Decimal("10") - 7, 3)
  3718. # to_integral_exact
  3719. self.assertEqual(Decimal("1.12345").to_integral_exact(), 1)
  3720. # Boolean functions
  3721. self.assertTrue(Decimal("1").is_canonical())
  3722. self.assertTrue(Decimal("1").is_finite())
  3723. self.assertTrue(Decimal("1").is_finite())
  3724. self.assertTrue(Decimal("snan").is_snan())
  3725. self.assertTrue(Decimal("-1").is_signed())
  3726. self.assertTrue(Decimal("0").is_zero())
  3727. self.assertTrue(Decimal("0").is_zero())
  3728. # Copy
  3729. with localcontext() as c:
  3730. c.prec = 10000
  3731. x = 1228 ** 1523
  3732. y = -Decimal(x)
  3733. z = y.copy_abs()
  3734. self.assertEqual(z, x)
  3735. z = y.copy_negate()
  3736. self.assertEqual(z, x)
  3737. z = y.copy_sign(Decimal(1))
  3738. self.assertEqual(z, x)
  3739. def test_divmod(self):
  3740. Decimal = self.decimal.Decimal
  3741. localcontext = self.decimal.localcontext
  3742. InvalidOperation = self.decimal.InvalidOperation
  3743. DivisionByZero = self.decimal.DivisionByZero
  3744. with localcontext() as c:
  3745. q, r = divmod(Decimal("10912837129"), 1001)
  3746. self.assertEqual(q, Decimal('10901935'))
  3747. self.assertEqual(r, Decimal('194'))
  3748. q, r = divmod(Decimal("NaN"), 7)
  3749. self.assertTrue(q.is_nan() and r.is_nan())
  3750. c.traps[InvalidOperation] = False
  3751. q, r = divmod(Decimal("NaN"), 7)
  3752. self.assertTrue(q.is_nan() and r.is_nan())
  3753. c.traps[InvalidOperation] = False
  3754. c.clear_flags()
  3755. q, r = divmod(Decimal("inf"), Decimal("inf"))
  3756. self.assertTrue(q.is_nan() and r.is_nan())
  3757. self.assertTrue(c.flags[InvalidOperation])
  3758. c.clear_flags()
  3759. q, r = divmod(Decimal("inf"), 101)
  3760. self.assertTrue(q.is_infinite() and r.is_nan())
  3761. self.assertTrue(c.flags[InvalidOperation])
  3762. c.clear_flags()
  3763. q, r = divmod(Decimal(0), 0)
  3764. self.assertTrue(q.is_nan() and r.is_nan())
  3765. self.assertTrue(c.flags[InvalidOperation])
  3766. c.traps[DivisionByZero] = False
  3767. c.clear_flags()
  3768. q, r = divmod(Decimal(11), 0)
  3769. self.assertTrue(q.is_infinite() and r.is_nan())
  3770. self.assertTrue(c.flags[InvalidOperation] and
  3771. c.flags[DivisionByZero])
  3772. def test_power(self):
  3773. Decimal = self.decimal.Decimal
  3774. localcontext = self.decimal.localcontext
  3775. Overflow = self.decimal.Overflow
  3776. Rounded = self.decimal.Rounded
  3777. with localcontext() as c:
  3778. c.prec = 3
  3779. c.clear_flags()
  3780. self.assertEqual(Decimal("1.0") ** 100, Decimal('1.00'))
  3781. self.assertTrue(c.flags[Rounded])
  3782. c.prec = 1
  3783. c.Emax = 1
  3784. c.Emin = -1
  3785. c.clear_flags()
  3786. c.traps[Overflow] = False
  3787. self.assertEqual(Decimal(10000) ** Decimal("0.5"), Decimal('inf'))
  3788. self.assertTrue(c.flags[Overflow])
  3789. def test_quantize(self):
  3790. Decimal = self.decimal.Decimal
  3791. localcontext = self.decimal.localcontext
  3792. InvalidOperation = self.decimal.InvalidOperation
  3793. with localcontext() as c:
  3794. c.prec = 1
  3795. c.Emax = 1
  3796. c.Emin = -1
  3797. c.traps[InvalidOperation] = False
  3798. x = Decimal(99).quantize(Decimal("1e1"))
  3799. self.assertTrue(x.is_nan())
  3800. def test_radix(self):
  3801. Decimal = self.decimal.Decimal
  3802. getcontext = self.decimal.getcontext
  3803. c = getcontext()
  3804. self.assertEqual(Decimal("1").radix(), 10)
  3805. self.assertEqual(c.radix(), 10)
  3806. def test_rop(self):
  3807. Decimal = self.decimal.Decimal
  3808. for attr in ('__radd__', '__rsub__', '__rmul__', '__rtruediv__',
  3809. '__rdivmod__', '__rmod__', '__rfloordiv__', '__rpow__'):
  3810. self.assertIs(getattr(Decimal("1"), attr)("xyz"), NotImplemented)
  3811. def test_round(self):
  3812. # Python3 behavior: round() returns Decimal
  3813. Decimal = self.decimal.Decimal
  3814. localcontext = self.decimal.localcontext
  3815. with localcontext() as c:
  3816. c.prec = 28
  3817. self.assertEqual(str(Decimal("9.99").__round__()), "10")
  3818. self.assertEqual(str(Decimal("9.99e-5").__round__()), "0")
  3819. self.assertEqual(str(Decimal("1.23456789").__round__(5)), "1.23457")
  3820. self.assertEqual(str(Decimal("1.2345").__round__(10)), "1.2345000000")
  3821. self.assertEqual(str(Decimal("1.2345").__round__(-10)), "0E+10")
  3822. self.assertRaises(TypeError, Decimal("1.23").__round__, "5")
  3823. self.assertRaises(TypeError, Decimal("1.23").__round__, 5, 8)
  3824. def test_create_decimal(self):
  3825. c = self.decimal.Context()
  3826. self.assertRaises(ValueError, c.create_decimal, ["%"])
  3827. def test_int(self):
  3828. Decimal = self.decimal.Decimal
  3829. localcontext = self.decimal.localcontext
  3830. with localcontext() as c:
  3831. c.prec = 9999
  3832. x = Decimal(1221**1271) / 10**3923
  3833. self.assertEqual(int(x), 1)
  3834. self.assertEqual(x.to_integral(), 2)
  3835. def test_copy(self):
  3836. Context = self.decimal.Context
  3837. c = Context()
  3838. c.prec = 10000
  3839. x = -(1172 ** 1712)
  3840. y = c.copy_abs(x)
  3841. self.assertEqual(y, -x)
  3842. y = c.copy_negate(x)
  3843. self.assertEqual(y, -x)
  3844. y = c.copy_sign(x, 1)
  3845. self.assertEqual(y, -x)
  3846. class CCoverage(Coverage):
  3847. decimal = C
  3848. class PyCoverage(Coverage):
  3849. decimal = P
  3850. def setUp(self):
  3851. super().setUp()
  3852. self._previous_int_limit = sys.get_int_max_str_digits()
  3853. sys.set_int_max_str_digits(7000)
  3854. def tearDown(self):
  3855. sys.set_int_max_str_digits(self._previous_int_limit)
  3856. super().tearDown()
  3857. class PyFunctionality(unittest.TestCase):
  3858. """Extra functionality in decimal.py"""
  3859. def test_py_alternate_formatting(self):
  3860. # triples giving a format, a Decimal, and the expected result
  3861. Decimal = P.Decimal
  3862. localcontext = P.localcontext
  3863. test_values = [
  3864. # Issue 7094: Alternate formatting (specified by #)
  3865. ('.0e', '1.0', '1e+0'),
  3866. ('#.0e', '1.0', '1.e+0'),
  3867. ('.0f', '1.0', '1'),
  3868. ('#.0f', '1.0', '1.'),
  3869. ('g', '1.1', '1.1'),
  3870. ('#g', '1.1', '1.1'),
  3871. ('.0g', '1', '1'),
  3872. ('#.0g', '1', '1.'),
  3873. ('.0%', '1.0', '100%'),
  3874. ('#.0%', '1.0', '100.%'),
  3875. ]
  3876. for fmt, d, result in test_values:
  3877. self.assertEqual(format(Decimal(d), fmt), result)
  3878. class PyWhitebox(unittest.TestCase):
  3879. """White box testing for decimal.py"""
  3880. def test_py_exact_power(self):
  3881. # Rarely exercised lines in _power_exact.
  3882. Decimal = P.Decimal
  3883. localcontext = P.localcontext
  3884. with localcontext() as c:
  3885. c.prec = 8
  3886. x = Decimal(2**16) ** Decimal("-0.5")
  3887. self.assertEqual(x, Decimal('0.00390625'))
  3888. x = Decimal(2**16) ** Decimal("-0.6")
  3889. self.assertEqual(x, Decimal('0.0012885819'))
  3890. x = Decimal("256e7") ** Decimal("-0.5")
  3891. x = Decimal(152587890625) ** Decimal('-0.0625')
  3892. self.assertEqual(x, Decimal("0.2"))
  3893. x = Decimal("152587890625e7") ** Decimal('-0.0625')
  3894. x = Decimal(5**2659) ** Decimal('-0.0625')
  3895. c.prec = 1
  3896. x = Decimal("152587890625") ** Decimal('-0.5')
  3897. c.prec = 201
  3898. x = Decimal(2**578) ** Decimal("-0.5")
  3899. def test_py_immutability_operations(self):
  3900. # Do operations and check that it didn't change internal objects.
  3901. Decimal = P.Decimal
  3902. DefaultContext = P.DefaultContext
  3903. setcontext = P.setcontext
  3904. c = DefaultContext.copy()
  3905. c.traps = dict((s, 0) for s in OrderedSignals[P])
  3906. setcontext(c)
  3907. d1 = Decimal('-25e55')
  3908. b1 = Decimal('-25e55')
  3909. d2 = Decimal('33e+33')
  3910. b2 = Decimal('33e+33')
  3911. def checkSameDec(operation, useOther=False):
  3912. if useOther:
  3913. eval("d1." + operation + "(d2)")
  3914. self.assertEqual(d1._sign, b1._sign)
  3915. self.assertEqual(d1._int, b1._int)
  3916. self.assertEqual(d1._exp, b1._exp)
  3917. self.assertEqual(d2._sign, b2._sign)
  3918. self.assertEqual(d2._int, b2._int)
  3919. self.assertEqual(d2._exp, b2._exp)
  3920. else:
  3921. eval("d1." + operation + "()")
  3922. self.assertEqual(d1._sign, b1._sign)
  3923. self.assertEqual(d1._int, b1._int)
  3924. self.assertEqual(d1._exp, b1._exp)
  3925. Decimal(d1)
  3926. self.assertEqual(d1._sign, b1._sign)
  3927. self.assertEqual(d1._int, b1._int)
  3928. self.assertEqual(d1._exp, b1._exp)
  3929. checkSameDec("__abs__")
  3930. checkSameDec("__add__", True)
  3931. checkSameDec("__divmod__", True)
  3932. checkSameDec("__eq__", True)
  3933. checkSameDec("__ne__", True)
  3934. checkSameDec("__le__", True)
  3935. checkSameDec("__lt__", True)
  3936. checkSameDec("__ge__", True)
  3937. checkSameDec("__gt__", True)
  3938. checkSameDec("__float__")
  3939. checkSameDec("__floordiv__", True)
  3940. checkSameDec("__hash__")
  3941. checkSameDec("__int__")
  3942. checkSameDec("__trunc__")
  3943. checkSameDec("__mod__", True)
  3944. checkSameDec("__mul__", True)
  3945. checkSameDec("__neg__")
  3946. checkSameDec("__bool__")
  3947. checkSameDec("__pos__")
  3948. checkSameDec("__pow__", True)
  3949. checkSameDec("__radd__", True)
  3950. checkSameDec("__rdivmod__", True)
  3951. checkSameDec("__repr__")
  3952. checkSameDec("__rfloordiv__", True)
  3953. checkSameDec("__rmod__", True)
  3954. checkSameDec("__rmul__", True)
  3955. checkSameDec("__rpow__", True)
  3956. checkSameDec("__rsub__", True)
  3957. checkSameDec("__str__")
  3958. checkSameDec("__sub__", True)
  3959. checkSameDec("__truediv__", True)
  3960. checkSameDec("adjusted")
  3961. checkSameDec("as_tuple")
  3962. checkSameDec("compare", True)
  3963. checkSameDec("max", True)
  3964. checkSameDec("min", True)
  3965. checkSameDec("normalize")
  3966. checkSameDec("quantize", True)
  3967. checkSameDec("remainder_near", True)
  3968. checkSameDec("same_quantum", True)
  3969. checkSameDec("sqrt")
  3970. checkSameDec("to_eng_string")
  3971. checkSameDec("to_integral")
  3972. def test_py_decimal_id(self):
  3973. Decimal = P.Decimal
  3974. d = Decimal(45)
  3975. e = Decimal(d)
  3976. self.assertEqual(str(e), '45')
  3977. self.assertNotEqual(id(d), id(e))
  3978. def test_py_rescale(self):
  3979. # Coverage
  3980. Decimal = P.Decimal
  3981. localcontext = P.localcontext
  3982. with localcontext() as c:
  3983. x = Decimal("NaN")._rescale(3, ROUND_UP)
  3984. self.assertTrue(x.is_nan())
  3985. def test_py__round(self):
  3986. # Coverage
  3987. Decimal = P.Decimal
  3988. self.assertRaises(ValueError, Decimal("3.1234")._round, 0, ROUND_UP)
  3989. class CFunctionality(unittest.TestCase):
  3990. """Extra functionality in _decimal"""
  3991. @requires_extra_functionality
  3992. def test_c_ieee_context(self):
  3993. # issue 8786: Add support for IEEE 754 contexts to decimal module.
  3994. IEEEContext = C.IEEEContext
  3995. DECIMAL32 = C.DECIMAL32
  3996. DECIMAL64 = C.DECIMAL64
  3997. DECIMAL128 = C.DECIMAL128
  3998. def assert_rest(self, context):
  3999. self.assertEqual(context.clamp, 1)
  4000. assert_signals(self, context, 'traps', [])
  4001. assert_signals(self, context, 'flags', [])
  4002. c = IEEEContext(DECIMAL32)
  4003. self.assertEqual(c.prec, 7)
  4004. self.assertEqual(c.Emax, 96)
  4005. self.assertEqual(c.Emin, -95)
  4006. assert_rest(self, c)
  4007. c = IEEEContext(DECIMAL64)
  4008. self.assertEqual(c.prec, 16)
  4009. self.assertEqual(c.Emax, 384)
  4010. self.assertEqual(c.Emin, -383)
  4011. assert_rest(self, c)
  4012. c = IEEEContext(DECIMAL128)
  4013. self.assertEqual(c.prec, 34)
  4014. self.assertEqual(c.Emax, 6144)
  4015. self.assertEqual(c.Emin, -6143)
  4016. assert_rest(self, c)
  4017. # Invalid values
  4018. self.assertRaises(OverflowError, IEEEContext, 2**63)
  4019. self.assertRaises(ValueError, IEEEContext, -1)
  4020. self.assertRaises(ValueError, IEEEContext, 1024)
  4021. @requires_extra_functionality
  4022. def test_c_context(self):
  4023. Context = C.Context
  4024. c = Context(flags=C.DecClamped, traps=C.DecRounded)
  4025. self.assertEqual(c._flags, C.DecClamped)
  4026. self.assertEqual(c._traps, C.DecRounded)
  4027. @requires_extra_functionality
  4028. def test_constants(self):
  4029. # Condition flags
  4030. cond = (
  4031. C.DecClamped, C.DecConversionSyntax, C.DecDivisionByZero,
  4032. C.DecDivisionImpossible, C.DecDivisionUndefined,
  4033. C.DecFpuError, C.DecInexact, C.DecInvalidContext,
  4034. C.DecInvalidOperation, C.DecMallocError,
  4035. C.DecFloatOperation, C.DecOverflow, C.DecRounded,
  4036. C.DecSubnormal, C.DecUnderflow
  4037. )
  4038. # IEEEContext
  4039. self.assertEqual(C.DECIMAL32, 32)
  4040. self.assertEqual(C.DECIMAL64, 64)
  4041. self.assertEqual(C.DECIMAL128, 128)
  4042. self.assertEqual(C.IEEE_CONTEXT_MAX_BITS, 512)
  4043. # Conditions
  4044. for i, v in enumerate(cond):
  4045. self.assertEqual(v, 1<<i)
  4046. self.assertEqual(C.DecIEEEInvalidOperation,
  4047. C.DecConversionSyntax|
  4048. C.DecDivisionImpossible|
  4049. C.DecDivisionUndefined|
  4050. C.DecFpuError|
  4051. C.DecInvalidContext|
  4052. C.DecInvalidOperation|
  4053. C.DecMallocError)
  4054. self.assertEqual(C.DecErrors,
  4055. C.DecIEEEInvalidOperation|
  4056. C.DecDivisionByZero)
  4057. self.assertEqual(C.DecTraps,
  4058. C.DecErrors|C.DecOverflow|C.DecUnderflow)
  4059. class CWhitebox(unittest.TestCase):
  4060. """Whitebox testing for _decimal"""
  4061. def test_bignum(self):
  4062. # Not exactly whitebox, but too slow with pydecimal.
  4063. Decimal = C.Decimal
  4064. localcontext = C.localcontext
  4065. b1 = 10**35
  4066. b2 = 10**36
  4067. with localcontext() as c:
  4068. c.prec = 1000000
  4069. for i in range(5):
  4070. a = random.randrange(b1, b2)
  4071. b = random.randrange(1000, 1200)
  4072. x = a ** b
  4073. y = Decimal(a) ** Decimal(b)
  4074. self.assertEqual(x, y)
  4075. def test_invalid_construction(self):
  4076. self.assertRaises(TypeError, C.Decimal, 9, "xyz")
  4077. def test_c_input_restriction(self):
  4078. # Too large for _decimal to be converted exactly
  4079. Decimal = C.Decimal
  4080. InvalidOperation = C.InvalidOperation
  4081. Context = C.Context
  4082. localcontext = C.localcontext
  4083. with localcontext(Context()):
  4084. self.assertRaises(InvalidOperation, Decimal,
  4085. "1e9999999999999999999")
  4086. def test_c_context_repr(self):
  4087. # This test is _decimal-only because flags are not printed
  4088. # in the same order.
  4089. DefaultContext = C.DefaultContext
  4090. FloatOperation = C.FloatOperation
  4091. c = DefaultContext.copy()
  4092. c.prec = 425000000
  4093. c.Emax = 425000000
  4094. c.Emin = -425000000
  4095. c.rounding = ROUND_HALF_DOWN
  4096. c.capitals = 0
  4097. c.clamp = 1
  4098. for sig in OrderedSignals[C]:
  4099. c.flags[sig] = True
  4100. c.traps[sig] = True
  4101. c.flags[FloatOperation] = True
  4102. c.traps[FloatOperation] = True
  4103. s = c.__repr__()
  4104. t = "Context(prec=425000000, rounding=ROUND_HALF_DOWN, " \
  4105. "Emin=-425000000, Emax=425000000, capitals=0, clamp=1, " \
  4106. "flags=[Clamped, InvalidOperation, DivisionByZero, Inexact, " \
  4107. "FloatOperation, Overflow, Rounded, Subnormal, Underflow], " \
  4108. "traps=[Clamped, InvalidOperation, DivisionByZero, Inexact, " \
  4109. "FloatOperation, Overflow, Rounded, Subnormal, Underflow])"
  4110. self.assertEqual(s, t)
  4111. def test_c_context_errors(self):
  4112. Context = C.Context
  4113. InvalidOperation = C.InvalidOperation
  4114. Overflow = C.Overflow
  4115. FloatOperation = C.FloatOperation
  4116. localcontext = C.localcontext
  4117. getcontext = C.getcontext
  4118. setcontext = C.setcontext
  4119. HAVE_CONFIG_64 = (C.MAX_PREC > 425000000)
  4120. c = Context()
  4121. # SignalDict: input validation
  4122. self.assertRaises(KeyError, c.flags.__setitem__, 801, 0)
  4123. self.assertRaises(KeyError, c.traps.__setitem__, 801, 0)
  4124. self.assertRaises(ValueError, c.flags.__delitem__, Overflow)
  4125. self.assertRaises(ValueError, c.traps.__delitem__, InvalidOperation)
  4126. self.assertRaises(TypeError, setattr, c, 'flags', ['x'])
  4127. self.assertRaises(TypeError, setattr, c,'traps', ['y'])
  4128. self.assertRaises(KeyError, setattr, c, 'flags', {0:1})
  4129. self.assertRaises(KeyError, setattr, c, 'traps', {0:1})
  4130. # Test assignment from a signal dict with the correct length but
  4131. # one invalid key.
  4132. d = c.flags.copy()
  4133. del d[FloatOperation]
  4134. d["XYZ"] = 91283719
  4135. self.assertRaises(KeyError, setattr, c, 'flags', d)
  4136. self.assertRaises(KeyError, setattr, c, 'traps', d)
  4137. # Input corner cases
  4138. int_max = 2**63-1 if HAVE_CONFIG_64 else 2**31-1
  4139. gt_max_emax = 10**18 if HAVE_CONFIG_64 else 10**9
  4140. # prec, Emax, Emin
  4141. for attr in ['prec', 'Emax']:
  4142. self.assertRaises(ValueError, setattr, c, attr, gt_max_emax)
  4143. self.assertRaises(ValueError, setattr, c, 'Emin', -gt_max_emax)
  4144. # prec, Emax, Emin in context constructor
  4145. self.assertRaises(ValueError, Context, prec=gt_max_emax)
  4146. self.assertRaises(ValueError, Context, Emax=gt_max_emax)
  4147. self.assertRaises(ValueError, Context, Emin=-gt_max_emax)
  4148. # Overflow in conversion
  4149. self.assertRaises(OverflowError, Context, prec=int_max+1)
  4150. self.assertRaises(OverflowError, Context, Emax=int_max+1)
  4151. self.assertRaises(OverflowError, Context, Emin=-int_max-2)
  4152. self.assertRaises(OverflowError, Context, clamp=int_max+1)
  4153. self.assertRaises(OverflowError, Context, capitals=int_max+1)
  4154. # OverflowError, general ValueError
  4155. for attr in ('prec', 'Emin', 'Emax', 'capitals', 'clamp'):
  4156. self.assertRaises(OverflowError, setattr, c, attr, int_max+1)
  4157. self.assertRaises(OverflowError, setattr, c, attr, -int_max-2)
  4158. if sys.platform != 'win32':
  4159. self.assertRaises(ValueError, setattr, c, attr, int_max)
  4160. self.assertRaises(ValueError, setattr, c, attr, -int_max-1)
  4161. # OverflowError: _unsafe_setprec, _unsafe_setemin, _unsafe_setemax
  4162. if C.MAX_PREC == 425000000:
  4163. self.assertRaises(OverflowError, getattr(c, '_unsafe_setprec'),
  4164. int_max+1)
  4165. self.assertRaises(OverflowError, getattr(c, '_unsafe_setemax'),
  4166. int_max+1)
  4167. self.assertRaises(OverflowError, getattr(c, '_unsafe_setemin'),
  4168. -int_max-2)
  4169. # ValueError: _unsafe_setprec, _unsafe_setemin, _unsafe_setemax
  4170. if C.MAX_PREC == 425000000:
  4171. self.assertRaises(ValueError, getattr(c, '_unsafe_setprec'), 0)
  4172. self.assertRaises(ValueError, getattr(c, '_unsafe_setprec'),
  4173. 1070000001)
  4174. self.assertRaises(ValueError, getattr(c, '_unsafe_setemax'), -1)
  4175. self.assertRaises(ValueError, getattr(c, '_unsafe_setemax'),
  4176. 1070000001)
  4177. self.assertRaises(ValueError, getattr(c, '_unsafe_setemin'),
  4178. -1070000001)
  4179. self.assertRaises(ValueError, getattr(c, '_unsafe_setemin'), 1)
  4180. # capitals, clamp
  4181. for attr in ['capitals', 'clamp']:
  4182. self.assertRaises(ValueError, setattr, c, attr, -1)
  4183. self.assertRaises(ValueError, setattr, c, attr, 2)
  4184. self.assertRaises(TypeError, setattr, c, attr, [1,2,3])
  4185. if HAVE_CONFIG_64:
  4186. self.assertRaises(ValueError, setattr, c, attr, 2**32)
  4187. self.assertRaises(ValueError, setattr, c, attr, 2**32+1)
  4188. # Invalid local context
  4189. self.assertRaises(TypeError, exec, 'with localcontext("xyz"): pass',
  4190. locals())
  4191. self.assertRaises(TypeError, exec,
  4192. 'with localcontext(context=getcontext()): pass',
  4193. locals())
  4194. # setcontext
  4195. saved_context = getcontext()
  4196. self.assertRaises(TypeError, setcontext, "xyz")
  4197. setcontext(saved_context)
  4198. def test_rounding_strings_interned(self):
  4199. self.assertIs(C.ROUND_UP, P.ROUND_UP)
  4200. self.assertIs(C.ROUND_DOWN, P.ROUND_DOWN)
  4201. self.assertIs(C.ROUND_CEILING, P.ROUND_CEILING)
  4202. self.assertIs(C.ROUND_FLOOR, P.ROUND_FLOOR)
  4203. self.assertIs(C.ROUND_HALF_UP, P.ROUND_HALF_UP)
  4204. self.assertIs(C.ROUND_HALF_DOWN, P.ROUND_HALF_DOWN)
  4205. self.assertIs(C.ROUND_HALF_EVEN, P.ROUND_HALF_EVEN)
  4206. self.assertIs(C.ROUND_05UP, P.ROUND_05UP)
  4207. @requires_extra_functionality
  4208. def test_c_context_errors_extra(self):
  4209. Context = C.Context
  4210. InvalidOperation = C.InvalidOperation
  4211. Overflow = C.Overflow
  4212. localcontext = C.localcontext
  4213. getcontext = C.getcontext
  4214. setcontext = C.setcontext
  4215. HAVE_CONFIG_64 = (C.MAX_PREC > 425000000)
  4216. c = Context()
  4217. # Input corner cases
  4218. int_max = 2**63-1 if HAVE_CONFIG_64 else 2**31-1
  4219. # OverflowError, general ValueError
  4220. self.assertRaises(OverflowError, setattr, c, '_allcr', int_max+1)
  4221. self.assertRaises(OverflowError, setattr, c, '_allcr', -int_max-2)
  4222. if sys.platform != 'win32':
  4223. self.assertRaises(ValueError, setattr, c, '_allcr', int_max)
  4224. self.assertRaises(ValueError, setattr, c, '_allcr', -int_max-1)
  4225. # OverflowError, general TypeError
  4226. for attr in ('_flags', '_traps'):
  4227. self.assertRaises(OverflowError, setattr, c, attr, int_max+1)
  4228. self.assertRaises(OverflowError, setattr, c, attr, -int_max-2)
  4229. if sys.platform != 'win32':
  4230. self.assertRaises(TypeError, setattr, c, attr, int_max)
  4231. self.assertRaises(TypeError, setattr, c, attr, -int_max-1)
  4232. # _allcr
  4233. self.assertRaises(ValueError, setattr, c, '_allcr', -1)
  4234. self.assertRaises(ValueError, setattr, c, '_allcr', 2)
  4235. self.assertRaises(TypeError, setattr, c, '_allcr', [1,2,3])
  4236. if HAVE_CONFIG_64:
  4237. self.assertRaises(ValueError, setattr, c, '_allcr', 2**32)
  4238. self.assertRaises(ValueError, setattr, c, '_allcr', 2**32+1)
  4239. # _flags, _traps
  4240. for attr in ['_flags', '_traps']:
  4241. self.assertRaises(TypeError, setattr, c, attr, 999999)
  4242. self.assertRaises(TypeError, setattr, c, attr, 'x')
  4243. def test_c_valid_context(self):
  4244. # These tests are for code coverage in _decimal.
  4245. DefaultContext = C.DefaultContext
  4246. Clamped = C.Clamped
  4247. Underflow = C.Underflow
  4248. Inexact = C.Inexact
  4249. Rounded = C.Rounded
  4250. Subnormal = C.Subnormal
  4251. c = DefaultContext.copy()
  4252. # Exercise all getters and setters
  4253. c.prec = 34
  4254. c.rounding = ROUND_HALF_UP
  4255. c.Emax = 3000
  4256. c.Emin = -3000
  4257. c.capitals = 1
  4258. c.clamp = 0
  4259. self.assertEqual(c.prec, 34)
  4260. self.assertEqual(c.rounding, ROUND_HALF_UP)
  4261. self.assertEqual(c.Emin, -3000)
  4262. self.assertEqual(c.Emax, 3000)
  4263. self.assertEqual(c.capitals, 1)
  4264. self.assertEqual(c.clamp, 0)
  4265. self.assertEqual(c.Etiny(), -3033)
  4266. self.assertEqual(c.Etop(), 2967)
  4267. # Exercise all unsafe setters
  4268. if C.MAX_PREC == 425000000:
  4269. c._unsafe_setprec(999999999)
  4270. c._unsafe_setemax(999999999)
  4271. c._unsafe_setemin(-999999999)
  4272. self.assertEqual(c.prec, 999999999)
  4273. self.assertEqual(c.Emax, 999999999)
  4274. self.assertEqual(c.Emin, -999999999)
  4275. @requires_extra_functionality
  4276. def test_c_valid_context_extra(self):
  4277. DefaultContext = C.DefaultContext
  4278. c = DefaultContext.copy()
  4279. self.assertEqual(c._allcr, 1)
  4280. c._allcr = 0
  4281. self.assertEqual(c._allcr, 0)
  4282. def test_c_round(self):
  4283. # Restricted input.
  4284. Decimal = C.Decimal
  4285. InvalidOperation = C.InvalidOperation
  4286. localcontext = C.localcontext
  4287. MAX_EMAX = C.MAX_EMAX
  4288. MIN_ETINY = C.MIN_ETINY
  4289. int_max = 2**63-1 if C.MAX_PREC > 425000000 else 2**31-1
  4290. with localcontext() as c:
  4291. c.traps[InvalidOperation] = True
  4292. self.assertRaises(InvalidOperation, Decimal("1.23").__round__,
  4293. -int_max-1)
  4294. self.assertRaises(InvalidOperation, Decimal("1.23").__round__,
  4295. int_max)
  4296. self.assertRaises(InvalidOperation, Decimal("1").__round__,
  4297. int(MAX_EMAX+1))
  4298. self.assertRaises(C.InvalidOperation, Decimal("1").__round__,
  4299. -int(MIN_ETINY-1))
  4300. self.assertRaises(OverflowError, Decimal("1.23").__round__,
  4301. -int_max-2)
  4302. self.assertRaises(OverflowError, Decimal("1.23").__round__,
  4303. int_max+1)
  4304. def test_c_format(self):
  4305. # Restricted input
  4306. Decimal = C.Decimal
  4307. HAVE_CONFIG_64 = (C.MAX_PREC > 425000000)
  4308. self.assertRaises(TypeError, Decimal(1).__format__, "=10.10", [], 9)
  4309. self.assertRaises(TypeError, Decimal(1).__format__, "=10.10", 9)
  4310. self.assertRaises(TypeError, Decimal(1).__format__, [])
  4311. self.assertRaises(ValueError, Decimal(1).__format__, "<>=10.10")
  4312. maxsize = 2**63-1 if HAVE_CONFIG_64 else 2**31-1
  4313. self.assertRaises(ValueError, Decimal("1.23456789").__format__,
  4314. "=%d.1" % maxsize)
  4315. def test_c_integral(self):
  4316. Decimal = C.Decimal
  4317. Inexact = C.Inexact
  4318. localcontext = C.localcontext
  4319. x = Decimal(10)
  4320. self.assertEqual(x.to_integral(), 10)
  4321. self.assertRaises(TypeError, x.to_integral, '10')
  4322. self.assertRaises(TypeError, x.to_integral, 10, 'x')
  4323. self.assertRaises(TypeError, x.to_integral, 10)
  4324. self.assertEqual(x.to_integral_value(), 10)
  4325. self.assertRaises(TypeError, x.to_integral_value, '10')
  4326. self.assertRaises(TypeError, x.to_integral_value, 10, 'x')
  4327. self.assertRaises(TypeError, x.to_integral_value, 10)
  4328. self.assertEqual(x.to_integral_exact(), 10)
  4329. self.assertRaises(TypeError, x.to_integral_exact, '10')
  4330. self.assertRaises(TypeError, x.to_integral_exact, 10, 'x')
  4331. self.assertRaises(TypeError, x.to_integral_exact, 10)
  4332. with localcontext() as c:
  4333. x = Decimal("99999999999999999999999999.9").to_integral_value(ROUND_UP)
  4334. self.assertEqual(x, Decimal('100000000000000000000000000'))
  4335. x = Decimal("99999999999999999999999999.9").to_integral_exact(ROUND_UP)
  4336. self.assertEqual(x, Decimal('100000000000000000000000000'))
  4337. c.traps[Inexact] = True
  4338. self.assertRaises(Inexact, Decimal("999.9").to_integral_exact, ROUND_UP)
  4339. def test_c_funcs(self):
  4340. # Invalid arguments
  4341. Decimal = C.Decimal
  4342. InvalidOperation = C.InvalidOperation
  4343. DivisionByZero = C.DivisionByZero
  4344. getcontext = C.getcontext
  4345. localcontext = C.localcontext
  4346. self.assertEqual(Decimal('9.99e10').to_eng_string(), '99.9E+9')
  4347. self.assertRaises(TypeError, pow, Decimal(1), 2, "3")
  4348. self.assertRaises(TypeError, Decimal(9).number_class, "x", "y")
  4349. self.assertRaises(TypeError, Decimal(9).same_quantum, 3, "x", "y")
  4350. self.assertRaises(
  4351. TypeError,
  4352. Decimal("1.23456789").quantize, Decimal('1e-100000'), []
  4353. )
  4354. self.assertRaises(
  4355. TypeError,
  4356. Decimal("1.23456789").quantize, Decimal('1e-100000'), getcontext()
  4357. )
  4358. self.assertRaises(
  4359. TypeError,
  4360. Decimal("1.23456789").quantize, Decimal('1e-100000'), 10
  4361. )
  4362. self.assertRaises(
  4363. TypeError,
  4364. Decimal("1.23456789").quantize, Decimal('1e-100000'), ROUND_UP, 1000
  4365. )
  4366. with localcontext() as c:
  4367. c.clear_traps()
  4368. # Invalid arguments
  4369. self.assertRaises(TypeError, c.copy_sign, Decimal(1), "x", "y")
  4370. self.assertRaises(TypeError, c.canonical, 200)
  4371. self.assertRaises(TypeError, c.is_canonical, 200)
  4372. self.assertRaises(TypeError, c.divmod, 9, 8, "x", "y")
  4373. self.assertRaises(TypeError, c.same_quantum, 9, 3, "x", "y")
  4374. self.assertEqual(str(c.canonical(Decimal(200))), '200')
  4375. self.assertEqual(c.radix(), 10)
  4376. c.traps[DivisionByZero] = True
  4377. self.assertRaises(DivisionByZero, Decimal(9).__divmod__, 0)
  4378. self.assertRaises(DivisionByZero, c.divmod, 9, 0)
  4379. self.assertTrue(c.flags[InvalidOperation])
  4380. c.clear_flags()
  4381. c.traps[InvalidOperation] = True
  4382. self.assertRaises(InvalidOperation, Decimal(9).__divmod__, 0)
  4383. self.assertRaises(InvalidOperation, c.divmod, 9, 0)
  4384. self.assertTrue(c.flags[DivisionByZero])
  4385. c.traps[InvalidOperation] = True
  4386. c.prec = 2
  4387. self.assertRaises(InvalidOperation, pow, Decimal(1000), 1, 501)
  4388. def test_va_args_exceptions(self):
  4389. Decimal = C.Decimal
  4390. Context = C.Context
  4391. x = Decimal("10001111111")
  4392. for attr in ['exp', 'is_normal', 'is_subnormal', 'ln', 'log10',
  4393. 'logb', 'logical_invert', 'next_minus', 'next_plus',
  4394. 'normalize', 'number_class', 'sqrt', 'to_eng_string']:
  4395. func = getattr(x, attr)
  4396. self.assertRaises(TypeError, func, context="x")
  4397. self.assertRaises(TypeError, func, "x", context=None)
  4398. for attr in ['compare', 'compare_signal', 'logical_and',
  4399. 'logical_or', 'max', 'max_mag', 'min', 'min_mag',
  4400. 'remainder_near', 'rotate', 'scaleb', 'shift']:
  4401. func = getattr(x, attr)
  4402. self.assertRaises(TypeError, func, context="x")
  4403. self.assertRaises(TypeError, func, "x", context=None)
  4404. self.assertRaises(TypeError, x.to_integral, rounding=None, context=[])
  4405. self.assertRaises(TypeError, x.to_integral, rounding={}, context=[])
  4406. self.assertRaises(TypeError, x.to_integral, [], [])
  4407. self.assertRaises(TypeError, x.to_integral_value, rounding=None, context=[])
  4408. self.assertRaises(TypeError, x.to_integral_value, rounding={}, context=[])
  4409. self.assertRaises(TypeError, x.to_integral_value, [], [])
  4410. self.assertRaises(TypeError, x.to_integral_exact, rounding=None, context=[])
  4411. self.assertRaises(TypeError, x.to_integral_exact, rounding={}, context=[])
  4412. self.assertRaises(TypeError, x.to_integral_exact, [], [])
  4413. self.assertRaises(TypeError, x.fma, 1, 2, context="x")
  4414. self.assertRaises(TypeError, x.fma, 1, 2, "x", context=None)
  4415. self.assertRaises(TypeError, x.quantize, 1, [], context=None)
  4416. self.assertRaises(TypeError, x.quantize, 1, [], rounding=None)
  4417. self.assertRaises(TypeError, x.quantize, 1, [], [])
  4418. c = Context()
  4419. self.assertRaises(TypeError, c.power, 1, 2, mod="x")
  4420. self.assertRaises(TypeError, c.power, 1, "x", mod=None)
  4421. self.assertRaises(TypeError, c.power, "x", 2, mod=None)
  4422. @requires_extra_functionality
  4423. def test_c_context_templates(self):
  4424. self.assertEqual(
  4425. C.BasicContext._traps,
  4426. C.DecIEEEInvalidOperation|C.DecDivisionByZero|C.DecOverflow|
  4427. C.DecUnderflow|C.DecClamped
  4428. )
  4429. self.assertEqual(
  4430. C.DefaultContext._traps,
  4431. C.DecIEEEInvalidOperation|C.DecDivisionByZero|C.DecOverflow
  4432. )
  4433. @requires_extra_functionality
  4434. def test_c_signal_dict(self):
  4435. # SignalDict coverage
  4436. Context = C.Context
  4437. DefaultContext = C.DefaultContext
  4438. InvalidOperation = C.InvalidOperation
  4439. FloatOperation = C.FloatOperation
  4440. DivisionByZero = C.DivisionByZero
  4441. Overflow = C.Overflow
  4442. Subnormal = C.Subnormal
  4443. Underflow = C.Underflow
  4444. Rounded = C.Rounded
  4445. Inexact = C.Inexact
  4446. Clamped = C.Clamped
  4447. DecClamped = C.DecClamped
  4448. DecInvalidOperation = C.DecInvalidOperation
  4449. DecIEEEInvalidOperation = C.DecIEEEInvalidOperation
  4450. def assertIsExclusivelySet(signal, signal_dict):
  4451. for sig in signal_dict:
  4452. if sig == signal:
  4453. self.assertTrue(signal_dict[sig])
  4454. else:
  4455. self.assertFalse(signal_dict[sig])
  4456. c = DefaultContext.copy()
  4457. # Signal dict methods
  4458. self.assertTrue(Overflow in c.traps)
  4459. c.clear_traps()
  4460. for k in c.traps.keys():
  4461. c.traps[k] = True
  4462. for v in c.traps.values():
  4463. self.assertTrue(v)
  4464. c.clear_traps()
  4465. for k, v in c.traps.items():
  4466. self.assertFalse(v)
  4467. self.assertFalse(c.flags.get(Overflow))
  4468. self.assertIs(c.flags.get("x"), None)
  4469. self.assertEqual(c.flags.get("x", "y"), "y")
  4470. self.assertRaises(TypeError, c.flags.get, "x", "y", "z")
  4471. self.assertEqual(len(c.flags), len(c.traps))
  4472. s = sys.getsizeof(c.flags)
  4473. s = sys.getsizeof(c.traps)
  4474. s = c.flags.__repr__()
  4475. # Set flags/traps.
  4476. c.clear_flags()
  4477. c._flags = DecClamped
  4478. self.assertTrue(c.flags[Clamped])
  4479. c.clear_traps()
  4480. c._traps = DecInvalidOperation
  4481. self.assertTrue(c.traps[InvalidOperation])
  4482. # Set flags/traps from dictionary.
  4483. c.clear_flags()
  4484. d = c.flags.copy()
  4485. d[DivisionByZero] = True
  4486. c.flags = d
  4487. assertIsExclusivelySet(DivisionByZero, c.flags)
  4488. c.clear_traps()
  4489. d = c.traps.copy()
  4490. d[Underflow] = True
  4491. c.traps = d
  4492. assertIsExclusivelySet(Underflow, c.traps)
  4493. # Random constructors
  4494. IntSignals = {
  4495. Clamped: C.DecClamped,
  4496. Rounded: C.DecRounded,
  4497. Inexact: C.DecInexact,
  4498. Subnormal: C.DecSubnormal,
  4499. Underflow: C.DecUnderflow,
  4500. Overflow: C.DecOverflow,
  4501. DivisionByZero: C.DecDivisionByZero,
  4502. FloatOperation: C.DecFloatOperation,
  4503. InvalidOperation: C.DecIEEEInvalidOperation
  4504. }
  4505. IntCond = [
  4506. C.DecDivisionImpossible, C.DecDivisionUndefined, C.DecFpuError,
  4507. C.DecInvalidContext, C.DecInvalidOperation, C.DecMallocError,
  4508. C.DecConversionSyntax,
  4509. ]
  4510. lim = len(OrderedSignals[C])
  4511. for r in range(lim):
  4512. for t in range(lim):
  4513. for round in RoundingModes:
  4514. flags = random.sample(OrderedSignals[C], r)
  4515. traps = random.sample(OrderedSignals[C], t)
  4516. prec = random.randrange(1, 10000)
  4517. emin = random.randrange(-10000, 0)
  4518. emax = random.randrange(0, 10000)
  4519. clamp = random.randrange(0, 2)
  4520. caps = random.randrange(0, 2)
  4521. cr = random.randrange(0, 2)
  4522. c = Context(prec=prec, rounding=round, Emin=emin, Emax=emax,
  4523. capitals=caps, clamp=clamp, flags=list(flags),
  4524. traps=list(traps))
  4525. self.assertEqual(c.prec, prec)
  4526. self.assertEqual(c.rounding, round)
  4527. self.assertEqual(c.Emin, emin)
  4528. self.assertEqual(c.Emax, emax)
  4529. self.assertEqual(c.capitals, caps)
  4530. self.assertEqual(c.clamp, clamp)
  4531. f = 0
  4532. for x in flags:
  4533. f |= IntSignals[x]
  4534. self.assertEqual(c._flags, f)
  4535. f = 0
  4536. for x in traps:
  4537. f |= IntSignals[x]
  4538. self.assertEqual(c._traps, f)
  4539. for cond in IntCond:
  4540. c._flags = cond
  4541. self.assertTrue(c._flags&DecIEEEInvalidOperation)
  4542. assertIsExclusivelySet(InvalidOperation, c.flags)
  4543. for cond in IntCond:
  4544. c._traps = cond
  4545. self.assertTrue(c._traps&DecIEEEInvalidOperation)
  4546. assertIsExclusivelySet(InvalidOperation, c.traps)
  4547. def test_invalid_override(self):
  4548. Decimal = C.Decimal
  4549. try:
  4550. from locale import CHAR_MAX
  4551. except ImportError:
  4552. self.skipTest('locale.CHAR_MAX not available')
  4553. def make_grouping(lst):
  4554. return ''.join([chr(x) for x in lst])
  4555. def get_fmt(x, override=None, fmt='n'):
  4556. return Decimal(x).__format__(fmt, override)
  4557. invalid_grouping = {
  4558. 'decimal_point' : ',',
  4559. 'grouping' : make_grouping([255, 255, 0]),
  4560. 'thousands_sep' : ','
  4561. }
  4562. invalid_dot = {
  4563. 'decimal_point' : 'xxxxx',
  4564. 'grouping' : make_grouping([3, 3, 0]),
  4565. 'thousands_sep' : ','
  4566. }
  4567. invalid_sep = {
  4568. 'decimal_point' : '.',
  4569. 'grouping' : make_grouping([3, 3, 0]),
  4570. 'thousands_sep' : 'yyyyy'
  4571. }
  4572. if CHAR_MAX == 127: # negative grouping in override
  4573. self.assertRaises(ValueError, get_fmt, 12345,
  4574. invalid_grouping, 'g')
  4575. self.assertRaises(ValueError, get_fmt, 12345, invalid_dot, 'g')
  4576. self.assertRaises(ValueError, get_fmt, 12345, invalid_sep, 'g')
  4577. def test_exact_conversion(self):
  4578. Decimal = C.Decimal
  4579. localcontext = C.localcontext
  4580. InvalidOperation = C.InvalidOperation
  4581. with localcontext() as c:
  4582. c.traps[InvalidOperation] = True
  4583. # Clamped
  4584. x = "0e%d" % sys.maxsize
  4585. self.assertRaises(InvalidOperation, Decimal, x)
  4586. x = "0e%d" % (-sys.maxsize-1)
  4587. self.assertRaises(InvalidOperation, Decimal, x)
  4588. # Overflow
  4589. x = "1e%d" % sys.maxsize
  4590. self.assertRaises(InvalidOperation, Decimal, x)
  4591. # Underflow
  4592. x = "1e%d" % (-sys.maxsize-1)
  4593. self.assertRaises(InvalidOperation, Decimal, x)
  4594. def test_from_tuple(self):
  4595. Decimal = C.Decimal
  4596. localcontext = C.localcontext
  4597. InvalidOperation = C.InvalidOperation
  4598. Overflow = C.Overflow
  4599. Underflow = C.Underflow
  4600. with localcontext() as c:
  4601. c.prec = 9
  4602. c.traps[InvalidOperation] = True
  4603. c.traps[Overflow] = True
  4604. c.traps[Underflow] = True
  4605. # SSIZE_MAX
  4606. x = (1, (), sys.maxsize)
  4607. self.assertEqual(str(c.create_decimal(x)), '-0E+999999')
  4608. self.assertRaises(InvalidOperation, Decimal, x)
  4609. x = (1, (0, 1, 2), sys.maxsize)
  4610. self.assertRaises(Overflow, c.create_decimal, x)
  4611. self.assertRaises(InvalidOperation, Decimal, x)
  4612. # SSIZE_MIN
  4613. x = (1, (), -sys.maxsize-1)
  4614. self.assertEqual(str(c.create_decimal(x)), '-0E-1000007')
  4615. self.assertRaises(InvalidOperation, Decimal, x)
  4616. x = (1, (0, 1, 2), -sys.maxsize-1)
  4617. self.assertRaises(Underflow, c.create_decimal, x)
  4618. self.assertRaises(InvalidOperation, Decimal, x)
  4619. # OverflowError
  4620. x = (1, (), sys.maxsize+1)
  4621. self.assertRaises(OverflowError, c.create_decimal, x)
  4622. self.assertRaises(OverflowError, Decimal, x)
  4623. x = (1, (), -sys.maxsize-2)
  4624. self.assertRaises(OverflowError, c.create_decimal, x)
  4625. self.assertRaises(OverflowError, Decimal, x)
  4626. # Specials
  4627. x = (1, (), "N")
  4628. self.assertEqual(str(Decimal(x)), '-sNaN')
  4629. x = (1, (0,), "N")
  4630. self.assertEqual(str(Decimal(x)), '-sNaN')
  4631. x = (1, (0, 1), "N")
  4632. self.assertEqual(str(Decimal(x)), '-sNaN1')
  4633. def test_sizeof(self):
  4634. Decimal = C.Decimal
  4635. HAVE_CONFIG_64 = (C.MAX_PREC > 425000000)
  4636. self.assertGreater(Decimal(0).__sizeof__(), 0)
  4637. if HAVE_CONFIG_64:
  4638. x = Decimal(10**(19*24)).__sizeof__()
  4639. y = Decimal(10**(19*25)).__sizeof__()
  4640. self.assertEqual(y, x+8)
  4641. else:
  4642. x = Decimal(10**(9*24)).__sizeof__()
  4643. y = Decimal(10**(9*25)).__sizeof__()
  4644. self.assertEqual(y, x+4)
  4645. def test_internal_use_of_overridden_methods(self):
  4646. Decimal = C.Decimal
  4647. # Unsound subtyping
  4648. class X(float):
  4649. def as_integer_ratio(self):
  4650. return 1
  4651. def __abs__(self):
  4652. return self
  4653. class Y(float):
  4654. def __abs__(self):
  4655. return [1]*200
  4656. class I(int):
  4657. def bit_length(self):
  4658. return [1]*200
  4659. class Z(float):
  4660. def as_integer_ratio(self):
  4661. return (I(1), I(1))
  4662. def __abs__(self):
  4663. return self
  4664. for cls in X, Y, Z:
  4665. self.assertEqual(Decimal.from_float(cls(101.1)),
  4666. Decimal.from_float(101.1))
  4667. # Issue 41540:
  4668. @unittest.skipIf(sys.platform.startswith("aix"),
  4669. "AIX: default ulimit: test is flaky because of extreme over-allocation")
  4670. @unittest.skipIf(is_emscripten, "Test is unstable on Emscripten")
  4671. @unittest.skipIf(check_sanitizer(address=True, memory=True),
  4672. "ASAN/MSAN sanitizer defaults to crashing "
  4673. "instead of returning NULL for malloc failure.")
  4674. def test_maxcontext_exact_arith(self):
  4675. # Make sure that exact operations do not raise MemoryError due
  4676. # to huge intermediate values when the context precision is very
  4677. # large.
  4678. # The following functions fill the available precision and are
  4679. # therefore not suitable for large precisions (by design of the
  4680. # specification).
  4681. MaxContextSkip = ['logical_invert', 'next_minus', 'next_plus',
  4682. 'logical_and', 'logical_or', 'logical_xor',
  4683. 'next_toward', 'rotate', 'shift']
  4684. Decimal = C.Decimal
  4685. Context = C.Context
  4686. localcontext = C.localcontext
  4687. # Here only some functions that are likely candidates for triggering a
  4688. # MemoryError are tested. deccheck.py has an exhaustive test.
  4689. maxcontext = Context(prec=C.MAX_PREC, Emin=C.MIN_EMIN, Emax=C.MAX_EMAX)
  4690. with localcontext(maxcontext):
  4691. self.assertEqual(Decimal(0).exp(), 1)
  4692. self.assertEqual(Decimal(1).ln(), 0)
  4693. self.assertEqual(Decimal(1).log10(), 0)
  4694. self.assertEqual(Decimal(10**2).log10(), 2)
  4695. self.assertEqual(Decimal(10**223).log10(), 223)
  4696. self.assertEqual(Decimal(10**19).logb(), 19)
  4697. self.assertEqual(Decimal(4).sqrt(), 2)
  4698. self.assertEqual(Decimal("40E9").sqrt(), Decimal('2.0E+5'))
  4699. self.assertEqual(divmod(Decimal(10), 3), (3, 1))
  4700. self.assertEqual(Decimal(10) // 3, 3)
  4701. self.assertEqual(Decimal(4) / 2, 2)
  4702. self.assertEqual(Decimal(400) ** -1, Decimal('0.0025'))
  4703. @requires_docstrings
  4704. @unittest.skipUnless(C, "test requires C version")
  4705. class SignatureTest(unittest.TestCase):
  4706. """Function signatures"""
  4707. def test_inspect_module(self):
  4708. for attr in dir(P):
  4709. if attr.startswith('_'):
  4710. continue
  4711. p_func = getattr(P, attr)
  4712. c_func = getattr(C, attr)
  4713. if (attr == 'Decimal' or attr == 'Context' or
  4714. inspect.isfunction(p_func)):
  4715. p_sig = inspect.signature(p_func)
  4716. c_sig = inspect.signature(c_func)
  4717. # parameter names:
  4718. c_names = list(c_sig.parameters.keys())
  4719. p_names = [x for x in p_sig.parameters.keys() if not
  4720. x.startswith('_')]
  4721. self.assertEqual(c_names, p_names,
  4722. msg="parameter name mismatch in %s" % p_func)
  4723. c_kind = [x.kind for x in c_sig.parameters.values()]
  4724. p_kind = [x[1].kind for x in p_sig.parameters.items() if not
  4725. x[0].startswith('_')]
  4726. # parameters:
  4727. if attr != 'setcontext':
  4728. self.assertEqual(c_kind, p_kind,
  4729. msg="parameter kind mismatch in %s" % p_func)
  4730. def test_inspect_types(self):
  4731. POS = inspect._ParameterKind.POSITIONAL_ONLY
  4732. POS_KWD = inspect._ParameterKind.POSITIONAL_OR_KEYWORD
  4733. # Type heuristic (type annotations would help!):
  4734. pdict = {C: {'other': C.Decimal(1),
  4735. 'third': C.Decimal(1),
  4736. 'x': C.Decimal(1),
  4737. 'y': C.Decimal(1),
  4738. 'z': C.Decimal(1),
  4739. 'a': C.Decimal(1),
  4740. 'b': C.Decimal(1),
  4741. 'c': C.Decimal(1),
  4742. 'exp': C.Decimal(1),
  4743. 'modulo': C.Decimal(1),
  4744. 'num': "1",
  4745. 'f': 1.0,
  4746. 'rounding': C.ROUND_HALF_UP,
  4747. 'context': C.getcontext()},
  4748. P: {'other': P.Decimal(1),
  4749. 'third': P.Decimal(1),
  4750. 'a': P.Decimal(1),
  4751. 'b': P.Decimal(1),
  4752. 'c': P.Decimal(1),
  4753. 'exp': P.Decimal(1),
  4754. 'modulo': P.Decimal(1),
  4755. 'num': "1",
  4756. 'f': 1.0,
  4757. 'rounding': P.ROUND_HALF_UP,
  4758. 'context': P.getcontext()}}
  4759. def mkargs(module, sig):
  4760. args = []
  4761. kwargs = {}
  4762. for name, param in sig.parameters.items():
  4763. if name == 'self': continue
  4764. if param.kind == POS:
  4765. args.append(pdict[module][name])
  4766. elif param.kind == POS_KWD:
  4767. kwargs[name] = pdict[module][name]
  4768. else:
  4769. raise TestFailed("unexpected parameter kind")
  4770. return args, kwargs
  4771. def tr(s):
  4772. """The C Context docstrings use 'x' in order to prevent confusion
  4773. with the article 'a' in the descriptions."""
  4774. if s == 'x': return 'a'
  4775. if s == 'y': return 'b'
  4776. if s == 'z': return 'c'
  4777. return s
  4778. def doit(ty):
  4779. p_type = getattr(P, ty)
  4780. c_type = getattr(C, ty)
  4781. for attr in dir(p_type):
  4782. if attr.startswith('_'):
  4783. continue
  4784. p_func = getattr(p_type, attr)
  4785. c_func = getattr(c_type, attr)
  4786. if inspect.isfunction(p_func):
  4787. p_sig = inspect.signature(p_func)
  4788. c_sig = inspect.signature(c_func)
  4789. # parameter names:
  4790. p_names = list(p_sig.parameters.keys())
  4791. c_names = [tr(x) for x in c_sig.parameters.keys()]
  4792. self.assertEqual(c_names, p_names,
  4793. msg="parameter name mismatch in %s" % p_func)
  4794. p_kind = [x.kind for x in p_sig.parameters.values()]
  4795. c_kind = [x.kind for x in c_sig.parameters.values()]
  4796. # 'self' parameter:
  4797. self.assertIs(p_kind[0], POS_KWD)
  4798. self.assertIs(c_kind[0], POS)
  4799. # remaining parameters:
  4800. if ty == 'Decimal':
  4801. self.assertEqual(c_kind[1:], p_kind[1:],
  4802. msg="parameter kind mismatch in %s" % p_func)
  4803. else: # Context methods are positional only in the C version.
  4804. self.assertEqual(len(c_kind), len(p_kind),
  4805. msg="parameter kind mismatch in %s" % p_func)
  4806. # Run the function:
  4807. args, kwds = mkargs(C, c_sig)
  4808. try:
  4809. getattr(c_type(9), attr)(*args, **kwds)
  4810. except Exception:
  4811. raise TestFailed("invalid signature for %s: %s %s" % (c_func, args, kwds))
  4812. args, kwds = mkargs(P, p_sig)
  4813. try:
  4814. getattr(p_type(9), attr)(*args, **kwds)
  4815. except Exception:
  4816. raise TestFailed("invalid signature for %s: %s %s" % (p_func, args, kwds))
  4817. doit('Decimal')
  4818. doit('Context')
  4819. all_tests = [
  4820. CExplicitConstructionTest, PyExplicitConstructionTest,
  4821. CImplicitConstructionTest, PyImplicitConstructionTest,
  4822. CFormatTest, PyFormatTest,
  4823. CArithmeticOperatorsTest, PyArithmeticOperatorsTest,
  4824. CThreadingTest, PyThreadingTest,
  4825. CUsabilityTest, PyUsabilityTest,
  4826. CPythonAPItests, PyPythonAPItests,
  4827. CContextAPItests, PyContextAPItests,
  4828. CContextWithStatement, PyContextWithStatement,
  4829. CContextFlags, PyContextFlags,
  4830. CSpecialContexts, PySpecialContexts,
  4831. CContextInputValidation, PyContextInputValidation,
  4832. CContextSubclassing, PyContextSubclassing,
  4833. CCoverage, PyCoverage,
  4834. CFunctionality, PyFunctionality,
  4835. CWhitebox, PyWhitebox,
  4836. CIBMTestCases, PyIBMTestCases,
  4837. ]
  4838. # Delete C tests if _decimal.so is not present.
  4839. if not C:
  4840. all_tests = all_tests[1::2]
  4841. else:
  4842. all_tests.insert(0, CheckAttributes)
  4843. all_tests.insert(1, SignatureTest)
  4844. def test_main(arith=None, verbose=None, todo_tests=None, debug=None):
  4845. """ Execute the tests.
  4846. Runs all arithmetic tests if arith is True or if the "decimal" resource
  4847. is enabled in regrtest.py
  4848. """
  4849. init(C)
  4850. init(P)
  4851. global TEST_ALL, DEBUG
  4852. TEST_ALL = arith if arith is not None else is_resource_enabled('decimal')
  4853. DEBUG = debug
  4854. if todo_tests is None:
  4855. test_classes = all_tests
  4856. else:
  4857. test_classes = [CIBMTestCases, PyIBMTestCases]
  4858. # Dynamically build custom test definition for each file in the test
  4859. # directory and add the definitions to the DecimalTest class. This
  4860. # procedure insures that new files do not get skipped.
  4861. for filename in os.listdir(directory):
  4862. if '.decTest' not in filename or filename.startswith("."):
  4863. continue
  4864. head, tail = filename.split('.')
  4865. if todo_tests is not None and head not in todo_tests:
  4866. continue
  4867. tester = lambda self, f=filename: self.eval_file(directory + f)
  4868. setattr(CIBMTestCases, 'test_' + head, tester)
  4869. setattr(PyIBMTestCases, 'test_' + head, tester)
  4870. del filename, head, tail, tester
  4871. try:
  4872. run_unittest(*test_classes)
  4873. if todo_tests is None:
  4874. from doctest import IGNORE_EXCEPTION_DETAIL
  4875. savedecimal = sys.modules['decimal']
  4876. if C:
  4877. sys.modules['decimal'] = C
  4878. run_doctest(C, verbose, optionflags=IGNORE_EXCEPTION_DETAIL)
  4879. sys.modules['decimal'] = P
  4880. run_doctest(P, verbose)
  4881. sys.modules['decimal'] = savedecimal
  4882. finally:
  4883. if C: C.setcontext(ORIGINAL_CONTEXT[C])
  4884. P.setcontext(ORIGINAL_CONTEXT[P])
  4885. if not C:
  4886. warnings.warn('C tests skipped: no module named _decimal.',
  4887. UserWarning)
  4888. if not orig_sys_decimal is sys.modules['decimal']:
  4889. raise TestFailed("Internal error: unbalanced number of changes to "
  4890. "sys.modules['decimal'].")
  4891. if __name__ == '__main__':
  4892. import optparse
  4893. p = optparse.OptionParser("test_decimal.py [--debug] [{--skip | test1 [test2 [...]]}]")
  4894. p.add_option('--debug', '-d', action='store_true', help='shows the test number and context before each test')
  4895. p.add_option('--skip', '-s', action='store_true', help='skip over 90% of the arithmetic tests')
  4896. (opt, args) = p.parse_args()
  4897. if opt.skip:
  4898. test_main(arith=False, verbose=True)
  4899. elif args:
  4900. test_main(arith=True, verbose=True, todo_tests=args, debug=opt.debug)
  4901. else:
  4902. test_main(arith=True, verbose=True)