GIF89a=( õ' 7IAXKgNgYvYx\%wh…hŽth%ˆs%—x¨}9®Œ©€&©‰%¶†(¹–.¹5·œD¹&Çš)ÇŸ5ǘ;Í£*È¡&Õ²)ׯ7×µ<Ñ»4ï°3ø‘HÖ§KͯT÷¨Yÿšqÿ»qÿÔFØ !ù ' !ÿ NETSCAPE2.0 , =( þÀ“pH,È¤rÉl:ŸÐ¨tJ­Z¯Ø¬vËíz¿à°xL.›Ïè´zÍn»ßð¸|N¯Ûïø¼~Ïïûÿ€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§gª«ªE¯°¨¬ª±²Œ¹º¹E¾­”´ÂB¶¯ §Åȸ»ÑD¾¿Á•ÄÅ®° ÝH¾ÒLÀÆDÙ«D¶BÝïðÀ¾DÑÑÔTÌÍíH òGö¨A RÎڐ |¥ ٭&ºìE8œ¹kGÔAÞpx­a¶­ã R2XB®åE8I€Õ6Xî:vT)äžþÀq¦è³¥ì仕F~%xñ  4#ZÔ‰O|-4Bs‘X:= QÉ œš lºÒyXJŠGȦ|s hÏíK–3l7·B|¥$'7Jީܪ‰‡àá”Dæn=Pƒ ¤Òëí‰`䌨ljóá¯Éüv>á–Á¼5 ½.69ûϸd«­ºÀûnlv©‹ªîf{¬ÜãPbŸ  l5‘ޝpß ´ ˜3aÅùäI«O’ý·‘áÞ‡˜¾Æ‚ÙÏiÇÿ‹Àƒ #öó)pâš Þ½ ‘Ý{ó)vmÞü%D~ 6f s}ŃƒDØW Eþ`‡þ À…L8xá†ç˜{)x`X/> Ì}mø‚–RØ‘*|`D=‚Ø_ ^ð5 !_…'aä“OÚ—7âcð`D”Cx`ÝÂ¥ä‹éY¹—F¼¤¥Š?¡Õ™ n@`} lď’ÄÉ@4>ñd œ à‘vÒxNÃ×™@žd=ˆgsžG±æ ´²æud &p8Qñ)ˆ«lXD©øÜéAžHìySun jª×k*D¤LH] †¦§C™Jä–´Xb~ʪwStŽ6K,°£qÁœ:9ت:¨þªl¨@¡`‚ûÚ ».Û¬¯t‹ÆSÉ[:°=Š‹„‘Nåû”Ìî{¿ÂA ‡Rà›ÀÙ6úë°Ÿð0Ä_ ½;ÃϱîÉì^ÇÛÇ#Ëë¼ôº!±Ä˜íUîÅÇ;0L1óÁµö«p% AÀºU̬ݵ¼á%霼€‡¯Á~`ÏG¯»À× ­²± =4ªnpð3¾¤³¯­ü¾¦îuÙuµÙ®|%2ÊIÿür¦#0·ÔJ``8È@S@5ê¢ ö×Þ^`8EÜ]ý.뜃Âç 7 ú ȉÞj œ½Dç zý¸iþœÑÙûÄë!ˆÞÀl§Ïw‹*DçI€nEX¯¬¼ &A¬Go¼QföõFç°¯;é¦÷îŽêJ°îúôF5¡ÌQ|îúöXªæ»TÁÏyñêï]ê² o óÎC=öõ›ÒÓPB@ D×½œä(>èCÂxŽ`±«Ÿ–JЀ»Û á¤±p+eE0`ëŽ`A Ú/NE€Ø†À9‚@¤à H½7”à‡%B‰`Àl*ƒó‘–‡8 2ñ%¸ —€:Ù1Á‰E¸àux%nP1ð!‘ðC)¾P81lÑɸF#ˆ€{´âé°ÈB„0>±û °b¡Š´±O‚3È–Ù()yRpbµ¨E.Z‘D8ÊH@% òŒx+%Ù˜Æcü »¸˜fõ¬b·d`Fê™8èXH"ÉÈ-±|1Ô6iI, 2““¬$+](A*jÐ QTÂo‰.ÛU슬Œã„Ž`¯SN¡–¶Äåyše¯ª’­¬‚´b¦Éož œ)åyâ@Ì®3 ÎtT̉°&Ø+žLÀf"Ø-|žçÔ>‡Ðv¦Ðžì\‚ Q1)Ž@Žh#aP72”ˆ™¨$‚ !ù " , =( …7IAXG]KgNgYvYxR"k\%w]'}hŽth%ˆg+ˆs%—r.—m3šx3˜x¨}9®€&©€+¨‡7§‰%¶†(¹–.¹œD¹&ǘ;Í•&ײ)×»4ïÌ6ò§KÍ þ@‘pH,È¤rÉl:ŸÐ¨tJ­Z¯Ø¬vËíz¿à°xL.›Ïè´zÍn»ßð¸|N¯Ûïø¼~Ïïûÿ€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§g «¬ E ±± ¨­¶°ººE Á´”·®C¬²§Ç¶Œ»ÓDÃÕƷ¯Ê±H½ºM×ÁGÚ¬D¶BËÁ½î½DÓôTÏÛßîG»ôõC×CÌ l&âž:'òtU³6ɹ#·Ø)€'Ü.6±&ëÍÈ» K(8p0N?!æ2"ÛˆNIJX>R¼ÐO‚M '¡¨2¸*Ÿþ>#n↠å@‚<[:¡Iïf’ ¤TÚ˘CdbÜÙ“[«ŽEú5MBo¤×@€`@„€Êt W-3 ¶Ÿ¡BíêäjIÝ…Eò9[T…$íêﯧ„…•s»Óȳ¹€ÅÚdc®UUρ#±Ùïldj?´í¼²`\ŽÁðÞu|3'ÖŒ]ë6 ¶S#²‡˜FKLÈ *N E´‘áäŠ$˜›eÄYD„ºq«.è촁ƒs \-ÔjA 9²õ÷å- üúM[Âx(ís÷ì®x€|í¡Ù’p¦‚ ŽkÛTÇDpE@WÜ ²Ç]kŠ1¨ þ€·Yb ÓÁ‰l°*n0 ç™—žzBdОu¾7ĉBl€â‰-ºx~|UåU‰  h*Hœ|e"#"?vpÄiŠe6^ˆ„+qâŠm8 #VÇá ‘å–ÄV„œ|Аè•m"сœn|@›U¶ÆÎž—Špb¥G¨ED”€±Úê2FÌIç? >Éxå Œ± ¡¤„%‘žjŸ‘ꄯ<Ìaà9ijÐ2˜D¦È&›†Z`‚å]wþ¼Â:ç6àB¤7eFJ|õÒ§Õ,¨äàFÇ®cS·Ê¶+B°,‘Þ˜ºNûãØ>PADÌHD¹æž«ÄÀnÌ¥}­#Ë’ë QÀÉSÌÂÇ2ÌXÀ{æk²lQÁ2«ÊðÀ¯w|2Í h‹ÄÂG€,m¾¶ë3ÐÙ6-´ÅE¬L°ÆIij*K½ÀÇqï`DwVÍQXœÚÔpeœ±¬Ñ q˜§Tœ½µƒ°Œìu Â<¶aØ*At¯lmEØ ü ôÛN[P1ÔÛ¦­±$ÜÆ@`ùåDpy¶yXvCAyåB`ŽD¶ 0QwG#¯ æš[^Äþ $ÀÓÝǦ{„L™[±úKÄgÌ;ï£S~¹ìGX.ôgoT.»åˆ°ùŸûù¡?1zö¦Ÿž:ÅgÁ|ìL¹ „®£œŠ‚à0œ]PÁ^p F<"•ç?!,ñ‡N4—…PÄ Á„ö¨Û:Tè@hÀ‹%táÿ:ø-žI<`þ‹p I….)^ 40D#p@ƒj4–؀:²‰1Øâr˜¼F2oW¼#Z†;$Q q” ‘ ÂK¦ñNl#29 !’F@¥Bh·ᏀL!—XFóLH‘Kh¤.«hE&JòG¨¥<™WN!€ÑÙÚˆY„@†>Œž19J" 2,/ &.GXB%ÌRÈ9B6¹W]’î×ÔW¥’IÎ$ ñ‹ÓŒE8YÆ ¼³™ñA5“à®Q.aŸB€&Ø©³ JÁ—! ¦t)K%tœ-¦JF bòNMxLôþ)ÐR¸Ð™‘ èÝ6‘O!THÌ„HÛ ‰ !ù ) , =( …AXKgNgYvYxR"k\%wh…hŽh%ˆg+ˆs%—r.—x3˜x¨}9®€&©€+¨Œ,©‡7§‰%¶†(¹–.¹5·&Çš)ǘ;Í•&×£*Ȳ)ׯ7×»4ï°3øÌ6ò‘HÖ§KÍ»Hó¯T÷¨Yÿ»qÿÇhÿ þÀ”pH,È¤rÉl:ŸÐ¨tJ­Z¯Ø¬vËíz¿à°xL.›Ïè´zÍn»ßð¸|N¯Ûïø¼~Ïïûÿ€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§g ª« E$±²¨ª­ · °²½$E$ÂÕ««D· Í ¿¦Ç¶¸ÌŒ¾³CÃÅÆ E ééH½MÛÂGâªD­ çBêêϾD²ÒaÀà€Š1r­ðÓ¤ ÔožzU!L˜C'¾yW½UGtäÇïÙllê0×àÂuGþ)AÀs[þ·xì ÁxO%ƒûX2ó—  P£n›R/¡ÑšHše+êDm?# —‘Ç£6¡8íJ¡ŸâDiäªM¥Ö„ôj“¬¹£5oQ7°- <‡ *´lãÓŒ2r/a!l)dÈ A™ÈE¢ôÔ͆…ð ;Ö˜c ¡%ß‚’Ùˆâ¸b½—pe~C"BíëÚHïeF2§æŠ8qb t_`urŠeü wÅu3êæPv§h•"ß`íÍxçLĹÜÖ3á  ~Öº“®›¸ÏMDfJÙ °„ÛµáWõ%§œ‚à©–‚X ÓØ)@®Ñ›Eþ´wëuÅSxb8y\mÖzœ¥§ZbºE—ÂLªÌw!y(>¡™wú=Ç|ÅÝs¢d €CÁW)HÜcC$€L Ä7„r.á\{)@ð` @ äXÈ$PD” `šaG:§æˆOˆ72EÐamn]ù"ŒcÊxÑŒ° &dR8`g«iÙŸLR!¦P …d’ä¡“¦ðÎTƒ¦ià|À _ ¥ Qi#¦Šg›Æ ›noMµ ›V ã£)p ç£ÎW…š=Âeªk§†j„ ´®1ß²sÉxéW«jšl|0¯B0Û, \jÛ´›6±¬¶C ÛíWþï|ëÙ‹¸ñzĸV {ì;Ýñn¼òVˆm³I¼³.Ðã¤PN¥ ²µ¼„µCã+¹ÍByî£Ñ¾HŸ›ëê 7ìYÆFTk¨SaoaY$Dµœìï¿Ã29RÈkt Çïfñ ÇÒ:ÀÐSp¹3ÇI¨â¥DZÄ ü9Ïýögñ½­uÔ*3)O‘˜Ö[_hv ,àî×Et Ÿé¶BH€ Õ[ü±64M@ÔSÌM7dÐl5-ÄÙU܍´©zߌ3Ô€3ž„ „ ¶ÛPô½5×g› êÚ˜kN„Ý…0Îj4€Ìë°“#{þÕ3S2çKÜ'ợlø¼Ú2K{° {Û¶?žm𸧠ËI¼nEò='êüóºè^üæÃ_Û=°óž‚ì#Oý¿Í'¡½áo..ÏYìnüñCœO±Áa¿¢Kô½o,üÄËbö²çºíï{ËC Ú— "”Ï{ËK ÍÒw„õ±Oz dÕ¨à:$ ƒô—«v»] A#ð «€¿šéz)Rx׿ˆ¥‚d``èw-îyÏf×K!ð€þ­Ð|ìPľ„=Ì`ý(f” 'Pa ¥ÐBJa%Ðâf§„%Š¡}FàáÝ×6>ÉäŠG"éŽè=ø!oа^FP¼Ø©Q„ÀCÙÁ`(Ž\ÄÝ® ©Â$<n@dÄ E#ììUÒI! ‚#lù‹`k¦ÐÇ'Rró’ZýNBÈMF Í[¤+‹ðɈ-áwj¨¥þ8¾rá ,VÂh„"|½œ=×G_¦Ñ™EØ 0i*%̲˜Æda0mV‚k¾)›;„&6 p>ÓjK “¦Ç# âDÂ:ûc?:R Ó¬fÞéI-Ì“•Ã<ä=™Ï7˜3œ¨˜c2ŒW ,ˆ”8(T™P‰F¡Jhç"‚ ; 403WebShell
403Webshell
Server IP : 172.67.177.218  /  Your IP : 216.73.216.195
Web Server : LiteSpeed
System : Linux premium229.web-hosting.com 4.18.0-553.45.1.lve.el8.x86_64 #1 SMP Wed Mar 26 12:08:09 UTC 2025 x86_64
User : akhalid ( 749)
PHP Version : 8.3.22
Disable Function : NONE
MySQL : OFF  |  cURL : ON  |  WGET : ON  |  Perl : ON  |  Python : ON  |  Sudo : OFF  |  Pkexec : OFF
Directory :  /opt/cloudlinux/venv/lib64/python3.11/site-packages/testfixtures/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

Current File : /opt/cloudlinux/venv/lib64/python3.11/site-packages/testfixtures/datetime.py
from calendar import timegm
from datetime import datetime, timedelta, date, tzinfo as TZInfo
from typing import Optional, Callable, Type, Tuple, Dict, Any, cast, overload


class Queue(list):

    delta: float
    delta_delta: float
    delta_type: str

    def __init__(self, delta: Optional[float], delta_delta: float, delta_type: str):
        super().__init__()
        if delta is None:
            self.delta = 0
            self.delta_delta = delta_delta
        else:
            self.delta = delta
            self.delta_delta = 0
        self.delta_type = delta_type

    def advance_next(self, delta: timedelta) -> None:
        self[-1] += delta

    def next(self) -> 'MockedCurrent':
        instance = self.pop(0)
        if not self:
            self.delta += self.delta_delta
            n = instance + timedelta(**{self.delta_type: self.delta})
            self.append(n)
        return instance


class MockedCurrent:

    _mock_queue: Queue
    _mock_base_class: Type
    _mock_class: Type
    _mock_tzinfo: Optional[TZInfo]
    _mock_date_type: Type[date]
    _correct_mock_type: Callable = None

    def __init_subclass__(
            cls,
            concrete: bool = False,
            queue: Queue = None,
            strict: bool = None,
            tzinfo: TZInfo = None,
            date_type: Type[date] = None
    ):
        if concrete:
            cls._mock_queue = queue
            cls._mock_base_class = cls.__bases__[0].__bases__[1]
            cls._mock_class = cls if strict else cls._mock_base_class
            cls._mock_tzinfo = tzinfo
            cls._mock_date_type = date_type

    @classmethod
    def add(cls, *args, **kw):
        if 'tzinfo' in kw or len(args) > 7:
            raise TypeError('Cannot add using tzinfo on %s' % cls.__name__)
        if args and isinstance(args[0], cls._mock_base_class):
            instance = args[0]
            instance_tzinfo = getattr(instance, 'tzinfo', None)
            if instance_tzinfo:
                if instance_tzinfo != cls._mock_tzinfo:
                    raise ValueError(
                        'Cannot add %s with tzinfo of %s as configured to use %s' % (
                            instance.__class__.__name__, instance_tzinfo, cls._mock_tzinfo
                        ))
                instance = instance.replace(tzinfo=None)
            if cls._correct_mock_type:
                instance = cls._correct_mock_type(instance)
        else:
            instance = cls(*args, **kw)
        cls._mock_queue.append(instance)

    @classmethod
    def set(cls, *args, **kw) -> None:
        cls._mock_queue.clear()
        cls.add(*args, **kw)

    @classmethod
    def tick(cls, *args, **kw) -> None:
        if kw:
            delta = timedelta(**kw)
        else:
            delta, = args
        cls._mock_queue.advance_next(delta)

    def __add__(self, other) -> 'MockedCurrent':
        instance = super().__add__(other)
        if self._correct_mock_type:
            instance = self._correct_mock_type(instance)
        return instance

    def __new__(cls, *args, **kw):
        if cls is cls._mock_class:
            return super().__new__(cls, *args, **kw)
        else:
            return cls._mock_class(*args, **kw)


def mock_factory(
        type_name: str,
        mock_class: Type[MockedCurrent],
        default: Tuple[int, ...],
        args: tuple,
        kw: Dict[str, Any],
        delta: Optional[float],
        delta_type: str,
        delta_delta: float = 1,
        date_type: Type[date] = None,
        tzinfo: TZInfo = None,
        strict: bool = False
):
    cls = cast(Type[MockedCurrent], type(
        type_name,
        (mock_class,),
        {},
        concrete=True,
        queue=Queue(delta, delta_delta, delta_type),
        strict=strict,
        tzinfo=tzinfo,
        date_type=date_type,
    ))

    if args != (None,):
        if not (args or kw):
            args = default
        cls.add(*args, **kw)

    return cls


class MockDateTime(MockedCurrent, datetime):

    @overload
    @classmethod
    def add(
            cls,
            year: int,
            month: int,
            day: int,
            hour: int = ...,
            minute: int = ...,
            second: int = ...,
            microsecond: int = ...,
            tzinfo: TZInfo = ...,
    ) -> None:
        ...

    @overload
    @classmethod
    def add(
            cls,
            instance: datetime,
    ) -> None:
        ...

    @classmethod
    def add(cls, *args, **kw):
        """
        This will add the :class:`datetime.datetime` created from the
        supplied parameters to the queue of datetimes to be returned by
        :meth:`~MockDateTime.now` or :meth:`~MockDateTime.utcnow`. An instance
        of :class:`~datetime.datetime` may also be passed as a single
        positional argument.
        """
        return super().add(*args, **kw)

    @overload
    @classmethod
    def set(
            cls,
            year: int,
            month: int,
            day: int,
            hour: int = ...,
            minute: int = ...,
            second: int = ...,
            microsecond: int = ...,
            tzinfo: TZInfo = ...,
    ) -> None:
        ...

    @overload
    @classmethod
    def set(
            cls,
            instance: datetime,
    ) -> None:
        ...

    @classmethod
    def set(cls, *args, **kw):
        """
        This will set the :class:`datetime.datetime` created from the
        supplied parameters as the next datetime to be returned by
        :meth:`~MockDateTime.now` or :meth:`~MockDateTime.utcnow`, clearing out
        any datetimes in the queue.  An instance
        of :class:`~datetime.datetime` may also be passed as a single
        positional argument.
        """
        return super().set(*args, **kw)

    @overload
    @classmethod
    def tick(
            cls,
            days: float = ...,
            seconds: float = ...,
            microseconds: float = ...,
            milliseconds: float = ...,
            minutes: float = ...,
            hours: float = ...,
            weeks: float = ...,
    ) -> None:
        ...

    @overload
    @classmethod
    def tick(
            cls,
            delta: timedelta,  # can become positional-only when Python 3.8 minimum
    ) -> None:
        ...

    @classmethod
    def tick(cls, *args, **kw) -> None:
        """
        This method should be called either with a :class:`~datetime.timedelta`
        as a positional argument, or with keyword parameters that will be used
        to construct a :class:`~datetime.timedelta`.

        The  :class:`~datetime.timedelta` will be used to advance the next datetime
        to be returned by :meth:`~MockDateTime.now` or :meth:`~MockDateTime.utcnow`.
        """
        return super().tick(*args, **kw)

    @classmethod
    def _correct_mock_type(cls, instance):
        return cls._mock_class(
            instance.year,
            instance.month,
            instance.day,
            instance.hour,
            instance.minute,
            instance.second,
            instance.microsecond,
            instance.tzinfo,
        )

    @classmethod
    def now(cls, tz: TZInfo = None) -> datetime:
        """
        :param tz: An optional timezone to apply to the returned time.
                If supplied, it must be an instance of a
                :class:`~datetime.tzinfo` subclass.

        This will return the next supplied or calculated datetime from the
        internal queue, rather than the actual current datetime.

        If `tz` is supplied, see :ref:`timezones`.
        """
        instance = cast(datetime, cls._mock_queue.next())
        if tz is not None:
            if cls._mock_tzinfo:
                instance = instance - cls._mock_tzinfo.utcoffset(instance)
            instance = tz.fromutc(instance.replace(tzinfo=tz))
        return cls._correct_mock_type(instance)

    @classmethod
    def utcnow(cls) -> datetime:
        """
        This will return the next supplied or calculated datetime from the
        internal queue, rather than the actual current UTC datetime.

        If you care about timezones, see :ref:`timezones`.
        """
        instance = cast(datetime, cls._mock_queue.next())
        if cls._mock_tzinfo is not None:
            instance = instance - cls._mock_tzinfo.utcoffset(instance)
        return instance

    def date(self) -> date:
        """
        This will return the date component of the current mock instance,
        but using the date type supplied when the mock class was created.
        """
        return self._mock_date_type(
            self.year,
            self.month,
            self.day
            )


@overload
def mock_datetime(
        tzinfo: TZInfo = None,
        delta: float = None,
        delta_type: str = 'seconds',
        date_type: Type[date] = date,
        strict: bool = False
) -> Type[MockDateTime]:
    ...


@overload
def mock_datetime(
        year: int,
        month: int,
        day: int,
        hour: int = ...,
        minute: int = ...,
        second: int = ...,
        microsecond: int = ...,
        tzinfo: TZInfo = None,
        delta: float = None,
        delta_type: str = 'seconds',
        date_type: Type[date] = date,
        strict: bool = False
) -> Type[MockDateTime]:
    ...


@overload
def mock_datetime(
        default: datetime,
        tzinfo: TZInfo = None,
        delta: float = None,
        delta_type: str = 'seconds',
        date_type: Type[date] = date,
        strict: bool = False
) -> Type[MockDateTime]:
    ...


@overload
def mock_datetime(
        default: None,  # explicit None positional
        tzinfo: TZInfo = None,
        delta: float = None,
        delta_type: str = 'seconds',
        date_type: Type[date] = date,
        strict: bool = False
) -> Type[MockDateTime]:
    ...


def mock_datetime(
        *args,
        tzinfo: TZInfo = None,
        delta: float = None,
        delta_type: str = 'seconds',
        date_type: Type[date] = date,
        strict: bool = False,
        **kw,
) -> Type[MockDateTime]:
    """
    .. currentmodule:: testfixtures.datetime

    A function that returns a mock object that can be used in place of
    the :class:`datetime.datetime` class but where the return value of
    :meth:`~MockDateTime.now` can be controlled.

    If a single positional argument of ``None`` is passed, then the
    queue of datetimes to be returned will be empty and you will need to
    call :meth:`~MockDateTime.set` or :meth:`~MockDateTime.add` before calling
    :meth:`~MockDateTime.now` or :meth:`~MockDateTime.utcnow`.

    If an instance of :class:`~datetime.datetime` is passed as a single
    positional argument, that will be used as the first date returned by
    :meth:`~MockDateTime.now`

    :param year:
      An optional year used to create the first datetime returned by :meth:`~MockDateTime.now`.

    :param month:
      An optional month used to create the first datetime returned by :meth:`~MockDateTime.now`.

    :param day:
      An optional day used to create the first datetime returned by :meth:`~MockDateTime.now`.

    :param hour:
      An optional hour used to create the first datetime returned by :meth:`~MockDateTime.now`.

    :param minute:
      An optional minute used to create the first datetime returned by :meth:`~MockDateTime.now`.

    :param second:
      An optional second used to create the first datetime returned by :meth:`~MockDateTime.now`.

    :param microsecond:
      An optional microsecond used to create the first datetime returned by
      :meth:`~MockDateTime.now`.

    :param tzinfo:
      An optional :class:`datetime.tzinfo`, see :ref:`timezones`.

    :param delta:
      The size of the delta to use between values returned from mocked class methods.
      If not specified, it will increase by 1 with each call to :meth:`~MockDateTime.now`.

    :param delta_type:
      The type of the delta to use between values returned from mocked class methods.
      This can be any keyword parameter accepted by the :class:`~datetime.timedelta` constructor.

    :param date_type:
      The type to use for the return value of the mocked class methods.
      This can help with gotchas that occur when type checking is performed on values returned
      by the :meth:`~testfixtures.datetime.MockDateTime.date` method.

    :param strict:
      If ``True``, calling the mock class and any of its methods will result in an instance of
      the mock being returned. If ``False``, the default, an instance of
      :class:`~datetime.datetime` will be returned instead.

    The mock returned will behave exactly as the :class:`datetime.datetime` class
    as well as being a subclass of :class:`~testfixtures.datetime.MockDateTime`.
    """
    if len(args) > 7:
        tzinfo = args[7]
        args = args[:7]
    else:
        tzinfo = tzinfo or (getattr(args[0], 'tzinfo', None) if args else None)
    return cast(Type[MockDateTime], mock_factory(
        'MockDateTime',
        MockDateTime,
        (2001, 1, 1, 0, 0, 0),
        args,
        kw,
        tzinfo=tzinfo,
        delta=delta,
        delta_delta=10,
        delta_type=delta_type,
        date_type=date_type,
        strict=strict,
        ))


class MockDate(MockedCurrent, date):

    @classmethod
    def _correct_mock_type(cls, instance):
        return cls._mock_class(
            instance.year,
            instance.month,
            instance.day,
        )

    @overload
    @classmethod
    def add(
            cls,
            year: int,
            month: int,
            day: int,
    ) -> None:
        ...

    @overload
    @classmethod
    def add(
            cls,
            instance: date,
    ) -> None:
        ...

    @classmethod
    def add(cls, *args, **kw):
        """
        This will add the :class:`datetime.date` created from the
        supplied parameters to the queue of dates to be returned by
        :meth:`~MockDate.today`.  An instance
        of :class:`~datetime.date` may also be passed as a single
        positional argument.
        """
        return super().add(*args, **kw)

    @overload
    @classmethod
    def set(
            cls,
            year: int,
            month: int,
            day: int,
    ) -> None:
        ...

    @overload
    @classmethod
    def set(
            cls,
            instance: date,
    ) -> None:
        ...

    @classmethod
    def set(cls, *args, **kw) -> None:
        """
        This will set the :class:`datetime.date` created from the
        supplied parameters as the next date to be returned by
        :meth:`~MockDate.today`, regardless of any dates in the
        queue.   An instance
        of :class:`~datetime.date` may also be passed as a single
        positional argument.
        """
        return super().set(*args, **kw)

    @overload
    @classmethod
    def tick(
            cls,
            days: float = ...,
            weeks: float = ...,
    ) -> None:
        ...

    @overload
    @classmethod
    def tick(
            cls,
            delta: timedelta,  # can become positional-only when Python 3.8 minimum
    ) -> None:
        ...

    @classmethod
    def tick(cls, *args, **kw) -> None:
        """
        This method should be called either with a :class:`~datetime.timedelta`
        as a positional argument, or with keyword parameters that will be used
        to construct a :class:`~datetime.timedelta`.

        The  :class:`~datetime.timedelta` will be used to advance the next date
        to be returned by :meth:`~MockDate.today`.
        """
        return super().tick(*args, **kw)

    @classmethod
    def today(cls) -> date:
        """
        This will return the next supplied or calculated date from the
        internal queue, rather than the actual current date.

        """
        return cast(date, cls._mock_queue.next())


@overload
def mock_date(
        delta: float = None,
        delta_type: str = None,
        date_type: Type[date] = date,
        strict: bool = False
) -> Type[MockDate]:
    ...


@overload
def mock_date(
        year: int,
        month: int,
        day: int,
        delta: float = None,
        delta_type: str = 'days',
        strict: bool = False,
) -> Type[MockDate]:
    ...


@overload
def mock_date(
        default: date,
        delta: float = None,
        delta_type: str = 'days',
        strict: bool = False,
) -> Type[MockDate]:
    ...


@overload
def mock_date(
        default: None,  # explicit None positional
        delta: float = None,
        delta_type: str = 'days',
        strict: bool = False,
) -> Type[MockDate]:
    ...


def mock_date(
        *args,
        delta: float = None,
        delta_type: str = 'days',
        strict: bool = False,
        **kw
) -> Type[MockDate]:
    """
    .. currentmodule:: testfixtures.datetime

    A function that returns a mock object that can be used in place of
    the :class:`datetime.date` class but where the return value of
    :meth:`~datetime.date.today` can be controlled.

    If a single positional argument of ``None`` is passed, then the
    queue of dates to be returned will be empty and you will need to
    call :meth:`~MockDate.set` or :meth:`~MockDate.add` before calling
    :meth:`~MockDate.today`.

    If an instance of :class:`~datetime.date` is passed as a single
    positional argument, that will be used as the first date returned by
    :meth:`~datetime.date.today`

    :param year:
      An optional year used to create the first date returned by :meth:`~datetime.date.today`.

    :param month:
      An optional month used to create the first date returned by :meth:`~datetime.date.today`.

    :param day:
      An optional day used to create the first date returned by :meth:`~datetime.date.today`.

    :param delta:
      The size of the delta to use between values returned from :meth:`~datetime.date.today`.
      If not specified, it will increase by 1 with each call to :meth:`~datetime.date.today`.

    :param delta_type:
      The type of the delta to use between values returned from :meth:`~datetime.date.today`.
      This can be any keyword parameter accepted by the :class:`~datetime.timedelta` constructor.

    :param strict:
      If ``True``, calling the mock class and any of its methods will result in an instance of
      the mock being returned. If ``False``, the default, an instance of :class:`~datetime.date`
      will be returned instead.

    The mock returned will behave exactly as the :class:`datetime.date` class
    as well as being a subclass of :class:`~testfixtures.datetime.MockDate`.
    """
    return cast(Type[MockDate], mock_factory(
        'MockDate', MockDate, (2001, 1, 1), args, kw,
        delta=delta,
        delta_type=delta_type,
        strict=strict,
        ))


ms = 10**6


class MockTime(MockedCurrent, datetime):

    @overload
    @classmethod
    def add(
            cls,
            year: int,
            month: int,
            day: int,
            hour: int = ...,
            minute: int = ...,
            second: int = ...,
            microsecond: int = ...,
    ) -> None:
        ...

    @overload
    @classmethod
    def add(
            cls,
            instance: datetime,
    ) -> None:
        ...

    @classmethod
    def add(cls, *args, **kw):
        """
        This will add the time specified by the supplied parameters to the
        queue of times to be returned by calls to the mock. The
        parameters are the same as the :class:`datetime.datetime`
        constructor. An instance of :class:`~datetime.datetime` may also
        be passed as a single positional argument.
        """
        return super().add(*args, **kw)

    @overload
    @classmethod
    def set(
            cls,
            year: int,
            month: int,
            day: int,
            hour: int = ...,
            minute: int = ...,
            second: int = ...,
            microsecond: int = ...,
    ) -> None:
        ...

    @overload
    @classmethod
    def set(
            cls,
            instance: datetime,
    ) -> None:
        ...

    @classmethod
    def set(cls, *args, **kw):
        """
        This will set the time specified by the supplied parameters as
        the next time to be returned by a call to the mock, regardless of
        any times in the queue.  The parameters are the same as the
        :class:`datetime.datetime` constructor.  An instance of
        :class:`~datetime.datetime` may also be passed as a single
        positional argument.
        """
        return super().set(*args, **kw)

    @overload
    @classmethod
    def tick(
            cls,
            days: float = ...,
            seconds: float = ...,
            microseconds: float = ...,
            milliseconds: float = ...,
            minutes: float = ...,
            hours: float = ...,
            weeks: float = ...,
    ) -> None:
        ...

    @overload
    @classmethod
    def tick(
            cls,
            delta: timedelta,  # can become positional-only when Python 3.8 minimum
    ) -> None:
        ...

    @classmethod
    def tick(cls, *args, **kw):
        """
        This method should be called either with a :class:`~datetime.timedelta`
        as a positional argument, or with keyword parameters that will be used
        to construct a :class:`~datetime.timedelta`.

        The  :class:`~datetime.timedelta` will be used to advance the next time
        to be returned by a call to the mock.
        """
        return super().tick(*args, **kw)

    def __new__(cls, *args, **kw) -> float:
        """
        Return a :class:`float` representing the mocked current time as would normally
        be returned by :func:`time.time`.
        """
        if args or kw:
            # Used when adding stuff to the queue
            return super().__new__(cls, *args, **kw)
        else:
            instance = cast(datetime, cls._mock_queue.next())
            time = timegm(instance.utctimetuple())
            time += (float(instance.microsecond)/ms)
            return time


@overload
def mock_time(
        delta: float = None,
        delta_type: str = 'seconds',
) -> Type[MockDateTime]:
    ...


@overload
def mock_time(
        year: int,
        month: int,
        day: int,
        hour: int = ...,
        minute: int = ...,
        second: int = ...,
        microsecond: int = ...,
        delta: float = None,
        delta_type: str = 'seconds',
) -> Type[MockDateTime]:
    ...


@overload
def mock_time(
        default: datetime,
        delta: float = None,
        delta_type: str = 'seconds',
) -> Type[MockDateTime]:
    ...


@overload
def mock_time(
        default: None,  # explicit None positional
        delta: float = None,
        delta_type: str = 'seconds',
) -> Type[MockDateTime]:
    ...


def mock_time(*args, delta: float = None, delta_type: str = 'seconds', **kw) -> Type[MockTime]:
    """
    .. currentmodule:: testfixtures.datetime

    A function that returns a :class:`mock object <testfixtures.datetime.MockTime>` that can be
    used in place of the :func:`time.time` function but where the return value can be
    controlled.

    If a single positional argument of ``None`` is passed, then the
    queue of times to be returned will be empty and you will need to
    call :meth:`~MockTime.set` or :meth:`~MockTime.add` before calling
    the mock.

    If an instance of :class:`~datetime.datetime` is passed as a single
    positional argument, that will be used to create the first time returned.

    :param year: An optional year used to create the first time returned.

    :param month: An optional month used to create the first time.

    :param day: An optional day used to create the first time.

    :param hour: An optional hour used to create the first time.

    :param minute: An optional minute used to create the first time.

    :param second: An optional second used to create the first time.

    :param microsecond: An optional microsecond used to create the first time.

    :param delta:
      The size of the delta to use between values returned.
      If not specified, it will increase by 1 with each call to the mock.

    :param delta_type:
      The type of the delta to use between values returned.
      This can be any keyword parameter accepted by the :class:`~datetime.timedelta` constructor.

    The :meth:`~testfixtures.datetime.MockTime.add`, :meth:`~testfixtures.datetime.MockTime.set`
    and :meth:`~testfixtures.datetime.MockTime.tick` methods on the mock can be used to
    control the return values.
    """
    if 'tzinfo' in kw or len(args) > 7 or (args and getattr(args[0], 'tzinfo', None)):
        raise TypeError("You don't want to use tzinfo with test_time")
    return cast(Type[MockTime], mock_factory(
        'MockTime', MockTime, (2001, 1, 1, 0, 0, 0), args, kw,
        delta=delta,
        delta_type=delta_type,
        ))

Youez - 2016 - github.com/yon3zu
LinuXploit