Skip to content

Feature request: Mock current date/time #81

@eviljoe

Description

@eviljoe

Add support for mocking the value returned from functions like datetime.datetime.now(). I have several functions that make use of the current date. I have not found a way to appropriately test those using Mockito.

The example below is how I have tried to mock the current date/time. I am not asking date/time freezing to work exactly like this example. This is just to help show what I am talking about.

Example

requirements.txt

expects==0.9.0
mamba==0.11.2
mockito==1.4.0

datetime_spec.py

from datetime import datetime

from expects import equal, expect
from mamba import description, before, after, it
from mockito import unstub, when

with description('current date') as self:
    with before.each:
        self.now = datetime(year=2024, month=1, day=1)
        when(datetime).now(...).thenReturn(self.now)

    with after.each:
        unstub()  # <-- This line throws an error

    with it('can mock the date'):
        expect(datetime.now().timestamp()).to(equal(1704067200.0))

Command

python -m mamba.cli ./datetime_spec.py

Error Message

Failure/Error: ./datetime_spec.py unstub()
         TypeError: cannot set 'now' attribute of immutable type 'datetime.datetime'

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions