....................................../////.===Shadow-Here===./////................................................ > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < ------------------------------------------------------------------------------------------------------------------- /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// RIFF¤ WEBPVP8 ˜ ðÑ *ôô>‘HŸK¥¤"§£±¨àð enü¹%½_F‘åè¿2ºQú³íªú`N¿­3ÿƒügµJžaÿ¯ÿ°~¼ÎùnúîÞÖô•òíôÁÉß®Sm¥Ü/ ‡ó˜f£Ùà<˜„xëJ¢Ù€SO3x<ªÔ©4¿+ç¶A`q@Ì“Úñè™ÍÿJÌ´ª-˜ÆtÊÛL]Ïq*‘Ý”ì#ŸÌÏãY]@ê`¿ /ªfkØB4·®£ó z—Üw¥Pxù–ÞLШKÇN¾AkÙTf½è'‰g gÆv›Øuh~ a˜Z— ïj*á¥t d£“uÒ ¨`K˜¹ßþ]b>˜]_ÏÔ6W—è2r4x•íÖ…"ƒÖNîä!¦å Ú}ýxGøÌ —@ ;ÆÚŠ=ɾ1ý8lªË¥ô ^yf®Œ¢u&2©nÙÇ›ñÂñŒ³ aPo['½»øFùà­+4ê“$!lövlüÞ=;N®3ð‚õ›DÉKòÞ>ÄÍ ¥ˆuߤ#ˆ$6ù™¥îЇy’ÍB¼ çxÛ;X"WL£R÷͝*ó-¶Zu}º.s¸sšXqù–DþÿvªhüïwyŸ ¯é³lÀ:KCûÄ£Ëá\…­ ~—ýóî ¼ûûÜTÓüÇy…ŽÆvc»¾×U ñ¸žþоP÷¦ó:Ò¨¨5;Ð#&#ÖúñläÿÁœ GxÉ­/ñ‡áQðìYÉtÒw޼GÔ´zàÒò ð*ëzƒ•4~H]Ø‹f ñÓÈñ`NåWçs'ÆÏW^ø¹!XžµmQ5ÃËoLœÎ: ÞËÍ¥J ù…î èo£ßPÎñ¶ž8.Œ]ʵ~5›ÙË-ù*8ÙÖß±~ ©¹rÓê‚j¶d¸{^Q'˜±Crß ÚH—#¥¥QlÀ×ëã‡DÜ«èî þ&Çæžî;ŽÏºò6ÒLÃXy&ZŒ'j‚¢Ù€IßÚù+–MGi‰*jE€‘JcÜ ÓÌ EÏÚj]o˜ Þr <¾U ûŪæÍ/šÝH¥˜b”¼ ÁñßX GP›ï2›4WŠÏà×£…íÓk†¦H·ÅíMh–*nó÷à]ÁjCº€b7<ب‹¨5車bp2:Á[UªM„QŒçiNMa#<5›áËó¸HýÊ"…×Éw¹¦ì2º–x<›»a±¸3Weü®FÝ⑱ö–î–³|LPÈ~çð~Çå‡|º kD¢µÏàÆAI %1À% ¹Ò – ”ϝS¦‰4&¶£°à Öý”û_Ò Áw°A«Å€?mÇÛgHÉ/8)á¾ÛìáöŽP í¨PŸNÙµº¦‡§Ùš"ÿ«>+ªÕ`Ê÷‡‚ß Õû˜þãÇ-PÍ.¾XV‘€ dÜ"þ4¹ ±Oú‘©t¥¦FªÄÃÄ•b‚znýu½—#cDs˜ÃiÑOˆñ×QO=*IAÊ,¶ŽZƒ;‡wøXè%EÐk:F±Ú” .Ѽ+Áu&Ç`."pÈÉw o&¿dE6‘’EqTuK@Ì¥ã™À(Êk(h‰,H}RÀIXÛš3µ1©_OqÚÒJAñ$ÊÙÜ;D3çŒ[þùœh¬Ã³™ö6ç†NY".Ú‰ï[ªŸŒ '²Ð öø_¨ÂÉ9ué¶³ÒŠõTàîMØ#û¯gN‡bÙ놚X„ö …ÉeüÌ^J ‹€.œ$Æ)βÄeæW#óüßĺŸ€ ÀzwV 9oä»f4V*uB «Ë†¹ì¯žR霓æHXa=&“I4K;¯ç‹h×·"UŠ~<•╪Vêª&ÍSÃÆÅ?ÔqÎ*mTM ˜›µwêd#[C¡©§‘D<©àb†–ÁœøvH/,í:¯( ²£|4-„Æövv„Yͼ™^Á$ˆ„¢Û[6yB.åH*V¨æ?$=˜Ñ€•ñ·­(VlŸ‘ nÀt8W÷´Bûba?q9ú¶Xƒl«ÿ\ù¶’þòUÐj/õ¢Ìµ³g$ƒÎR!¸»|Oߍë’BhîÚÑ¢ñåŒJ„®„£2Ð3•ô02Nt…!£Í]Ïc½Qÿ?ˆ<&ÃA¾Ú,JˆijÌ#5yz„‰Î|ÊŽ5QÏ:‹ÐaóVÔxW—CpeÏzÐïíçôÿÅ_[hãsÐ_/ŽTÝ?BîˆííV$<¿i>²F¬_Eß¿ †bÊŒº­ÿ®Z H“C}”¬,Mp ý/Bá£w>˜YV°aƒúh+cŠ- r/[%|üUMHäQ°X»|û/@|°¥Ð !BÔ Ç¢Ä©š+Õì D«7ìN¶ŽðÔ " ƶ’ÖçtA‰Û×}{tþz­¾GÍ›k¹OEJR$ Â׃ «ëÁ"oÉôž$oUK(Ä)Ãz³Ê-‹êN[Ò3Œñbï8P 4ƒ×q¢bo|?<ÛX¬òÄͰL–±›(™ûG?ýË©ÚÄ–ÂDØÐ_Ç¡ô ¾–ÄÏø ×e8Ë©$ÄF¹Å‹ì[©óìl:F¾f´‹‹Xì²ï®\¬ôùƒ ÿat¥óèÒùHß0äe‚;ü×h:ÆWðHž=Ã8骣"kœ'Y?³}Tûè€>?0l›e1Lòñ„aæKÆw…hÖŠùW…ÈÆÄ0ši·›[pcwËþñiêíY/~-Á5˜!¿†A›™Mÿþ(±“t@â“ö2­´TG5yé]çå僳 .·ÍïçÝ7UÚ±Ð/Nè»,_Ï ùdj7\ï Wì4›„»c¸àešg#ÒÊ⥭áØo5‘?ÌdÝô¯ ¹kzsƒ=´#ëÉK›Ø´±-¥eW?‡çßtòTã…$Ý+qÿ±ƒ÷_3Ô¥í÷:æ–ž<·Ö‡‰Å¢ š‡%Ô—utÌÈìðžgÖÀz²À—ï÷Óîäõ{K'´È÷³yaÏÁjƒô}ž§®æÊydÕÈë5¯èˆõvÕ©ã*çD„ “z„Ó‡^^xÂ3M§A´JG‚öï 3W'ˆ.OvXè¡ÊÕª?5º7†˜(˜Ç¶#çê’¶!ÌdZK§æ 0fãaN]òY³RV ™î$®K2R¨`W!1Ôó\;Ý ýB%qæK•&ÓÈe9È0êI±žeŸß -ú@žQr¦ ö4»M¼Áè¹µmw 9 EÆE_°2ó„ŸXKWÁ×Hóì^´²GѝF©óäR†¦‰ç"V»eØ<3ùd3ÿÚ¤Žú“Gi" —‘_ÙËÎ~Üö¯¥½Î»üŸEÚŽåmÞþí ;ÞólËΦMzA"Âf(´òá;Éï(/7½ûñÌ­cïÕçлþÝz¾-ÍvÑ“pH­–ðÓj$¸Äû¤‚‘ãUBË-n“2åPkS5&‹Â|+g^œ®Ì͆d!OïäîU«c;{Û!ÅŽ«ëZ9Ókóˆ]¯ƒ›né `ÇÒ+tÆš (ØKá¾—=3œ®•vuMñg²\ï Ec€ 05±d™‡×iÇ×›UúvÌ¢£Èþ¡ÕØô¶ßÎA"ß±#Ö²ˆÊŸ¦*Ä~ij|àø.-¼'»Ú¥£h ofº¦‡VsR=N½„Î v˜Z*SÌ{=jÑB‹tê…;’HžH¯8–îDù8ñ¢|Q•bÛçš–‹m³“ê¨ åÏ^m¬Žãþ©ïêO‡½6] µÆ„Ooòü ²x}N¦Ë3ïé¿»€›HA˜m%çÞ/¿í7Fø“‹léUk)É°Œµ8Q8›:ÀŠeT*šõ~ôڝG6 ¢}`ùH­–”¡k ‰P1>š†®9z11!X wKfmÁ¦xÑ,N1Q”–æB¶M…ÒÃv6SMˆhU¬ÊPŽï‘öj=·CŒ¯u¹ƒVIЃsx4’ömÛýcå¡¶7ßŠß 57^\wÒÐÆ k§h,Œý î«q^R½3]J¸ÇðN ‚çU¬ôº^Áì} ³f©Õœ§ˆã:FÄÈ‚é(€™?àýÓüè1Gô£¼éj‚OÅñ  #>×—ßtà 0G¥Åa뀐kßhc™À_ÉñÞ#±)GD" YîäË-ÿÙ̪ ¹™a¯´¢E\ÝÒö‚;™„ë]_ p8‰o¡ñ+^÷ 3‘'dT4œŽ ðVë½° :¬víÑ«£tßÚS-3¶“þ2 †üüʨòrš¹M{É_¤`Û¨0ìjœøJ‡:÷ÃáZ˜†@GP&œÑDGÏs¡þ¦þDGú‘1Yá9Ôþ¼ ûø…§÷8&–ÜÑnÄ_m®^üÆ`;ÉVÁJ£?â€-ßê}suÍ2sõA NÌúA磸‘îÿÚ»ƒìö·á¿±tÑÐ"Tÿü˜[@/äj¬€uüªìù¥Ý˜á8Ý´sõj 8@rˆð äþZÇD®ÿUÏ2ùôõrBzÆÏÞž>Ì™xœ“ wiÎ×7_… ¸ \#€MɁV¶¥üÕÿPÔ9Z‡ø§É8#H:ƒ5ÀÝå9ÍIŒ5åKÙŠ÷qÄ>1AÈøžj"µÂд/ªnÀ qªã}"iŸBå˜ÓÛŽ¦…&ݧ;G@—³b¯“•"´4í¨ôM¨åñC‹ïùÉó¯ÓsSH2Ý@ßáM‡ˆKÀªÛUeø/4\gnm¥‹ŸŒ qÄ b9ÞwÒNÏ_4Ég³ú=܆‚´ •â¥õeíþkjz>éÚyU«Íӝ݃6"8/ø{=Ô¢»G¥ äUw°W«,ô—¿ãㆅү¢³xŠUû™yŒ (øSópÐ 9\åTâ»—*oG$/×ÍT†Y¿1¤Þ¢_‡ ¼ „±ÍçèSaÓ 3ÛMÁBkxs‰’R/¡¤ˆÙçª(*õ„üXÌ´ƒ E§´¬EF"Ù”R/ÐNyÆÂ^°?™6¡œïJ·±$§?º>ÖüœcNÌù¯G ‹ñ2ЁBB„^·úìaz¨k:#¨Æ¨8LÎõލ£^§S&cŒÐU€ü(‡F±Š¼&P>8ÙÁ ‰ p5?0ÊÆƒZl¸aô š¼¡}gÿ¶zÆC²¹¬ÎÖG*HB¡O<º2#ñŒAƒ–¡B˜´É$¥›É:FÀÔx¾u?XÜÏÓvN©RS{2ʈãk9rmP¼Qq̳ è¼ÐFׄ^¡Öì fE“F4A…!ì/…¦Lƒ… … $%´¾yã@CI¬ á—3PþBÏNÿ<ý°4Ü ËÃ#ØÍ~âW«rEñw‹eùMMHß²`¬Öó½íf³:‹k˜¯÷}Z!ã¿<¥,\#öµÀ¯aÒNÆIé,Ћ–lŽ#Àæ9ÀÒS·I’½-Ïp Äz¤Š Â* ­íÄ9­< h>׍3ZkËU¹§˜ŒŠ±f­’¤º³Q ÏB?‹#µíÃ¥®@(Gs«†vI¥Mµ‹Á©e~2ú³ÁP4ìÕi‚²Ê^ö@-DþÓàlÜOÍ]n"µã:žpsŽ¢:! Aõ.ç~ÓBûH÷JCÌ]õVƒd «ú´QÙEA–¯¯Œ!.ˆˆëQ±ù œ·Ì!Õâ )ùL„ÅÀlÚè5@B…o´Æ¸XÓ&Û…O«˜”_#‡ƒ„ûÈt!¤ÁÏ›ÎÝŠ?c9 â\>lÓÁVÄÑ™£eØY]:fÝ–—ù+p{™ðè û³”g±OƒÚSù£áÁÊ„ä,ï7š²G ÕÌBk)~ÑiCµ|h#u¤¶îK¨² #²vݯGãeÖ϶ú…¾múÀ¶þÔñ‚Š9'^($¤§ò “š½{éúp÷J›ušS¹áªCÂubÃH9™D™/ZöØÁ‡¦ÝÙŸ·kð*_”.C‹{áXó€‡c¡c€§/šò/&éš÷,àéJþ‰X›fµ“C¨œ®r¬"kL‰Â_q…Z–.ÉL~O µ›zn‚¹À¦Öª7\àHµšÖ %»ÇníV[¥*Õ;ƒ#½¾HK-ÖIÊdÏEÚ#=o÷Óò³´Š: Ç?{¾+9›–‘OEáU·S€˜j"ÄaÜ ŒÛWt› á–c#a»pÔZÞdŽtWê=9éöÊ¢µ~ ë ;Öe‡Œ®:bî3±ýê¢wà¼îpêñ¹¾4 zc¾ðÖÿzdêŒÑÒŝÀ‰s6¤í³ÎÙB¿OZ”+F¤á‡3@Ñëäg©·Ž ˆèª<ù@É{&S„œÕúÀA)‰h:YÀ5^ÂÓŒ°õäU\ ùËÍû#²?Xe¬tu‰^zÒÔãë¼ÛWtEtû …‚g¶Úüâî*moGè¨7%u!]PhÏd™Ý%Îx: VÒ¦ôÊD3ÀŽKÛËãvÆî…N¯ä>Eró–ð`5 Œ%u5XkñÌ*NU%¶áœÊ:Qÿú»“úzyÏ6å-၇¾ ´ ÒÊ]y žO‘w2Äøæ…H’²f±ÎÇ.ª|¥'gîV•Ü .̘¯€šòü¤U~Ù†*¢!?ò wý,}´°ÔÞnïoKq5µb!áÓ3"vAßH¡³¡·G(ÐÎ0Îò¼MG!/ài®@—¬04*`…«é8ªøøló“ˆÊ”èù¤…ßÊoÿé'ËuÌÖ5×È¡§ˆˆfŽë9}hìâ_!!¯  B&Ëö¶‰ÀAÙNVŸ Wh›¸®XÑJì¨ú“¿÷3uj²˜¨ÍÎìë±aúŠÝå¯ð*Ó¨ôJ“yºØ)m°WýOè68†ŸÏ2—‰Ïüꪫٚ¥‹l1 ø ÏÄFjêµvÌbü¦èÝx:X±¢H=MÐß—,ˆÉÇ´(9ú¾^ÅÚ4¿m‡$âX‘å%(AlZo@½¨UOÌÕ”1ø¸jÎÀÃÃ_ µ‘Ü.œº¦Ut: Æï’!=¯uwû#,“pþÇúŒø(é@?³ü¥‘Mo §—s@Œ#)§ŒùkL}NOÆêA›¸~r½¼ÙA—HJ«eˆÖ´*¡ÓpÌŸö.m<-"³ûÈ$¬_6­åf£ïÚâj1y§ÕJ½@dÞÁr&Í\Z%D£Íñ·AZ Û³øüd/ªAi†/Й~  ‡âĮҮÏh§°b—›Û«mJžòG'[ÈYýŒ¦9psl ýÁ ®±f¦x,‰½tN ‚Xª9 ÙÖH.«Lo0×?͹m¡å†Ѽ+›2ƒF ±Ê8 7Hցϓ²Æ–m9…òŸï]Â1äN†VLâCˆU .ÿ‰Ts +ÅÎx(%¦u]6AF Š ØF鈄‘ |¢¶c±soŒ/t[a¾–û:s·`i햍ê›ËchÈ…8ßÀUÜewŒðNOƒõD%q#éû\9¤x¹&UE×G¥ Í—™$ð E6-‡¼!ýpãÔM˜ Âsìe¯ñµK¢Ç¡ùôléœ4Ö£”À Š®Ðc ^¨À}ÙËŸ§›ºê{ÊuÉC ×Sr€¤’fÉ*j!úÓ’Gsùìoîßîn%ò· àc Wp÷$¨˜)û»H ×8ŽÒ€Zj¤3ÀÙºY'Ql¦py{-6íÔCeiØp‘‡XÊîÆUߢ܂ž£Xé¼Y8þ©ëgñß}é.ÎógÒ„ÃØËø¯»™§Xýy M%@NŠ À(~áÐvu7&•,Ù˜ó€uP‡^^®=_E„jt’ 403WebShell
403Webshell
Server IP : 198.54.126.4  /  Your IP : 216.73.216.178
Web Server : Apache
System : Linux host55.registrar-servers.com 4.18.0-513.18.1.lve.2.el8.x86_64 #1 SMP Sat Mar 30 15:36:11 UTC 2024 x86_64
User : aeaw ( 7508)
PHP Version : 8.1.33
Disable Function : NONE
MySQL : OFF  |  cURL : ON  |  WGET : ON  |  Perl : ON  |  Python : ON  |  Sudo : OFF  |  Pkexec : OFF
Directory :  /opt/cloudlinux/venv/lib/python3.11/site-packages/numpy/array_api/tests/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

Current File : /opt/cloudlinux/venv/lib/python3.11/site-packages/numpy/array_api/tests//test_array_object.py
import operator

from numpy.testing import assert_raises, suppress_warnings
import numpy as np
import pytest

from .. import ones, asarray, reshape, result_type, all, equal
from .._array_object import Array
from .._dtypes import (
    _all_dtypes,
    _boolean_dtypes,
    _real_floating_dtypes,
    _floating_dtypes,
    _complex_floating_dtypes,
    _integer_dtypes,
    _integer_or_boolean_dtypes,
    _real_numeric_dtypes,
    _numeric_dtypes,
    int8,
    int16,
    int32,
    int64,
    uint64,
    bool as bool_,
)


def test_validate_index():
    # The indexing tests in the official array API test suite test that the
    # array object correctly handles the subset of indices that are required
    # by the spec. But the NumPy array API implementation specifically
    # disallows any index not required by the spec, via Array._validate_index.
    # This test focuses on testing that non-valid indices are correctly
    # rejected. See
    # https://data-apis.org/array-api/latest/API_specification/indexing.html
    # and the docstring of Array._validate_index for the exact indexing
    # behavior that should be allowed. This does not test indices that are
    # already invalid in NumPy itself because Array will generally just pass
    # such indices directly to the underlying np.ndarray.

    a = ones((3, 4))

    # Out of bounds slices are not allowed
    assert_raises(IndexError, lambda: a[:4])
    assert_raises(IndexError, lambda: a[:-4])
    assert_raises(IndexError, lambda: a[:3:-1])
    assert_raises(IndexError, lambda: a[:-5:-1])
    assert_raises(IndexError, lambda: a[4:])
    assert_raises(IndexError, lambda: a[-4:])
    assert_raises(IndexError, lambda: a[4::-1])
    assert_raises(IndexError, lambda: a[-4::-1])

    assert_raises(IndexError, lambda: a[...,:5])
    assert_raises(IndexError, lambda: a[...,:-5])
    assert_raises(IndexError, lambda: a[...,:5:-1])
    assert_raises(IndexError, lambda: a[...,:-6:-1])
    assert_raises(IndexError, lambda: a[...,5:])
    assert_raises(IndexError, lambda: a[...,-5:])
    assert_raises(IndexError, lambda: a[...,5::-1])
    assert_raises(IndexError, lambda: a[...,-5::-1])

    # Boolean indices cannot be part of a larger tuple index
    assert_raises(IndexError, lambda: a[a[:,0]==1,0])
    assert_raises(IndexError, lambda: a[a[:,0]==1,...])
    assert_raises(IndexError, lambda: a[..., a[0]==1])
    assert_raises(IndexError, lambda: a[[True, True, True]])
    assert_raises(IndexError, lambda: a[(True, True, True),])

    # Integer array indices are not allowed (except for 0-D)
    idx = asarray([[0, 1]])
    assert_raises(IndexError, lambda: a[idx])
    assert_raises(IndexError, lambda: a[idx,])
    assert_raises(IndexError, lambda: a[[0, 1]])
    assert_raises(IndexError, lambda: a[(0, 1), (0, 1)])
    assert_raises(IndexError, lambda: a[[0, 1]])
    assert_raises(IndexError, lambda: a[np.array([[0, 1]])])

    # Multiaxis indices must contain exactly as many indices as dimensions
    assert_raises(IndexError, lambda: a[()])
    assert_raises(IndexError, lambda: a[0,])
    assert_raises(IndexError, lambda: a[0])
    assert_raises(IndexError, lambda: a[:])

def test_operators():
    # For every operator, we test that it works for the required type
    # combinations and raises TypeError otherwise
    binary_op_dtypes = {
        "__add__": "numeric",
        "__and__": "integer_or_boolean",
        "__eq__": "all",
        "__floordiv__": "real numeric",
        "__ge__": "real numeric",
        "__gt__": "real numeric",
        "__le__": "real numeric",
        "__lshift__": "integer",
        "__lt__": "real numeric",
        "__mod__": "real numeric",
        "__mul__": "numeric",
        "__ne__": "all",
        "__or__": "integer_or_boolean",
        "__pow__": "numeric",
        "__rshift__": "integer",
        "__sub__": "numeric",
        "__truediv__": "floating",
        "__xor__": "integer_or_boolean",
    }
    # Recompute each time because of in-place ops
    def _array_vals():
        for d in _integer_dtypes:
            yield asarray(1, dtype=d)
        for d in _boolean_dtypes:
            yield asarray(False, dtype=d)
        for d in _floating_dtypes:
            yield asarray(1.0, dtype=d)


    BIG_INT = int(1e30)
    for op, dtypes in binary_op_dtypes.items():
        ops = [op]
        if op not in ["__eq__", "__ne__", "__le__", "__ge__", "__lt__", "__gt__"]:
            rop = "__r" + op[2:]
            iop = "__i" + op[2:]
            ops += [rop, iop]
        for s in [1, 1.0, 1j, BIG_INT, False]:
            for _op in ops:
                for a in _array_vals():
                    # Test array op scalar. From the spec, the following combinations
                    # are supported:

                    # - Python bool for a bool array dtype,
                    # - a Python int within the bounds of the given dtype for integer array dtypes,
                    # - a Python int or float for real floating-point array dtypes
                    # - a Python int, float, or complex for complex floating-point array dtypes

                    if ((dtypes == "all"
                         or dtypes == "numeric" and a.dtype in _numeric_dtypes
                         or dtypes == "real numeric" and a.dtype in _real_numeric_dtypes
                         or dtypes == "integer" and a.dtype in _integer_dtypes
                         or dtypes == "integer_or_boolean" and a.dtype in _integer_or_boolean_dtypes
                         or dtypes == "boolean" and a.dtype in _boolean_dtypes
                         or dtypes == "floating" and a.dtype in _floating_dtypes
                        )
                        # bool is a subtype of int, which is why we avoid
                        # isinstance here.
                        and (a.dtype in _boolean_dtypes and type(s) == bool
                             or a.dtype in _integer_dtypes and type(s) == int
                             or a.dtype in _real_floating_dtypes and type(s) in [float, int]
                             or a.dtype in _complex_floating_dtypes and type(s) in [complex, float, int]
                        )):
                        if a.dtype in _integer_dtypes and s == BIG_INT:
                            assert_raises(OverflowError, lambda: getattr(a, _op)(s))
                        else:
                            # Only test for no error
                            with suppress_warnings() as sup:
                                # ignore warnings from pow(BIG_INT)
                                sup.filter(RuntimeWarning,
                                           "invalid value encountered in power")
                                getattr(a, _op)(s)
                    else:
                        assert_raises(TypeError, lambda: getattr(a, _op)(s))

                # Test array op array.
                for _op in ops:
                    for x in _array_vals():
                        for y in _array_vals():
                            # See the promotion table in NEP 47 or the array
                            # API spec page on type promotion. Mixed kind
                            # promotion is not defined.
                            if (x.dtype == uint64 and y.dtype in [int8, int16, int32, int64]
                                or y.dtype == uint64 and x.dtype in [int8, int16, int32, int64]
                                or x.dtype in _integer_dtypes and y.dtype not in _integer_dtypes
                                or y.dtype in _integer_dtypes and x.dtype not in _integer_dtypes
                                or x.dtype in _boolean_dtypes and y.dtype not in _boolean_dtypes
                                or y.dtype in _boolean_dtypes and x.dtype not in _boolean_dtypes
                                or x.dtype in _floating_dtypes and y.dtype not in _floating_dtypes
                                or y.dtype in _floating_dtypes and x.dtype not in _floating_dtypes
                                ):
                                assert_raises(TypeError, lambda: getattr(x, _op)(y))
                            # Ensure in-place operators only promote to the same dtype as the left operand.
                            elif (
                                _op.startswith("__i")
                                and result_type(x.dtype, y.dtype) != x.dtype
                            ):
                                assert_raises(TypeError, lambda: getattr(x, _op)(y))
                            # Ensure only those dtypes that are required for every operator are allowed.
                            elif (dtypes == "all" and (x.dtype in _boolean_dtypes and y.dtype in _boolean_dtypes
                                                      or x.dtype in _numeric_dtypes and y.dtype in _numeric_dtypes)
                                or (dtypes == "real numeric" and x.dtype in _real_numeric_dtypes and y.dtype in _real_numeric_dtypes)
                                or (dtypes == "numeric" and x.dtype in _numeric_dtypes and y.dtype in _numeric_dtypes)
                                or dtypes == "integer" and x.dtype in _integer_dtypes and y.dtype in _integer_dtypes
                                or dtypes == "integer_or_boolean" and (x.dtype in _integer_dtypes and y.dtype in _integer_dtypes
                                                                       or x.dtype in _boolean_dtypes and y.dtype in _boolean_dtypes)
                                or dtypes == "boolean" and x.dtype in _boolean_dtypes and y.dtype in _boolean_dtypes
                                or dtypes == "floating" and x.dtype in _floating_dtypes and y.dtype in _floating_dtypes
                            ):
                                getattr(x, _op)(y)
                            else:
                                assert_raises(TypeError, lambda: getattr(x, _op)(y))

    unary_op_dtypes = {
        "__abs__": "numeric",
        "__invert__": "integer_or_boolean",
        "__neg__": "numeric",
        "__pos__": "numeric",
    }
    for op, dtypes in unary_op_dtypes.items():
        for a in _array_vals():
            if (
                dtypes == "numeric"
                and a.dtype in _numeric_dtypes
                or dtypes == "integer_or_boolean"
                and a.dtype in _integer_or_boolean_dtypes
            ):
                # Only test for no error
                getattr(a, op)()
            else:
                assert_raises(TypeError, lambda: getattr(a, op)())

    # Finally, matmul() must be tested separately, because it works a bit
    # different from the other operations.
    def _matmul_array_vals():
        for a in _array_vals():
            yield a
        for d in _all_dtypes:
            yield ones((3, 4), dtype=d)
            yield ones((4, 2), dtype=d)
            yield ones((4, 4), dtype=d)

    # Scalars always error
    for _op in ["__matmul__", "__rmatmul__", "__imatmul__"]:
        for s in [1, 1.0, False]:
            for a in _matmul_array_vals():
                if (type(s) in [float, int] and a.dtype in _floating_dtypes
                    or type(s) == int and a.dtype in _integer_dtypes):
                    # Type promotion is valid, but @ is not allowed on 0-D
                    # inputs, so the error is a ValueError
                    assert_raises(ValueError, lambda: getattr(a, _op)(s))
                else:
                    assert_raises(TypeError, lambda: getattr(a, _op)(s))

    for x in _matmul_array_vals():
        for y in _matmul_array_vals():
            if (x.dtype == uint64 and y.dtype in [int8, int16, int32, int64]
                or y.dtype == uint64 and x.dtype in [int8, int16, int32, int64]
                or x.dtype in _integer_dtypes and y.dtype not in _integer_dtypes
                or y.dtype in _integer_dtypes and x.dtype not in _integer_dtypes
                or x.dtype in _floating_dtypes and y.dtype not in _floating_dtypes
                or y.dtype in _floating_dtypes and x.dtype not in _floating_dtypes
                or x.dtype in _boolean_dtypes
                or y.dtype in _boolean_dtypes
                ):
                assert_raises(TypeError, lambda: x.__matmul__(y))
                assert_raises(TypeError, lambda: y.__rmatmul__(x))
                assert_raises(TypeError, lambda: x.__imatmul__(y))
            elif x.shape == () or y.shape == () or x.shape[1] != y.shape[0]:
                assert_raises(ValueError, lambda: x.__matmul__(y))
                assert_raises(ValueError, lambda: y.__rmatmul__(x))
                if result_type(x.dtype, y.dtype) != x.dtype:
                    assert_raises(TypeError, lambda: x.__imatmul__(y))
                else:
                    assert_raises(ValueError, lambda: x.__imatmul__(y))
            else:
                x.__matmul__(y)
                y.__rmatmul__(x)
                if result_type(x.dtype, y.dtype) != x.dtype:
                    assert_raises(TypeError, lambda: x.__imatmul__(y))
                elif y.shape[0] != y.shape[1]:
                    # This one fails because x @ y has a different shape from x
                    assert_raises(ValueError, lambda: x.__imatmul__(y))
                else:
                    x.__imatmul__(y)


def test_python_scalar_construtors():
    b = asarray(False)
    i = asarray(0)
    f = asarray(0.0)
    c = asarray(0j)

    assert bool(b) == False
    assert int(i) == 0
    assert float(f) == 0.0
    assert operator.index(i) == 0

    # bool/int/float/complex should only be allowed on 0-D arrays.
    assert_raises(TypeError, lambda: bool(asarray([False])))
    assert_raises(TypeError, lambda: int(asarray([0])))
    assert_raises(TypeError, lambda: float(asarray([0.0])))
    assert_raises(TypeError, lambda: complex(asarray([0j])))
    assert_raises(TypeError, lambda: operator.index(asarray([0])))

    # bool should work on all types of arrays
    assert bool(b) is bool(i) is bool(f) is bool(c) is False

    # int should fail on complex arrays
    assert int(b) == int(i) == int(f) == 0
    assert_raises(TypeError, lambda: int(c))

    # float should fail on complex arrays
    assert float(b) == float(i) == float(f) == 0.0
    assert_raises(TypeError, lambda: float(c))

    # complex should work on all types of arrays
    assert complex(b) == complex(i) == complex(f) == complex(c) == 0j

    # index should only work on integer arrays
    assert operator.index(i) == 0
    assert_raises(TypeError, lambda: operator.index(b))
    assert_raises(TypeError, lambda: operator.index(f))
    assert_raises(TypeError, lambda: operator.index(c))


def test_device_property():
    a = ones((3, 4))
    assert a.device == 'cpu'

    assert all(equal(a.to_device('cpu'), a))
    assert_raises(ValueError, lambda: a.to_device('gpu'))

    assert all(equal(asarray(a, device='cpu'), a))
    assert_raises(ValueError, lambda: asarray(a, device='gpu'))

def test_array_properties():
    a = ones((1, 2, 3))
    b = ones((2, 3))
    assert_raises(ValueError, lambda: a.T)

    assert isinstance(b.T, Array)
    assert b.T.shape == (3, 2)

    assert isinstance(a.mT, Array)
    assert a.mT.shape == (1, 3, 2)
    assert isinstance(b.mT, Array)
    assert b.mT.shape == (3, 2)

def test___array__():
    a = ones((2, 3), dtype=int16)
    assert np.asarray(a) is a._array
    b = np.asarray(a, dtype=np.float64)
    assert np.all(np.equal(b, np.ones((2, 3), dtype=np.float64)))
    assert b.dtype == np.float64

def test_allow_newaxis():
    a = ones(5)
    indexed_a = a[None, :]
    assert indexed_a.shape == (1, 5)

def test_disallow_flat_indexing_with_newaxis():
    a = ones((3, 3, 3))
    with pytest.raises(IndexError):
        a[None, 0, 0]

def test_disallow_mask_with_newaxis():
    a = ones((3, 3, 3))
    with pytest.raises(IndexError):
        a[None, asarray(True)]

@pytest.mark.parametrize("shape", [(), (5,), (3, 3, 3)])
@pytest.mark.parametrize("index", ["string", False, True])
def test_error_on_invalid_index(shape, index):
    a = ones(shape)
    with pytest.raises(IndexError):
        a[index]

def test_mask_0d_array_without_errors():
    a = ones(())
    a[asarray(True)]

@pytest.mark.parametrize(
    "i", [slice(5), slice(5, 0), asarray(True), asarray([0, 1])]
)
def test_error_on_invalid_index_with_ellipsis(i):
    a = ones((3, 3, 3))
    with pytest.raises(IndexError):
        a[..., i]
    with pytest.raises(IndexError):
        a[i, ...]

def test_array_keys_use_private_array():
    """
    Indexing operations convert array keys before indexing the internal array

    Fails when array_api array keys are not converted into NumPy-proper arrays
    in __getitem__(). This is achieved by passing array_api arrays with 0-sized
    dimensions, which NumPy-proper treats erroneously - not sure why!

    TODO: Find and use appropriate __setitem__() case.
    """
    a = ones((0, 0), dtype=bool_)
    assert a[a].shape == (0,)

    a = ones((0,), dtype=bool_)
    key = ones((0, 0), dtype=bool_)
    with pytest.raises(IndexError):
        a[key]

Youez - 2016 - github.com/yon3zu
LinuXploit