Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Modify some tests so they pass on windows #6398

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion rotkehlchen/tests/api/blockchain/test_evm.py
Original file line number Diff line number Diff line change
Expand Up @@ -394,7 +394,7 @@ def patch_single_query(**kwargs): # pylint: disable=unused-argument
assert not api_task_greenlets[idx].dead

# now delete one address from api task and 1 from periodic task manager and see it's immediate
with gevent.Timeout(2):
with gevent.Timeout(5):
for address in (api_addies[0], task_manager_addy):
response = requests.delete(
api_url_for(
Expand Down
2 changes: 1 addition & 1 deletion rotkehlchen/tests/api/test_async.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ def test_query_async_tasks(rotkehlchen_api_server_with_exchanges):

binance_patch = patch.object(binance.session, 'get', side_effect=mock_binance_balance_response)

# Check querying the async taks resource when no async task is scheduled
# Check querying the async task resource when no async task is scheduled
response = requests.get(api_url_for(server, 'asynctasksresource'))
result = assert_proper_response_with_result(response)
assert result == {'completed': [], 'pending': []}
Expand Down
22 changes: 18 additions & 4 deletions rotkehlchen/tests/api/test_database.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import pytest
import requests

from rotkehlchen.api.server import APIServer
from rotkehlchen.db.settings import ROTKEHLCHEN_DB_VERSION
from rotkehlchen.tests.utils.api import (
api_url_for,
Expand All @@ -17,7 +18,12 @@


@pytest.mark.parametrize('start_with_logged_in_user', [True, False])
def test_query_db_info(rotkehlchen_api_server, data_dir, username, start_with_logged_in_user):
def test_query_db_info(
rotkehlchen_api_server: APIServer,
data_dir: Path,
username: str,
start_with_logged_in_user: bool,
):
"""Test that retrieving user and global database details works fine"""
if start_with_logged_in_user:
backup1 = Path(data_dir / username / '1624053928_rotkehlchen_db_v26.backup')
Expand All @@ -35,7 +41,7 @@ def test_query_db_info(rotkehlchen_api_server, data_dir, username, start_with_lo

if start_with_logged_in_user:
userdb = result['userdb']
assert userdb['info']['filepath'] == f'{data_dir}/{username}/rotkehlchen.db'
assert userdb['info']['filepath'] == str(data_dir / username / 'rotkehlchen.db')
assert userdb['info']['size'] >= 300000 # just from comparison at tests
assert userdb['info']['version'] == ROTKEHLCHEN_DB_VERSION
assert len(userdb['backups']) == 3
Expand All @@ -44,7 +50,11 @@ def test_query_db_info(rotkehlchen_api_server, data_dir, username, start_with_lo
assert {'size': len(backup1_contents), 'time': 1624053928, 'version': 26} in userdb['backups'] # noqa: E501


def test_create_download_delete_backup(rotkehlchen_api_server, data_dir, username):
def test_create_download_delete_backup(
rotkehlchen_api_server: APIServer,
data_dir: Path,
username: str,
):
"""Test that creating, downloading and deleting a backup works fine"""
start_ts = ts_now()
response = requests.put(api_url_for(rotkehlchen_api_server, 'databasebackupsresource'))
Expand Down Expand Up @@ -88,7 +98,11 @@ def test_create_download_delete_backup(rotkehlchen_api_server, data_dir, usernam
assert len(backups) == 0


def test_delete_download_backup_errors(rotkehlchen_api_server, data_dir, username):
def test_delete_download_backup_errors(
rotkehlchen_api_server: APIServer,
data_dir: Path,
username: str,
):
"""Test that errors are handled properly in backup deletion and download"""
user_data_dir = Path(data_dir, username)
# Make sure deleting file outside of user data dir fails
Expand Down
2 changes: 1 addition & 1 deletion rotkehlchen/tests/api/test_eth2.py
Original file line number Diff line number Diff line change
Expand Up @@ -297,7 +297,7 @@ def test_query_eth2_deposits_details_and_stats(rotkehlchen_api_server, ethereum_
def test_eth2_add_eth1_account(rotkehlchen_api_server):
"""This test uses real data and tests that adding an ETH1 address with
ETH2 deposits properly detects validators"""
new_account = '0xa966B0eabCD717fa28Bd165F1cE160E7057FA369'
new_account = '0xa966B0eabCD717fa28Bd165F1cE160E7057FA369' # exited
LefterisJP marked this conversation as resolved.
Show resolved Hide resolved
async_query = random.choice([False, True])
rotki = rotkehlchen_api_server.rest_api.rotkehlchen
setup = setup_balances(
Expand Down
5 changes: 3 additions & 2 deletions rotkehlchen/tests/api/test_liquity.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import requests
from flaky import flaky

from rotkehlchen.api.server import APIServer
from rotkehlchen.chain.evm.types import string_to_evm_address
from rotkehlchen.constants.assets import A_ETH, A_LQTY, A_LUSD
from rotkehlchen.fval import FVal
Expand Down Expand Up @@ -219,7 +220,7 @@ def mocked_request_dict(url, *_args, **_kwargs):
'0xbB8311c7bAD518f0D8f907Cad26c5CcC85a06dC4',
],
])
def test_staking_stats(rotkehlchen_api_server, ethereum_accounts):
def test_staking_stats(rotkehlchen_api_server: APIServer, ethereum_accounts: list[str]):
"""
Test that the stats generated by the liquity endpoint are correct using pre-queried
information and that the stats combining all the data are consistent with the
Expand Down Expand Up @@ -252,7 +253,7 @@ def test_staking_stats(rotkehlchen_api_server, ethereum_accounts):
assert len(global_stats['staking_gains']) == 3
assert len(global_stats['stability_pool_gains']) == 2
assert FVal(global_stats['stability_pool_gains'][0]['amount']).is_close(FVal(address_0_data['stability_pool_gains'][0]['amount']) + FVal(address_1_data['stability_pool_gains'][0]['amount']), max_diff='1e-8') # noqa: E501
assert address_0_data['stability_pool_gains'][0]['amount'] == '1.7820064710306824'
assert FVal(address_0_data['stability_pool_gains'][0]['amount']).is_close(FVal('1.7820064710306824')) # noqa: E501
assert address_1_data['stability_pool_gains'][0]['amount'] == '12.294706987216218'
assert address_1_data['stability_pool_gains'][1]['amount'] == '4240.34942308358'

Expand Down
19 changes: 15 additions & 4 deletions rotkehlchen/tests/api/test_user_assets.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import requests

from rotkehlchen.accounting.structures.balance import BalanceType
from rotkehlchen.api.server import APIServer
from rotkehlchen.assets.asset import Asset, EvmToken
from rotkehlchen.assets.types import AssetType
from rotkehlchen.balances.manual import ManuallyTrackedBalance
Expand All @@ -21,7 +22,7 @@
strethaddress_to_identifier,
)
from rotkehlchen.fval import FVal
from rotkehlchen.globaldb.handler import GLOBAL_DB_VERSION
from rotkehlchen.globaldb.handler import GLOBAL_DB_VERSION, GlobalDBHandler
from rotkehlchen.tests.utils.api import (
api_url_for,
assert_error_response,
Expand Down Expand Up @@ -875,7 +876,11 @@ def assert_db() -> None:
@pytest.mark.parametrize('use_clean_caching_directory', [True])
@pytest.mark.parametrize('start_with_logged_in_user', [True])
@pytest.mark.parametrize('with_custom_path', [False, True])
def test_exporting_user_assets_list(rotkehlchen_api_server, globaldb, with_custom_path):
def test_exporting_user_assets_list(
rotkehlchen_api_server: APIServer,
globaldb: GlobalDBHandler,
with_custom_path: bool,
):
"""Test that the endpoint for exporting user assets works correctly"""
eth_address = make_evm_address()
identifier = ethaddress_to_identifier(eth_address)
Expand All @@ -889,7 +894,9 @@ def test_exporting_user_assets_list(rotkehlchen_api_server, globaldb, with_custo
coingecko='YAB',
cryptocompare='YAB',
))
with tempfile.TemporaryDirectory() as path:
with tempfile.TemporaryDirectory(
ignore_cleanup_errors=True, # needed on windows, see https://tinyurl.com/tmp-win-err
) as path:
if with_custom_path:
response = requests.put(
api_url_for(
Expand Down Expand Up @@ -952,7 +959,11 @@ def test_exporting_user_assets_list(rotkehlchen_api_server, globaldb, with_custo
@pytest.mark.parametrize('start_with_logged_in_user', [True])
@pytest.mark.parametrize('method', ['post', 'put'])
@pytest.mark.parametrize('file_type', ['zip', 'json'])
def test_importing_user_assets_list(rotkehlchen_api_server, method, file_type):
def test_importing_user_assets_list(
rotkehlchen_api_server: APIServer,
method: str,
file_type: str,
):
"""Test that the endpoint for importing user assets works correctly"""
dir_path = Path(__file__).resolve().parent.parent
if file_type == 'zip':
Expand Down
50 changes: 35 additions & 15 deletions rotkehlchen/tests/api/test_users.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
import dataclasses
import os
import random
import shutil
from contextlib import ExitStack
from http import HTTPStatus
from pathlib import Path
from typing import Any, Optional
from unittest import mock

import pytest
import requests

from pysqlcipher3 import dbapi2 as sqlcipher
from rotkehlchen.api.server import APIServer
from rotkehlchen.db.drivers.gevent import DBConnection, DBConnectionType
from rotkehlchen.db.settings import ROTKEHLCHEN_DB_VERSION, DBSettings
from rotkehlchen.premium.premium import PremiumCredentials
Expand Down Expand Up @@ -47,7 +49,7 @@ def check_proper_unlock_result(
assert response_data['settings'][setting_to_check] == value


def check_user_status(api_server) -> dict[str, str]:
def check_user_status(api_server: APIServer) -> dict[str, str]:
# Check users status
response = requests.get(
api_url_for(api_server, 'usersresource'),
Expand All @@ -56,7 +58,7 @@ def check_user_status(api_server) -> dict[str, str]:
return result


def test_loggedin_user_querying(rotkehlchen_api_server, username, data_dir):
def test_loggedin_user_querying(rotkehlchen_api_server: APIServer, username: str, data_dir: Path):
"""Start with a logged in user and make sure we can query all users"""
Path(data_dir / 'another_user').mkdir()
Path(data_dir / 'another_user' / 'rotkehlchen.db').touch()
Expand All @@ -68,7 +70,11 @@ def test_loggedin_user_querying(rotkehlchen_api_server, username, data_dir):


@pytest.mark.parametrize('start_with_logged_in_user', [False])
def test_not_loggedin_user_querying(rotkehlchen_api_server, username, data_dir):
def test_not_loggedin_user_querying(
rotkehlchen_api_server: APIServer,
username: str,
data_dir: Path,
):
"""Start without logged in user and make sure we can query all users"""
Path(data_dir / 'another_user').mkdir()
Path(data_dir / 'another_user' / 'rotkehlchen.db').touch()
Expand Down Expand Up @@ -144,9 +150,16 @@ def test_user_creation_with_no_analytics(rotkehlchen_api_server, data_dir):

@pytest.mark.parametrize('use_clean_caching_directory', [True])
@pytest.mark.parametrize('start_with_logged_in_user', [False])
def test_user_creation_permission_error(rotkehlchen_api_server, data_dir):
@mock.patch.object(
LefterisJP marked this conversation as resolved.
Show resolved Hide resolved
Path, 'mkdir',
side_effect=PermissionError(
'Failed to create directory for user: [Errno 13] Permission denied',
),
)
def test_user_creation_permission_error(
mock_path_mkdir, rotkehlchen_api_server, # pylint:disable=unused-argument
):
"""Test that creating a user when data directory permissions are wrong is handled"""
os.chmod(data_dir, 0o200)
username = 'hania'
data = {
'name': username,
Expand All @@ -162,7 +175,6 @@ def test_user_creation_permission_error(rotkehlchen_api_server, data_dir):
contained_in_msg='Failed to create directory for user: [Errno 13] Permission denied',
status_code=HTTPStatus.CONFLICT,
)
os.chmod(data_dir, 0o777)


@pytest.mark.parametrize('start_with_logged_in_user', [False])
Expand Down Expand Up @@ -406,7 +418,10 @@ def test_user_creation_errors(rotkehlchen_api_server, data_dir):
)


def test_user_creation_with_already_loggedin_user(rotkehlchen_api_server, username):
def test_user_creation_with_already_loggedin_user(
rotkehlchen_api_server: APIServer,
username: str,
):
"""Test that creating a user while another one is logged in fails"""
# Missing username
data = {
Expand Down Expand Up @@ -761,7 +776,7 @@ def test_user_login(rotkehlchen_api_server, username, db_password, data_dir):
)


def test_user_set_premium_credentials(rotkehlchen_api_server, username):
def test_user_set_premium_credentials(rotkehlchen_api_server: APIServer, username: str):
"""Test that setting the premium credentials endpoint works.

We mock the server accepting the premium credentials
Expand Down Expand Up @@ -824,14 +839,16 @@ def test_user_del_premium_credentials(rotkehlchen_api_server, username):

@pytest.mark.parametrize('use_clean_caching_directory', [True])
@pytest.mark.parametrize('start_with_logged_in_user', [False])
def test_user_login_user_dir_permission_error(rotkehlchen_api_server, data_dir):
@mock.patch.object(Path, 'exists', side_effect=PermissionError)
def test_user_login_user_dir_permission_error(
mock_path_exists, rotkehlchen_api_server, data_dir, # pylint: disable=unused-argument
):
"""Test that user login with userdir path permission errors is handled properly"""
username = 'a_user'
user_dir = Path(data_dir / username)
user_dir.mkdir()
db_path = Path(data_dir / username / 'rotkehlchen.db')
db_path.touch()
os.chmod(user_dir, 0o200)
data = {'password': '123', 'sync_approval': 'unknown', 'async_query': True}
rotki = rotkehlchen_api_server.rest_api.rotkehlchen

Expand All @@ -853,14 +870,18 @@ def test_user_login_user_dir_permission_error(rotkehlchen_api_server, data_dir):

@pytest.mark.parametrize('use_clean_caching_directory', [True])
@pytest.mark.parametrize('start_with_logged_in_user', [False])
def test_user_login_db_permission_error(rotkehlchen_api_server, data_dir):
@mock.patch.object(
DBConnection, '__init__', side_effect=sqlcipher.OperationalError, # pylint: disable=no-member
)
def test_user_login_db_permission_error(
mock_db_conn, rotkehlchen_api_server, data_dir, # pylint: disable=unused-argument
):
"""Test that user login with db path permission errors is handled properly"""
username = 'a_user'
user_dir = Path(data_dir / username)
user_dir.mkdir()
db_path = Path(data_dir / username / 'rotkehlchen.db')
db_path.touch()
os.chmod(db_path, 0o200)
data = {'password': '123', 'sync_approval': 'unknown', 'async_query': True}
rotki = rotkehlchen_api_server.rest_api.rotkehlchen

Expand All @@ -878,10 +899,9 @@ def test_user_login_db_permission_error(rotkehlchen_api_server, data_dir):
contained_in_msg='Could not open database file',
status_code=HTTPStatus.CONFLICT,
)
os.chmod(db_path, 0o777)


def test_user_set_premium_credentials_errors(rotkehlchen_api_server, username):
def test_user_set_premium_credentials_errors(rotkehlchen_api_server: APIServer, username: str):
"""Test that setting the premium credentials endpoint reacts properly to bad input"""
# Set premium credentials for non-logged in user
data = {'premium_api_key': 'dadssad', 'premium_api_secret': 'jhjhkh'}
Expand Down
3 changes: 3 additions & 0 deletions rotkehlchen/tests/fixtures/accounting.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import os
import shutil
import sys
from collections import defaultdict
from pathlib import Path
from typing import Optional
Expand Down Expand Up @@ -28,6 +29,8 @@
@pytest.fixture(name='use_clean_caching_directory')
def fixture_use_clean_caching_directory():
"""If this is set to True then a clean test user directory will be used."""
if sys.platform == 'win32': # need clean data dir only in Windows TODO: Figure out why # noqa: E501
return True
return False


Expand Down
Loading