Fake utcnow for the pytestUnit Testing of parser method using pytestTrying to use global variables for referencing directories in Python 2.5TDD - Kata - String CalculatorMocking UserDefaults in SwiftPython - Faster random business date generationHours and Minutes math in a work week calculatorApply a series of functions on Django querysets using decoratorsCode to implement the Jaro similarity for fuzzy matching stringsMaking a graph of the import structure of a programCurrency converter - CLI and API
The (Easy) Road to Code
Rationale to prefer local variables over instance variables?
Does the US political system, in principle, allow for a no-party system?
An Undercover Army
What is the meaning of option 'by' in TikZ Intersections
Iron deposits mined from under the city
Custom javascript not working
Gemara word for QED
What's the difference between Compensation, Indemnity, and Reparations?
Can you run a ground wire from stove directly to ground pole in the ground
What's the best tool for cutting holes into duct work?
I've given my players a lot of magic items. Is it reasonable for me to give them harder encounters?
Why do phishing e-mails use faked e-mail addresses instead of the real one?
Convert an array of objects to array of the objects' values
Called into a meeting and told we are being made redundant (laid off) and "not to share outside". Can I tell my partner?
Is this nominative case or accusative case?
Ultrafilters as a double dual
Short story about an infectious indestructible metal bar?
How to write a chaotic neutral protagonist and prevent my readers from thinking they are evil?
Is being socially reclusive okay for a graduate student?
Practical reasons to have both a large police force and bounty hunting network?
Are Wave equations equivalent to Maxwell equations in free space?
Professor forcing me to attend a conference
When to use the term transposed instead of modulation?
Fake utcnow for the pytest
Unit Testing of parser method using pytestTrying to use global variables for referencing directories in Python 2.5TDD - Kata - String CalculatorMocking UserDefaults in SwiftPython - Faster random business date generationHours and Minutes math in a work week calculatorApply a series of functions on Django querysets using decoratorsCode to implement the Jaro similarity for fuzzy matching stringsMaking a graph of the import structure of a programCurrency converter - CLI and API
$begingroup$
I want to create a pytest with a fake utcnow
, but also I need to preserve the functionality of all other datetime
methods. Simple example here:
import datetime as dt
class FakeTime(dt.datetime):
fake_time = None
@classmethod
def utcnow(cls):
return cls.fake_time
def str_2_time(str_dt: str) -> dt.datetime:
"""Shortcut to do convert the string to datetime"""
return dt.datetime.strptime(str_dt, '%Y-%m-%d %H:%M')
def test_patch_datetime():
for utc_time in ['2019-01-01 10:00', '2019-02-01 13:00', '2019-03-01 16:00']:
FakeTime.fake_time = str_2_time(utc_time)
dt.datetime = FakeTime
assert dt.datetime.utcnow() == str_2_time(utc_time)
Is this the right way?
The method str_2_time
just need to show that all other methods of the datetime works fine.
python datetime unit-testing mocks
New contributor
$endgroup$
add a comment |
$begingroup$
I want to create a pytest with a fake utcnow
, but also I need to preserve the functionality of all other datetime
methods. Simple example here:
import datetime as dt
class FakeTime(dt.datetime):
fake_time = None
@classmethod
def utcnow(cls):
return cls.fake_time
def str_2_time(str_dt: str) -> dt.datetime:
"""Shortcut to do convert the string to datetime"""
return dt.datetime.strptime(str_dt, '%Y-%m-%d %H:%M')
def test_patch_datetime():
for utc_time in ['2019-01-01 10:00', '2019-02-01 13:00', '2019-03-01 16:00']:
FakeTime.fake_time = str_2_time(utc_time)
dt.datetime = FakeTime
assert dt.datetime.utcnow() == str_2_time(utc_time)
Is this the right way?
The method str_2_time
just need to show that all other methods of the datetime works fine.
python datetime unit-testing mocks
New contributor
$endgroup$
$begingroup$
I highly recommend this lib for mockingnow
in python tests github.com/spulec/freezegun
$endgroup$
– Anentropic
yesterday
$begingroup$
@Anentropic thank you, but if i will need more options i will add the package to the project
$endgroup$
– Bear Brown
yesterday
add a comment |
$begingroup$
I want to create a pytest with a fake utcnow
, but also I need to preserve the functionality of all other datetime
methods. Simple example here:
import datetime as dt
class FakeTime(dt.datetime):
fake_time = None
@classmethod
def utcnow(cls):
return cls.fake_time
def str_2_time(str_dt: str) -> dt.datetime:
"""Shortcut to do convert the string to datetime"""
return dt.datetime.strptime(str_dt, '%Y-%m-%d %H:%M')
def test_patch_datetime():
for utc_time in ['2019-01-01 10:00', '2019-02-01 13:00', '2019-03-01 16:00']:
FakeTime.fake_time = str_2_time(utc_time)
dt.datetime = FakeTime
assert dt.datetime.utcnow() == str_2_time(utc_time)
Is this the right way?
The method str_2_time
just need to show that all other methods of the datetime works fine.
python datetime unit-testing mocks
New contributor
$endgroup$
I want to create a pytest with a fake utcnow
, but also I need to preserve the functionality of all other datetime
methods. Simple example here:
import datetime as dt
class FakeTime(dt.datetime):
fake_time = None
@classmethod
def utcnow(cls):
return cls.fake_time
def str_2_time(str_dt: str) -> dt.datetime:
"""Shortcut to do convert the string to datetime"""
return dt.datetime.strptime(str_dt, '%Y-%m-%d %H:%M')
def test_patch_datetime():
for utc_time in ['2019-01-01 10:00', '2019-02-01 13:00', '2019-03-01 16:00']:
FakeTime.fake_time = str_2_time(utc_time)
dt.datetime = FakeTime
assert dt.datetime.utcnow() == str_2_time(utc_time)
Is this the right way?
The method str_2_time
just need to show that all other methods of the datetime works fine.
python datetime unit-testing mocks
python datetime unit-testing mocks
New contributor
New contributor
edited yesterday
Bear Brown
New contributor
asked yesterday
Bear BrownBear Brown
1236
1236
New contributor
New contributor
$begingroup$
I highly recommend this lib for mockingnow
in python tests github.com/spulec/freezegun
$endgroup$
– Anentropic
yesterday
$begingroup$
@Anentropic thank you, but if i will need more options i will add the package to the project
$endgroup$
– Bear Brown
yesterday
add a comment |
$begingroup$
I highly recommend this lib for mockingnow
in python tests github.com/spulec/freezegun
$endgroup$
– Anentropic
yesterday
$begingroup$
@Anentropic thank you, but if i will need more options i will add the package to the project
$endgroup$
– Bear Brown
yesterday
$begingroup$
I highly recommend this lib for mocking
now
in python tests github.com/spulec/freezegun$endgroup$
– Anentropic
yesterday
$begingroup$
I highly recommend this lib for mocking
now
in python tests github.com/spulec/freezegun$endgroup$
– Anentropic
yesterday
$begingroup$
@Anentropic thank you, but if i will need more options i will add the package to the project
$endgroup$
– Bear Brown
yesterday
$begingroup$
@Anentropic thank you, but if i will need more options i will add the package to the project
$endgroup$
– Bear Brown
yesterday
add a comment |
2 Answers
2
active
oldest
votes
$begingroup$
According to this, subclassing datetime.datetime
seems the way to go.
There is no use for the str_2_time
method though. You can easily inline this, or even simpler, just use the datetime.datetime
constructor:
def test_patch_datetime():
for utc_time in [
dt.datetime(2019, 1, 1, 10),
dt.datetime(2019, 2, 1, 13),
dt.datetime(2019, 3, 1, 16),
]:
FakeTime.fake_time = utc_time
dt.datetime = FakeTime
assert dt.datetime.utcnow() == utc_time
You should be aware that this can have side effects in other parts of your code, so it might be needed to replace it back with the original class after the test method:
def test_patch_datetime():
datetime_orig = dt.datetime
utc_times = [
dt.datetime(2019, 1, 1, 10),
dt.datetime(2019, 2, 1, 13),
dt.datetime(2019, 3, 1, 16),
]
for utc_time in utc_times:
FakeTime.fake_time = utc_time
dt.datetime = FakeTime
assert dt.datetime.utcnow() == utc_time
dt.datetime = datetime_orig
# print(dt.datetime.utcnow())
assert dt.datetime.utcnow() > max(utc_times)
$endgroup$
$begingroup$
thank you, but the methodstr_2_time
just need to show that all other methods of thedatetime
works fine.
$endgroup$
– Bear Brown
yesterday
add a comment |
$begingroup$
Usually, I do:
- Separate module, for example
utils.py
, that contains:
from datetime import datetime
def get_utcnow() -> datetime:
return datetime.utcnow()
- Use this function everywhere in my code.
- Add the mocking fixture in
tests/conftest.py
:
from datetime import datetime, timedelta
import pytest
from .. import utils
@pytest.fixture
def mock_utcnow(monkeypatch):
now = datetime.min
def wrapped(delta=0.0):
when = now + timedelta(delta)
monkeypatch.setattr(utils, "get_utcnow", lambda: when)
return when
return wrapped
- Now it's easy to use it in your tests:
def test(mock_utcnow):
now = mock_utcnow()
new_now = mock_utcnow(0.1)
Additionally, with this fixture you can set the returning value with desired offset.
Hope it helps.
New contributor
$endgroup$
$begingroup$
thank you for the answer, but i don't understand how it should help for my case.
$endgroup$
– Bear Brown
yesterday
$begingroup$
If I understand you right, you wantutcnow
to return fake datetime. So, using code from my answer: 1. You will useutils.get_utcnow
in your real code, not in the tests. 2. In the tests you'll use fixture, that mocksutils.get_utcnow
. After you call mocking function, every call ofutils.get_utcnow
in your real code will return fake datetime.
$endgroup$
– S. Zobov
21 hours ago
$begingroup$
But with the code from my answer you'll getdatetime.min
by default, and after you can increase its value by addingtimedelta
, e.g. by callingmock_utcnow(0.1)
.
$endgroup$
– S. Zobov
21 hours ago
$begingroup$
If you want to start not with adatetime.min
, you can extend fixture with this But it requires more code in your tests.
$endgroup$
– S. Zobov
21 hours ago
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
return StackExchange.using("mathjaxEditing", function ()
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
);
);
, "mathjax-editing");
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "196"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Bear Brown is a new contributor. Be nice, and check out our Code of Conduct.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f214816%2ffake-utcnow-for-the-pytest%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
$begingroup$
According to this, subclassing datetime.datetime
seems the way to go.
There is no use for the str_2_time
method though. You can easily inline this, or even simpler, just use the datetime.datetime
constructor:
def test_patch_datetime():
for utc_time in [
dt.datetime(2019, 1, 1, 10),
dt.datetime(2019, 2, 1, 13),
dt.datetime(2019, 3, 1, 16),
]:
FakeTime.fake_time = utc_time
dt.datetime = FakeTime
assert dt.datetime.utcnow() == utc_time
You should be aware that this can have side effects in other parts of your code, so it might be needed to replace it back with the original class after the test method:
def test_patch_datetime():
datetime_orig = dt.datetime
utc_times = [
dt.datetime(2019, 1, 1, 10),
dt.datetime(2019, 2, 1, 13),
dt.datetime(2019, 3, 1, 16),
]
for utc_time in utc_times:
FakeTime.fake_time = utc_time
dt.datetime = FakeTime
assert dt.datetime.utcnow() == utc_time
dt.datetime = datetime_orig
# print(dt.datetime.utcnow())
assert dt.datetime.utcnow() > max(utc_times)
$endgroup$
$begingroup$
thank you, but the methodstr_2_time
just need to show that all other methods of thedatetime
works fine.
$endgroup$
– Bear Brown
yesterday
add a comment |
$begingroup$
According to this, subclassing datetime.datetime
seems the way to go.
There is no use for the str_2_time
method though. You can easily inline this, or even simpler, just use the datetime.datetime
constructor:
def test_patch_datetime():
for utc_time in [
dt.datetime(2019, 1, 1, 10),
dt.datetime(2019, 2, 1, 13),
dt.datetime(2019, 3, 1, 16),
]:
FakeTime.fake_time = utc_time
dt.datetime = FakeTime
assert dt.datetime.utcnow() == utc_time
You should be aware that this can have side effects in other parts of your code, so it might be needed to replace it back with the original class after the test method:
def test_patch_datetime():
datetime_orig = dt.datetime
utc_times = [
dt.datetime(2019, 1, 1, 10),
dt.datetime(2019, 2, 1, 13),
dt.datetime(2019, 3, 1, 16),
]
for utc_time in utc_times:
FakeTime.fake_time = utc_time
dt.datetime = FakeTime
assert dt.datetime.utcnow() == utc_time
dt.datetime = datetime_orig
# print(dt.datetime.utcnow())
assert dt.datetime.utcnow() > max(utc_times)
$endgroup$
$begingroup$
thank you, but the methodstr_2_time
just need to show that all other methods of thedatetime
works fine.
$endgroup$
– Bear Brown
yesterday
add a comment |
$begingroup$
According to this, subclassing datetime.datetime
seems the way to go.
There is no use for the str_2_time
method though. You can easily inline this, or even simpler, just use the datetime.datetime
constructor:
def test_patch_datetime():
for utc_time in [
dt.datetime(2019, 1, 1, 10),
dt.datetime(2019, 2, 1, 13),
dt.datetime(2019, 3, 1, 16),
]:
FakeTime.fake_time = utc_time
dt.datetime = FakeTime
assert dt.datetime.utcnow() == utc_time
You should be aware that this can have side effects in other parts of your code, so it might be needed to replace it back with the original class after the test method:
def test_patch_datetime():
datetime_orig = dt.datetime
utc_times = [
dt.datetime(2019, 1, 1, 10),
dt.datetime(2019, 2, 1, 13),
dt.datetime(2019, 3, 1, 16),
]
for utc_time in utc_times:
FakeTime.fake_time = utc_time
dt.datetime = FakeTime
assert dt.datetime.utcnow() == utc_time
dt.datetime = datetime_orig
# print(dt.datetime.utcnow())
assert dt.datetime.utcnow() > max(utc_times)
$endgroup$
According to this, subclassing datetime.datetime
seems the way to go.
There is no use for the str_2_time
method though. You can easily inline this, or even simpler, just use the datetime.datetime
constructor:
def test_patch_datetime():
for utc_time in [
dt.datetime(2019, 1, 1, 10),
dt.datetime(2019, 2, 1, 13),
dt.datetime(2019, 3, 1, 16),
]:
FakeTime.fake_time = utc_time
dt.datetime = FakeTime
assert dt.datetime.utcnow() == utc_time
You should be aware that this can have side effects in other parts of your code, so it might be needed to replace it back with the original class after the test method:
def test_patch_datetime():
datetime_orig = dt.datetime
utc_times = [
dt.datetime(2019, 1, 1, 10),
dt.datetime(2019, 2, 1, 13),
dt.datetime(2019, 3, 1, 16),
]
for utc_time in utc_times:
FakeTime.fake_time = utc_time
dt.datetime = FakeTime
assert dt.datetime.utcnow() == utc_time
dt.datetime = datetime_orig
# print(dt.datetime.utcnow())
assert dt.datetime.utcnow() > max(utc_times)
edited yesterday
answered yesterday
Maarten FabréMaarten Fabré
5,019417
5,019417
$begingroup$
thank you, but the methodstr_2_time
just need to show that all other methods of thedatetime
works fine.
$endgroup$
– Bear Brown
yesterday
add a comment |
$begingroup$
thank you, but the methodstr_2_time
just need to show that all other methods of thedatetime
works fine.
$endgroup$
– Bear Brown
yesterday
$begingroup$
thank you, but the method
str_2_time
just need to show that all other methods of the datetime
works fine.$endgroup$
– Bear Brown
yesterday
$begingroup$
thank you, but the method
str_2_time
just need to show that all other methods of the datetime
works fine.$endgroup$
– Bear Brown
yesterday
add a comment |
$begingroup$
Usually, I do:
- Separate module, for example
utils.py
, that contains:
from datetime import datetime
def get_utcnow() -> datetime:
return datetime.utcnow()
- Use this function everywhere in my code.
- Add the mocking fixture in
tests/conftest.py
:
from datetime import datetime, timedelta
import pytest
from .. import utils
@pytest.fixture
def mock_utcnow(monkeypatch):
now = datetime.min
def wrapped(delta=0.0):
when = now + timedelta(delta)
monkeypatch.setattr(utils, "get_utcnow", lambda: when)
return when
return wrapped
- Now it's easy to use it in your tests:
def test(mock_utcnow):
now = mock_utcnow()
new_now = mock_utcnow(0.1)
Additionally, with this fixture you can set the returning value with desired offset.
Hope it helps.
New contributor
$endgroup$
$begingroup$
thank you for the answer, but i don't understand how it should help for my case.
$endgroup$
– Bear Brown
yesterday
$begingroup$
If I understand you right, you wantutcnow
to return fake datetime. So, using code from my answer: 1. You will useutils.get_utcnow
in your real code, not in the tests. 2. In the tests you'll use fixture, that mocksutils.get_utcnow
. After you call mocking function, every call ofutils.get_utcnow
in your real code will return fake datetime.
$endgroup$
– S. Zobov
21 hours ago
$begingroup$
But with the code from my answer you'll getdatetime.min
by default, and after you can increase its value by addingtimedelta
, e.g. by callingmock_utcnow(0.1)
.
$endgroup$
– S. Zobov
21 hours ago
$begingroup$
If you want to start not with adatetime.min
, you can extend fixture with this But it requires more code in your tests.
$endgroup$
– S. Zobov
21 hours ago
add a comment |
$begingroup$
Usually, I do:
- Separate module, for example
utils.py
, that contains:
from datetime import datetime
def get_utcnow() -> datetime:
return datetime.utcnow()
- Use this function everywhere in my code.
- Add the mocking fixture in
tests/conftest.py
:
from datetime import datetime, timedelta
import pytest
from .. import utils
@pytest.fixture
def mock_utcnow(monkeypatch):
now = datetime.min
def wrapped(delta=0.0):
when = now + timedelta(delta)
monkeypatch.setattr(utils, "get_utcnow", lambda: when)
return when
return wrapped
- Now it's easy to use it in your tests:
def test(mock_utcnow):
now = mock_utcnow()
new_now = mock_utcnow(0.1)
Additionally, with this fixture you can set the returning value with desired offset.
Hope it helps.
New contributor
$endgroup$
$begingroup$
thank you for the answer, but i don't understand how it should help for my case.
$endgroup$
– Bear Brown
yesterday
$begingroup$
If I understand you right, you wantutcnow
to return fake datetime. So, using code from my answer: 1. You will useutils.get_utcnow
in your real code, not in the tests. 2. In the tests you'll use fixture, that mocksutils.get_utcnow
. After you call mocking function, every call ofutils.get_utcnow
in your real code will return fake datetime.
$endgroup$
– S. Zobov
21 hours ago
$begingroup$
But with the code from my answer you'll getdatetime.min
by default, and after you can increase its value by addingtimedelta
, e.g. by callingmock_utcnow(0.1)
.
$endgroup$
– S. Zobov
21 hours ago
$begingroup$
If you want to start not with adatetime.min
, you can extend fixture with this But it requires more code in your tests.
$endgroup$
– S. Zobov
21 hours ago
add a comment |
$begingroup$
Usually, I do:
- Separate module, for example
utils.py
, that contains:
from datetime import datetime
def get_utcnow() -> datetime:
return datetime.utcnow()
- Use this function everywhere in my code.
- Add the mocking fixture in
tests/conftest.py
:
from datetime import datetime, timedelta
import pytest
from .. import utils
@pytest.fixture
def mock_utcnow(monkeypatch):
now = datetime.min
def wrapped(delta=0.0):
when = now + timedelta(delta)
monkeypatch.setattr(utils, "get_utcnow", lambda: when)
return when
return wrapped
- Now it's easy to use it in your tests:
def test(mock_utcnow):
now = mock_utcnow()
new_now = mock_utcnow(0.1)
Additionally, with this fixture you can set the returning value with desired offset.
Hope it helps.
New contributor
$endgroup$
Usually, I do:
- Separate module, for example
utils.py
, that contains:
from datetime import datetime
def get_utcnow() -> datetime:
return datetime.utcnow()
- Use this function everywhere in my code.
- Add the mocking fixture in
tests/conftest.py
:
from datetime import datetime, timedelta
import pytest
from .. import utils
@pytest.fixture
def mock_utcnow(monkeypatch):
now = datetime.min
def wrapped(delta=0.0):
when = now + timedelta(delta)
monkeypatch.setattr(utils, "get_utcnow", lambda: when)
return when
return wrapped
- Now it's easy to use it in your tests:
def test(mock_utcnow):
now = mock_utcnow()
new_now = mock_utcnow(0.1)
Additionally, with this fixture you can set the returning value with desired offset.
Hope it helps.
New contributor
New contributor
answered yesterday
S. ZobovS. Zobov
212
212
New contributor
New contributor
$begingroup$
thank you for the answer, but i don't understand how it should help for my case.
$endgroup$
– Bear Brown
yesterday
$begingroup$
If I understand you right, you wantutcnow
to return fake datetime. So, using code from my answer: 1. You will useutils.get_utcnow
in your real code, not in the tests. 2. In the tests you'll use fixture, that mocksutils.get_utcnow
. After you call mocking function, every call ofutils.get_utcnow
in your real code will return fake datetime.
$endgroup$
– S. Zobov
21 hours ago
$begingroup$
But with the code from my answer you'll getdatetime.min
by default, and after you can increase its value by addingtimedelta
, e.g. by callingmock_utcnow(0.1)
.
$endgroup$
– S. Zobov
21 hours ago
$begingroup$
If you want to start not with adatetime.min
, you can extend fixture with this But it requires more code in your tests.
$endgroup$
– S. Zobov
21 hours ago
add a comment |
$begingroup$
thank you for the answer, but i don't understand how it should help for my case.
$endgroup$
– Bear Brown
yesterday
$begingroup$
If I understand you right, you wantutcnow
to return fake datetime. So, using code from my answer: 1. You will useutils.get_utcnow
in your real code, not in the tests. 2. In the tests you'll use fixture, that mocksutils.get_utcnow
. After you call mocking function, every call ofutils.get_utcnow
in your real code will return fake datetime.
$endgroup$
– S. Zobov
21 hours ago
$begingroup$
But with the code from my answer you'll getdatetime.min
by default, and after you can increase its value by addingtimedelta
, e.g. by callingmock_utcnow(0.1)
.
$endgroup$
– S. Zobov
21 hours ago
$begingroup$
If you want to start not with adatetime.min
, you can extend fixture with this But it requires more code in your tests.
$endgroup$
– S. Zobov
21 hours ago
$begingroup$
thank you for the answer, but i don't understand how it should help for my case.
$endgroup$
– Bear Brown
yesterday
$begingroup$
thank you for the answer, but i don't understand how it should help for my case.
$endgroup$
– Bear Brown
yesterday
$begingroup$
If I understand you right, you want
utcnow
to return fake datetime. So, using code from my answer: 1. You will use utils.get_utcnow
in your real code, not in the tests. 2. In the tests you'll use fixture, that mocks utils.get_utcnow
. After you call mocking function, every call of utils.get_utcnow
in your real code will return fake datetime.$endgroup$
– S. Zobov
21 hours ago
$begingroup$
If I understand you right, you want
utcnow
to return fake datetime. So, using code from my answer: 1. You will use utils.get_utcnow
in your real code, not in the tests. 2. In the tests you'll use fixture, that mocks utils.get_utcnow
. After you call mocking function, every call of utils.get_utcnow
in your real code will return fake datetime.$endgroup$
– S. Zobov
21 hours ago
$begingroup$
But with the code from my answer you'll get
datetime.min
by default, and after you can increase its value by adding timedelta
, e.g. by calling mock_utcnow(0.1)
.$endgroup$
– S. Zobov
21 hours ago
$begingroup$
But with the code from my answer you'll get
datetime.min
by default, and after you can increase its value by adding timedelta
, e.g. by calling mock_utcnow(0.1)
.$endgroup$
– S. Zobov
21 hours ago
$begingroup$
If you want to start not with a
datetime.min
, you can extend fixture with this But it requires more code in your tests.$endgroup$
– S. Zobov
21 hours ago
$begingroup$
If you want to start not with a
datetime.min
, you can extend fixture with this But it requires more code in your tests.$endgroup$
– S. Zobov
21 hours ago
add a comment |
Bear Brown is a new contributor. Be nice, and check out our Code of Conduct.
Bear Brown is a new contributor. Be nice, and check out our Code of Conduct.
Bear Brown is a new contributor. Be nice, and check out our Code of Conduct.
Bear Brown is a new contributor. Be nice, and check out our Code of Conduct.
Thanks for contributing an answer to Code Review Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f214816%2ffake-utcnow-for-the-pytest%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
$begingroup$
I highly recommend this lib for mocking
now
in python tests github.com/spulec/freezegun$endgroup$
– Anentropic
yesterday
$begingroup$
@Anentropic thank you, but if i will need more options i will add the package to the project
$endgroup$
– Bear Brown
yesterday