refactor: tests - update timezone.utc to UTC

This commit is contained in:
Matthias
2025-07-04 09:02:34 +02:00
parent deb8bde078
commit 640cab2ca8
12 changed files with 81 additions and 81 deletions

View File

@@ -1,4 +1,4 @@
from datetime import datetime, timedelta, timezone from datetime import UTC, datetime, timedelta
import pytest import pytest
@@ -8,19 +8,19 @@ from tests.conftest import create_mock_trades_usdt
@pytest.mark.usefixtures("init_persistence") @pytest.mark.usefixtures("init_persistence")
def test_key_value_store(time_machine): def test_key_value_store(time_machine):
start = datetime(2023, 1, 1, 4, tzinfo=timezone.utc) start = datetime(2023, 1, 1, 4, tzinfo=UTC)
time_machine.move_to(start, tick=False) time_machine.move_to(start, tick=False)
KeyValueStore.store_value("test", "testStringValue") KeyValueStore.store_value("test", "testStringValue")
KeyValueStore.store_value("test_dt", datetime.now(timezone.utc)) KeyValueStore.store_value("test_dt", datetime.now(UTC))
KeyValueStore.store_value("test_float", 22.51) KeyValueStore.store_value("test_float", 22.51)
KeyValueStore.store_value("test_int", 15) KeyValueStore.store_value("test_int", 15)
assert KeyValueStore.get_value("test") == "testStringValue" assert KeyValueStore.get_value("test") == "testStringValue"
assert KeyValueStore.get_value("test") == "testStringValue" assert KeyValueStore.get_value("test") == "testStringValue"
assert KeyValueStore.get_string_value("test") == "testStringValue" assert KeyValueStore.get_string_value("test") == "testStringValue"
assert KeyValueStore.get_value("test_dt") == datetime.now(timezone.utc) assert KeyValueStore.get_value("test_dt") == datetime.now(UTC)
assert KeyValueStore.get_datetime_value("test_dt") == datetime.now(timezone.utc) assert KeyValueStore.get_datetime_value("test_dt") == datetime.now(UTC)
assert KeyValueStore.get_string_value("test_dt") is None assert KeyValueStore.get_string_value("test_dt") is None
assert KeyValueStore.get_float_value("test_dt") is None assert KeyValueStore.get_float_value("test_dt") is None
assert KeyValueStore.get_int_value("test_dt") is None assert KeyValueStore.get_int_value("test_dt") is None
@@ -31,11 +31,11 @@ def test_key_value_store(time_machine):
assert KeyValueStore.get_datetime_value("test_int") is None assert KeyValueStore.get_datetime_value("test_int") is None
time_machine.move_to(start + timedelta(days=20, hours=5), tick=False) time_machine.move_to(start + timedelta(days=20, hours=5), tick=False)
assert KeyValueStore.get_value("test_dt") != datetime.now(timezone.utc) assert KeyValueStore.get_value("test_dt") != datetime.now(UTC)
assert KeyValueStore.get_value("test_dt") == start assert KeyValueStore.get_value("test_dt") == start
# Test update works # Test update works
KeyValueStore.store_value("test_dt", datetime.now(timezone.utc)) KeyValueStore.store_value("test_dt", datetime.now(UTC))
assert KeyValueStore.get_value("test_dt") == datetime.now(timezone.utc) assert KeyValueStore.get_value("test_dt") == datetime.now(UTC)
KeyValueStore.store_value("test_float", 23.51) KeyValueStore.store_value("test_float", 23.51)
assert KeyValueStore.get_value("test_float") == 23.51 assert KeyValueStore.get_value("test_float") == 23.51
@@ -52,7 +52,7 @@ def test_key_value_store(time_machine):
@pytest.mark.usefixtures("init_persistence") @pytest.mark.usefixtures("init_persistence")
def test_set_startup_time(fee, time_machine): def test_set_startup_time(fee, time_machine):
create_mock_trades_usdt(fee) create_mock_trades_usdt(fee)
start = datetime.now(timezone.utc) start = datetime.now(UTC)
time_machine.move_to(start, tick=False) time_machine.move_to(start, tick=False)
set_startup_time() set_startup_time()

View File

@@ -1,5 +1,5 @@
# pragma pylint: disable=missing-docstring, C0103 # pragma pylint: disable=missing-docstring, C0103
from datetime import datetime, timedelta, timezone from datetime import UTC, datetime, timedelta
from types import FunctionType from types import FunctionType
import pytest import pytest
@@ -265,7 +265,7 @@ def test_interest(fee, exchange, is_short, lev, minutes, rate, interest, trading
stake_amount=20.0, stake_amount=20.0,
amount=30.0, amount=30.0,
open_rate=2.0, open_rate=2.0,
open_date=datetime.now(timezone.utc) - timedelta(minutes=minutes), open_date=datetime.now(UTC) - timedelta(minutes=minutes),
fee_open=fee.return_value, fee_open=fee.return_value,
fee_close=fee.return_value, fee_close=fee.return_value,
exchange=exchange, exchange=exchange,
@@ -605,7 +605,7 @@ def test_calc_open_close_trade_price(
stake_amount=60.0, stake_amount=60.0,
open_rate=2.0, open_rate=2.0,
amount=30.0, amount=30.0,
open_date=datetime.now(tz=timezone.utc) - timedelta(minutes=10), open_date=datetime.now(tz=UTC) - timedelta(minutes=10),
interest_rate=0.0005, interest_rate=0.0005,
fee_open=fee.return_value, fee_open=fee.return_value,
fee_close=fee.return_value, fee_close=fee.return_value,
@@ -812,7 +812,7 @@ def test_calc_open_trade_value(
stake_amount=60.0, stake_amount=60.0,
amount=30.0, amount=30.0,
open_rate=2.0, open_rate=2.0,
open_date=datetime.now(tz=timezone.utc) - timedelta(minutes=10), open_date=datetime.now(tz=UTC) - timedelta(minutes=10),
fee_open=fee_rate, fee_open=fee_rate,
fee_close=fee_rate, fee_close=fee_rate,
exchange=exchange, exchange=exchange,
@@ -863,7 +863,7 @@ def test_calc_close_trade_price(
stake_amount=60.0, stake_amount=60.0,
amount=30.0, amount=30.0,
open_rate=open_rate, open_rate=open_rate,
open_date=datetime.now(tz=timezone.utc) - timedelta(minutes=10), open_date=datetime.now(tz=UTC) - timedelta(minutes=10),
fee_open=fee_rate, fee_open=fee_rate,
fee_close=fee_rate, fee_close=fee_rate,
exchange=exchange, exchange=exchange,
@@ -1164,7 +1164,7 @@ def test_calc_profit(
stake_amount=60.0, stake_amount=60.0,
amount=30.0 * lev, amount=30.0 * lev,
open_rate=2.0, open_rate=2.0,
open_date=datetime.now(tz=timezone.utc) - timedelta(minutes=10), open_date=datetime.now(tz=UTC) - timedelta(minutes=10),
interest_rate=0.0005, interest_rate=0.0005,
exchange=exchange, exchange=exchange,
is_short=is_short, is_short=is_short,
@@ -1882,7 +1882,7 @@ def test_get_trades_proxy(fee, use_db, is_short):
assert len(trades) == 2 assert len(trades) == 2
assert not trades[0].is_open assert not trades[0].is_open
opendate = datetime.now(tz=timezone.utc) - timedelta(minutes=15) opendate = datetime.now(tz=UTC) - timedelta(minutes=15)
assert len(Trade.get_trades_proxy(open_date=opendate)) == 3 assert len(Trade.get_trades_proxy(open_date=opendate)) == 3
@@ -1989,7 +1989,7 @@ def test_fully_canceled_entry_order_count(fee, is_short):
@pytest.mark.usefixtures("init_persistence") @pytest.mark.usefixtures("init_persistence")
def test_update_order_from_ccxt(caplog, time_machine): def test_update_order_from_ccxt(caplog, time_machine):
start = datetime(2023, 1, 1, 4, tzinfo=timezone.utc) start = datetime(2023, 1, 1, 4, tzinfo=UTC)
time_machine.move_to(start, tick=False) time_machine.move_to(start, tick=False)
# Most basic order return (only has orderid) # Most basic order return (only has orderid)
@@ -2172,7 +2172,7 @@ def test_trade_truncates_string_fields():
stake_amount=20.0, stake_amount=20.0,
amount=30.0, amount=30.0,
open_rate=2.0, open_rate=2.0,
open_date=datetime.now(timezone.utc) - timedelta(minutes=20), open_date=datetime.now(UTC) - timedelta(minutes=20),
fee_open=0.001, fee_open=0.001,
fee_close=0.001, fee_close=0.001,
exchange="binance", exchange="binance",

View File

@@ -1,5 +1,5 @@
import json import json
from datetime import datetime, timezone from datetime import UTC, datetime
import pytest import pytest
@@ -182,7 +182,7 @@ def test_trade_fromjson():
assert trade.id == 25 assert trade.id == 25
assert trade.pair == "ETH/USDT" assert trade.pair == "ETH/USDT"
assert trade.open_date_utc == datetime(2022, 10, 18, 9, 12, 42, tzinfo=timezone.utc) assert trade.open_date_utc == datetime(2022, 10, 18, 9, 12, 42, tzinfo=UTC)
assert isinstance(trade.open_date, datetime) assert isinstance(trade.open_date, datetime)
assert trade.exit_reason == "no longer good" assert trade.exit_reason == "no longer good"
assert trade.realized_profit == 2.76315361 assert trade.realized_profit == 2.76315361
@@ -192,7 +192,7 @@ def test_trade_fromjson():
assert len(trade.orders) == 5 assert len(trade.orders) == 5
last_o = trade.orders[-1] last_o = trade.orders[-1]
assert last_o.order_filled_utc == datetime(2022, 10, 18, 9, 45, 22, tzinfo=timezone.utc) assert last_o.order_filled_utc == datetime(2022, 10, 18, 9, 45, 22, tzinfo=UTC)
assert isinstance(last_o.order_date, datetime) assert isinstance(last_o.order_date, datetime)
assert last_o.funding_fee == -0.055 assert last_o.funding_fee == -0.055

View File

@@ -1,4 +1,4 @@
from datetime import datetime, timedelta, timezone from datetime import UTC, datetime, timedelta
import pytest import pytest
@@ -62,7 +62,7 @@ def test_PairLocks(use_db):
pair = "BTC/USDT" pair = "BTC/USDT"
# Lock until 14:30 # Lock until 14:30
lock_time = datetime(2020, 5, 1, 14, 30, 0, tzinfo=timezone.utc) lock_time = datetime(2020, 5, 1, 14, 30, 0, tzinfo=UTC)
PairLocks.lock_pair(pair, lock_time) PairLocks.lock_pair(pair, lock_time)
assert not PairLocks.is_pair_locked(pair) assert not PairLocks.is_pair_locked(pair)
@@ -121,15 +121,15 @@ def test_PairLocks_getlongestlock(use_db):
assert PairLocks.is_pair_locked(pair) assert PairLocks.is_pair_locked(pair)
lock = PairLocks.get_pair_longest_lock(pair) lock = PairLocks.get_pair_longest_lock(pair)
assert lock.lock_end_time.replace(tzinfo=timezone.utc) > dt_now() + timedelta(minutes=3) assert lock.lock_end_time.replace(tzinfo=UTC) > dt_now() + timedelta(minutes=3)
assert lock.lock_end_time.replace(tzinfo=timezone.utc) < dt_now() + timedelta(minutes=14) assert lock.lock_end_time.replace(tzinfo=UTC) < dt_now() + timedelta(minutes=14)
PairLocks.lock_pair(pair, dt_now() + timedelta(minutes=15)) PairLocks.lock_pair(pair, dt_now() + timedelta(minutes=15))
assert PairLocks.is_pair_locked(pair) assert PairLocks.is_pair_locked(pair)
lock = PairLocks.get_pair_longest_lock(pair) lock = PairLocks.get_pair_longest_lock(pair)
# Must be longer than above # Must be longer than above
assert lock.lock_end_time.replace(tzinfo=timezone.utc) > dt_now() + timedelta(minutes=14) assert lock.lock_end_time.replace(tzinfo=UTC) > dt_now() + timedelta(minutes=14)
PairLocks.reset_locks() PairLocks.reset_locks()
PairLocks.use_db = True PairLocks.use_db = True

View File

@@ -1,4 +1,4 @@
from datetime import datetime, timezone from datetime import UTC, datetime
from unittest.mock import MagicMock from unittest.mock import MagicMock
import pandas as pd import pandas as pd
@@ -141,7 +141,7 @@ def test_gen_pairlist_with_valid_change_pair_list_config(mocker, rpl_config, tic
"lookback_days": 4, "lookback_days": 4,
} }
] ]
start = datetime(2024, 8, 1, 0, 0, 0, 0, tzinfo=timezone.utc) start = datetime(2024, 8, 1, 0, 0, 0, 0, tzinfo=UTC)
time_machine.move_to(start, tick=False) time_machine.move_to(start, tick=False)
mock_ohlcv_data = { mock_ohlcv_data = {
@@ -224,7 +224,7 @@ def test_filter_pairlist_with_empty_ticker(mocker, rpl_config, tickers, time_mac
"lookback_days": 4, "lookback_days": 4,
} }
] ]
start = datetime(2024, 8, 1, 0, 0, 0, 0, tzinfo=timezone.utc) start = datetime(2024, 8, 1, 0, 0, 0, 0, tzinfo=UTC)
time_machine.move_to(start, tick=False) time_machine.move_to(start, tick=False)
mock_ohlcv_data = { mock_ohlcv_data = {
@@ -291,7 +291,7 @@ def test_filter_pairlist_with_max_value_set(mocker, rpl_config, tickers, time_ma
} }
] ]
start = datetime(2024, 8, 1, 0, 0, 0, 0, tzinfo=timezone.utc) start = datetime(2024, 8, 1, 0, 0, 0, 0, tzinfo=UTC)
time_machine.move_to(start, tick=False) time_machine.move_to(start, tick=False)
mock_ohlcv_data = { mock_ohlcv_data = {

View File

@@ -1,5 +1,5 @@
import random import random
from datetime import datetime, timedelta, timezone from datetime import UTC, datetime, timedelta
import pytest import pytest
@@ -31,8 +31,8 @@ def generate_mock_trade(
stake_amount=0.01, stake_amount=0.01,
fee_open=fee, fee_open=fee,
fee_close=fee, fee_close=fee,
open_date=datetime.now(timezone.utc) - timedelta(minutes=min_ago_open or 200), open_date=datetime.now(UTC) - timedelta(minutes=min_ago_open or 200),
close_date=datetime.now(timezone.utc) - timedelta(minutes=min_ago_close or 30), close_date=datetime.now(UTC) - timedelta(minutes=min_ago_close or 30),
open_rate=open_rate, open_rate=open_rate,
is_open=is_open, is_open=is_open,
amount=0.01 / open_rate, amount=0.01 / open_rate,
@@ -99,9 +99,9 @@ def test_protectionmanager(mocker, default_conf):
for handler in freqtrade.protections._protection_handlers: for handler in freqtrade.protections._protection_handlers:
assert handler.name in AVAILABLE_PROTECTIONS assert handler.name in AVAILABLE_PROTECTIONS
if not handler.has_global_stop: if not handler.has_global_stop:
assert handler.global_stop(datetime.now(timezone.utc), "*") is None assert handler.global_stop(datetime.now(UTC), "*") is None
if not handler.has_local_stop: if not handler.has_local_stop:
assert handler.stop_per_pair("XRP/BTC", datetime.now(timezone.utc), "*") is None assert handler.stop_per_pair("XRP/BTC", datetime.now(UTC), "*") is None
@pytest.mark.parametrize( @pytest.mark.parametrize(
@@ -499,7 +499,7 @@ def test_CooldownPeriod_unlock_at(mocker, default_conf, fee, caplog, time_machin
assert not log_has_re(message, caplog) assert not log_has_re(message, caplog)
caplog.clear() caplog.clear()
start_dt = datetime(2024, 5, 2, 0, 30, 0, tzinfo=timezone.utc) start_dt = datetime(2024, 5, 2, 0, 30, 0, tzinfo=UTC)
time_machine.move_to(start_dt, tick=False) time_machine.move_to(start_dt, tick=False)
generate_mock_trade( generate_mock_trade(
@@ -527,7 +527,7 @@ def test_CooldownPeriod_unlock_at(mocker, default_conf, fee, caplog, time_machin
assert not PairLocks.is_global_lock() assert not PairLocks.is_global_lock()
# Force rollover to the next day. # Force rollover to the next day.
start_dt = datetime(2024, 5, 2, 22, 00, 0, tzinfo=timezone.utc) start_dt = datetime(2024, 5, 2, 22, 00, 0, tzinfo=UTC)
time_machine.move_to(start_dt, tick=False) time_machine.move_to(start_dt, tick=False)
generate_mock_trade( generate_mock_trade(
"ETH/BTC", "ETH/BTC",

View File

@@ -1,5 +1,5 @@
from copy import deepcopy from copy import deepcopy
from datetime import datetime, timedelta, timezone from datetime import UTC, datetime, timedelta
from unittest.mock import ANY, MagicMock, PropertyMock from unittest.mock import ANY, MagicMock, PropertyMock
import pytest import pytest
@@ -347,7 +347,7 @@ def test__rpc_timeunit_profit(
assert day["starting_balance"] in (pytest.approx(1062.37), pytest.approx(1066.46)) assert day["starting_balance"] in (pytest.approx(1062.37), pytest.approx(1066.46))
assert day["fiat_value"] in (0.0,) assert day["fiat_value"] in (0.0,)
# ensure first day is current date # ensure first day is current date
assert str(days["data"][0]["date"]) == str(datetime.now(timezone.utc).date()) assert str(days["data"][0]["date"]) == str(datetime.now(UTC).date())
# Try invalid data # Try invalid data
with pytest.raises(RPCException, match=r".*must be an integer greater than 0*"): with pytest.raises(RPCException, match=r".*must be an integer greater than 0*"):
@@ -1296,9 +1296,9 @@ def test_rpc_add_and_delete_lock(mocker, default_conf):
rpc = RPC(freqtradebot) rpc = RPC(freqtradebot)
pair = "ETH/BTC" pair = "ETH/BTC"
rpc._rpc_add_lock(pair, datetime.now(timezone.utc) + timedelta(minutes=4), "", "*") rpc._rpc_add_lock(pair, datetime.now(UTC) + timedelta(minutes=4), "", "*")
rpc._rpc_add_lock(pair, datetime.now(timezone.utc) + timedelta(minutes=5), "", "*") rpc._rpc_add_lock(pair, datetime.now(UTC) + timedelta(minutes=5), "", "*")
rpc._rpc_add_lock(pair, datetime.now(timezone.utc) + timedelta(minutes=10), "", "*") rpc._rpc_add_lock(pair, datetime.now(UTC) + timedelta(minutes=10), "", "*")
locks = rpc._rpc_locks() locks = rpc._rpc_locks()
assert locks["lock_count"] == 3 assert locks["lock_count"] == 3

View File

@@ -5,7 +5,7 @@ Unit test file for rpc/api_server.py
import asyncio import asyncio
import logging import logging
import time import time
from datetime import datetime, timedelta, timezone from datetime import UTC, datetime, timedelta
from pathlib import Path from pathlib import Path
from unittest.mock import ANY, MagicMock, PropertyMock from unittest.mock import ANY, MagicMock, PropertyMock
@@ -637,12 +637,12 @@ def test_api_locks(botclient):
[ [
{ {
"pair": "ETH/BTC", "pair": "ETH/BTC",
"until": f"{format_date(datetime.now(timezone.utc) + timedelta(minutes=4))}Z", "until": f"{format_date(datetime.now(UTC) + timedelta(minutes=4))}Z",
"reason": "randreason", "reason": "randreason",
}, },
{ {
"pair": "XRP/BTC", "pair": "XRP/BTC",
"until": f"{format_date(datetime.now(timezone.utc) + timedelta(minutes=20))}Z", "until": f"{format_date(datetime.now(UTC) + timedelta(minutes=20))}Z",
"reason": "deadbeef", "reason": "deadbeef",
}, },
], ],
@@ -711,7 +711,7 @@ def test_api_daily(botclient, mocker, ticker, fee, markets):
assert len(response["data"]) == 7 assert len(response["data"]) == 7
assert response["stake_currency"] == "BTC" assert response["stake_currency"] == "BTC"
assert response["fiat_display_currency"] == "USD" assert response["fiat_display_currency"] == "USD"
assert response["data"][0]["date"] == str(datetime.now(timezone.utc).date()) assert response["data"][0]["date"] == str(datetime.now(UTC).date())
def test_api_weekly(botclient, mocker, ticker, fee, markets, time_machine): def test_api_weekly(botclient, mocker, ticker, fee, markets, time_machine):
@@ -1695,7 +1695,7 @@ def test_api_force_entry(botclient, mocker, fee, endpoint):
exchange="binance", exchange="binance",
stake_amount=1, stake_amount=1,
open_rate=0.245441, open_rate=0.245441,
open_date=datetime.now(timezone.utc), open_date=datetime.now(UTC),
is_open=False, is_open=False,
is_short=False, is_short=False,
fee_close=fee.return_value, fee_close=fee.return_value,

View File

@@ -4,7 +4,7 @@ Unit test file for rpc/external_message_consumer.py
import asyncio import asyncio
import logging import logging
from datetime import datetime, timezone from datetime import UTC, datetime
from unittest.mock import MagicMock from unittest.mock import MagicMock
import pytest import pytest
@@ -99,7 +99,7 @@ def test_emc_handle_producer_message(patched_emc, caplog, ohlcv_history):
"data": { "data": {
"key": ("BTC/USDT", "5m", "spot"), "key": ("BTC/USDT", "5m", "spot"),
"df": ohlcv_history, "df": ohlcv_history,
"la": datetime.now(timezone.utc), "la": datetime.now(UTC),
}, },
} }
patched_emc.handle_producer_message(test_producer, df_message) patched_emc.handle_producer_message(test_producer, df_message)
@@ -123,7 +123,7 @@ def test_emc_handle_producer_message(patched_emc, caplog, ohlcv_history):
malformed_message = { malformed_message = {
"type": "analyzed_df", "type": "analyzed_df",
"data": {"key": "BTC/USDT", "df": ohlcv_history, "la": datetime.now(timezone.utc)}, "data": {"key": "BTC/USDT", "df": ohlcv_history, "la": datetime.now(UTC)},
} }
patched_emc.handle_producer_message(test_producer, malformed_message) patched_emc.handle_producer_message(test_producer, malformed_message)
@@ -137,7 +137,7 @@ def test_emc_handle_producer_message(patched_emc, caplog, ohlcv_history):
"data": { "data": {
"key": ("BTC/USDT", "5m", "spot"), "key": ("BTC/USDT", "5m", "spot"),
"df": ohlcv_history.loc[ohlcv_history["open"] < 0], "df": ohlcv_history.loc[ohlcv_history["open"] < 0],
"la": datetime.now(timezone.utc), "la": datetime.now(UTC),
}, },
} }
patched_emc.handle_producer_message(test_producer, malformed_message) patched_emc.handle_producer_message(test_producer, malformed_message)

View File

@@ -1,4 +1,4 @@
from datetime import datetime, timezone from datetime import UTC, datetime
import pytest import pytest
from pandas import DataFrame from pandas import DataFrame
@@ -47,7 +47,7 @@ def test_strategy_test_v3(dataframe_1m, fee, is_short, side):
amount=0.1, amount=0.1,
rate=20000, rate=20000,
time_in_force="gtc", time_in_force="gtc",
current_time=datetime.now(timezone.utc), current_time=datetime.now(UTC),
side=side, side=side,
entry_tag=None, entry_tag=None,
) )
@@ -63,7 +63,7 @@ def test_strategy_test_v3(dataframe_1m, fee, is_short, side):
time_in_force="gtc", time_in_force="gtc",
exit_reason="roi", exit_reason="roi",
sell_reason="roi", sell_reason="roi",
current_time=datetime.now(timezone.utc), current_time=datetime.now(UTC),
side=side, side=side,
) )
is True is True

View File

@@ -1,7 +1,7 @@
# pragma pylint: disable=missing-docstring, C0103 # pragma pylint: disable=missing-docstring, C0103
import logging import logging
import math import math
from datetime import datetime, timedelta, timezone from datetime import UTC, datetime, timedelta
from pathlib import Path from pathlib import Path
from unittest.mock import MagicMock from unittest.mock import MagicMock
@@ -208,7 +208,7 @@ def test_ignore_expired_candle(default_conf):
strategy = StrategyResolver.load_strategy(default_conf) strategy = StrategyResolver.load_strategy(default_conf)
strategy.ignore_buying_expired_candle_after = 60 strategy.ignore_buying_expired_candle_after = 60
latest_date = datetime(2020, 12, 30, 7, 0, 0, tzinfo=timezone.utc) latest_date = datetime(2020, 12, 30, 7, 0, 0, tzinfo=UTC)
# Add 1 candle length as the "latest date" defines candle open. # Add 1 candle length as the "latest date" defines candle open.
current_time = latest_date + timedelta(seconds=80 + 300) current_time = latest_date + timedelta(seconds=80 + 300)
@@ -765,7 +765,7 @@ def test_leverage_callback(default_conf, side) -> None:
assert ( assert (
strategy.leverage( strategy.leverage(
pair="XRP/USDT", pair="XRP/USDT",
current_time=datetime.now(timezone.utc), current_time=datetime.now(UTC),
current_rate=2.2, current_rate=2.2,
proposed_leverage=1.0, proposed_leverage=1.0,
max_leverage=5.0, max_leverage=5.0,
@@ -780,7 +780,7 @@ def test_leverage_callback(default_conf, side) -> None:
assert ( assert (
strategy.leverage( strategy.leverage(
pair="XRP/USDT", pair="XRP/USDT",
current_time=datetime.now(timezone.utc), current_time=datetime.now(UTC),
current_rate=2.2, current_rate=2.2,
proposed_leverage=1.0, proposed_leverage=1.0,
max_leverage=5.0, max_leverage=5.0,
@@ -897,7 +897,7 @@ def test_is_pair_locked(default_conf):
pair = "BTC/USDT" pair = "BTC/USDT"
# Lock until 14:30 # Lock until 14:30
lock_time = datetime(2020, 5, 1, 14, 30, 0, tzinfo=timezone.utc) lock_time = datetime(2020, 5, 1, 14, 30, 0, tzinfo=UTC)
# Subtract 2 seconds, as locking rounds up to the next candle. # Subtract 2 seconds, as locking rounds up to the next candle.
strategy.lock_pair(pair, lock_time - timedelta(seconds=2)) strategy.lock_pair(pair, lock_time - timedelta(seconds=2))

View File

@@ -1,4 +1,4 @@
from datetime import datetime, timedelta, timezone from datetime import UTC, datetime, timedelta
import pytest import pytest
import time_machine import time_machine
@@ -21,14 +21,14 @@ from freqtrade.util.datetime_helpers import dt_humanize_delta
def test_dt_now(): def test_dt_now():
with time_machine.travel("2021-09-01 05:01:00 +00:00", tick=False) as t: with time_machine.travel("2021-09-01 05:01:00 +00:00", tick=False) as t:
now = datetime.now(timezone.utc) now = datetime.now(UTC)
assert dt_now() == now assert dt_now() == now
assert dt_ts() == int(now.timestamp() * 1000) assert dt_ts() == int(now.timestamp() * 1000)
assert dt_ts(now) == int(now.timestamp() * 1000) assert dt_ts(now) == int(now.timestamp() * 1000)
t.shift(timedelta(hours=5)) t.shift(timedelta(hours=5))
assert dt_now() >= now assert dt_now() >= now
assert dt_now() == datetime.now(timezone.utc) assert dt_now() == datetime.now(UTC)
assert dt_ts() == int(dt_now().timestamp() * 1000) assert dt_ts() == int(dt_now().timestamp() * 1000)
# Test with different time than now # Test with different time than now
assert dt_ts(now) == int(now.timestamp() * 1000) assert dt_ts(now) == int(now.timestamp() * 1000)
@@ -37,42 +37,42 @@ def test_dt_now():
def test_dt_ts_def(): def test_dt_ts_def():
assert dt_ts_def(None) == 0 assert dt_ts_def(None) == 0
assert dt_ts_def(None, 123) == 123 assert dt_ts_def(None, 123) == 123
assert dt_ts_def(datetime(2023, 5, 5, tzinfo=timezone.utc)) == 1683244800000 assert dt_ts_def(datetime(2023, 5, 5, tzinfo=UTC)) == 1683244800000
assert dt_ts_def(datetime(2023, 5, 5, tzinfo=timezone.utc), 123) == 1683244800000 assert dt_ts_def(datetime(2023, 5, 5, tzinfo=UTC), 123) == 1683244800000
def test_dt_ts_none(): def test_dt_ts_none():
assert dt_ts_none(None) is None assert dt_ts_none(None) is None
assert dt_ts_none(None) is None assert dt_ts_none(None) is None
assert dt_ts_none(datetime(2023, 5, 5, tzinfo=timezone.utc)) == 1683244800000 assert dt_ts_none(datetime(2023, 5, 5, tzinfo=UTC)) == 1683244800000
assert dt_ts_none(datetime(2023, 5, 5, tzinfo=timezone.utc)) == 1683244800000 assert dt_ts_none(datetime(2023, 5, 5, tzinfo=UTC)) == 1683244800000
def test_dt_utc(): def test_dt_utc():
assert dt_utc(2023, 5, 5) == datetime(2023, 5, 5, tzinfo=timezone.utc) assert dt_utc(2023, 5, 5) == datetime(2023, 5, 5, tzinfo=UTC)
assert dt_utc(2023, 5, 5, 0, 0, 0, 555500) == datetime( assert dt_utc(2023, 5, 5, 0, 0, 0, 555500) == datetime(
2023, 5, 5, 0, 0, 0, 555500, tzinfo=timezone.utc 2023, 5, 5, 0, 0, 0, 555500, tzinfo=UTC
) )
@pytest.mark.parametrize("as_ms", [True, False]) @pytest.mark.parametrize("as_ms", [True, False])
def test_dt_from_ts(as_ms): def test_dt_from_ts(as_ms):
multi = 1000 if as_ms else 1 multi = 1000 if as_ms else 1
assert dt_from_ts(1683244800.0 * multi) == datetime(2023, 5, 5, tzinfo=timezone.utc) assert dt_from_ts(1683244800.0 * multi) == datetime(2023, 5, 5, tzinfo=UTC)
assert dt_from_ts(1683244800.5555 * multi) == datetime( assert dt_from_ts(1683244800.5555 * multi) == datetime(
2023, 5, 5, 0, 0, 0, 555500, tzinfo=timezone.utc 2023, 5, 5, 0, 0, 0, 555500, tzinfo=UTC
) )
# As int # As int
assert dt_from_ts(1683244800 * multi) == datetime(2023, 5, 5, tzinfo=timezone.utc) assert dt_from_ts(1683244800 * multi) == datetime(2023, 5, 5, tzinfo=UTC)
# As milliseconds # As milliseconds
assert dt_from_ts(1683244800 * multi) == datetime(2023, 5, 5, tzinfo=timezone.utc) assert dt_from_ts(1683244800 * multi) == datetime(2023, 5, 5, tzinfo=UTC)
assert dt_from_ts(1683242400 * multi) == datetime(2023, 5, 4, 23, 20, tzinfo=timezone.utc) assert dt_from_ts(1683242400 * multi) == datetime(2023, 5, 4, 23, 20, tzinfo=UTC)
def test_dt_floor_day(): def test_dt_floor_day():
now = datetime(2023, 9, 1, 5, 2, 3, 455555, tzinfo=timezone.utc) now = datetime(2023, 9, 1, 5, 2, 3, 455555, tzinfo=UTC)
assert dt_floor_day(now) == datetime(2023, 9, 1, tzinfo=timezone.utc) assert dt_floor_day(now) == datetime(2023, 9, 1, tzinfo=UTC)
def test_shorten_date() -> None: def test_shorten_date() -> None:
@@ -95,21 +95,21 @@ def test_format_ms_time() -> None:
date_in_epoch_ms = 1523383321132 date_in_epoch_ms = 1523383321132
date = format_ms_time(date_in_epoch_ms) date = format_ms_time(date_in_epoch_ms)
assert isinstance(date, str) assert isinstance(date, str)
res = datetime(2018, 4, 10, 18, 2, 1, tzinfo=timezone.utc) res = datetime(2018, 4, 10, 18, 2, 1, tzinfo=UTC)
assert date == res.strftime("%Y-%m-%dT%H:%M:%S") assert date == res.strftime("%Y-%m-%dT%H:%M:%S")
assert date == "2018-04-10T18:02:01" assert date == "2018-04-10T18:02:01"
res = datetime(2017, 12, 13, 8, 2, 1, tzinfo=timezone.utc) res = datetime(2017, 12, 13, 8, 2, 1, tzinfo=UTC)
# Date 2017-12-13 08:02:01 # Date 2017-12-13 08:02:01
date_in_epoch_ms = 1513152121000 date_in_epoch_ms = 1513152121000
assert format_ms_time(date_in_epoch_ms) == res.strftime("%Y-%m-%dT%H:%M:%S") assert format_ms_time(date_in_epoch_ms) == res.strftime("%Y-%m-%dT%H:%M:%S")
def test_format_date() -> None: def test_format_date() -> None:
date = datetime(2023, 9, 1, 5, 2, 3, 455555, tzinfo=timezone.utc) date = datetime(2023, 9, 1, 5, 2, 3, 455555, tzinfo=UTC)
assert format_date(date) == "2023-09-01 05:02:03" assert format_date(date) == "2023-09-01 05:02:03"
assert format_date(None) == "" assert format_date(None) == ""
date = datetime(2021, 9, 30, 22, 59, 3, 455555, tzinfo=timezone.utc) date = datetime(2021, 9, 30, 22, 59, 3, 455555, tzinfo=UTC)
assert format_date(date) == "2021-09-30 22:59:03" assert format_date(date) == "2021-09-30 22:59:03"
assert format_date(None) == "" assert format_date(None) == ""
@@ -119,10 +119,10 @@ def test_format_ms_time_detailed() -> None:
date_in_epoch_ms = 1523383321132 date_in_epoch_ms = 1523383321132
date = format_ms_time_det(date_in_epoch_ms) date = format_ms_time_det(date_in_epoch_ms)
assert isinstance(date, str) assert isinstance(date, str)
res = datetime(2018, 4, 10, 18, 2, 1, 132145, tzinfo=timezone.utc) res = datetime(2018, 4, 10, 18, 2, 1, 132145, tzinfo=UTC)
assert date == res.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] assert date == res.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3]
assert date == "2018-04-10T18:02:01.132" assert date == "2018-04-10T18:02:01.132"
res = datetime(2017, 12, 13, 8, 2, 1, 512321, tzinfo=timezone.utc) res = datetime(2017, 12, 13, 8, 2, 1, 512321, tzinfo=UTC)
# Date 2017-12-13 08:02:01 # Date 2017-12-13 08:02:01
date_in_epoch_ms = 1513152121512 date_in_epoch_ms = 1513152121512
assert format_ms_time_det(date_in_epoch_ms) == res.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] assert format_ms_time_det(date_in_epoch_ms) == res.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3]