Skip to content

Commit

Permalink
Extend tests
Browse files Browse the repository at this point in the history
  • Loading branch information
drew2a committed Dec 29, 2021
1 parent 0901e0e commit 4f4ab66
Show file tree
Hide file tree
Showing 3 changed files with 78 additions and 17 deletions.
6 changes: 4 additions & 2 deletions src/tribler-common/tribler_common/patch_import.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
Original module distributes under Apache License 2.0.
"""
import builtins
from typing import List
from typing import List, Union
from unittest.mock import MagicMock, patch

__all__ = ['patch_import']
Expand All @@ -16,7 +16,7 @@
_builtins_import = builtins.__import__


def patch_import(modules=List[str], strict: bool = False, always_raise_exception_on_import=False, **mock_kwargs):
def patch_import(modules=Union[List[str], str], strict: bool = False, always_raise_exception_on_import=False, **mock_kwargs):
"""
Mocks import statement, and disable ImportError if a module
could not be imported.
Expand All @@ -30,6 +30,8 @@ def patch_import(modules=List[str], strict: bool = False, always_raise_exception
:param mock_kwargs: kwargs for MagicMock object.
:return: patch object
"""
if isinstance(modules, str):
modules = [modules]

def try_import(module_name, *args, **kwargs):
is_the_target_module = any((module_name == m or module_name.startswith(m + '.') for m in modules))
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
from unittest.mock import MagicMock, Mock, patch

import pytest

from tribler_common.patch_import import patch_import
from tribler_common.sentry_reporter.sentry_reporter import (
EXCEPTION, OS_ENVIRON,
PLATFORM_DETAILS,
Expand All @@ -19,8 +22,71 @@ def sentry_reporter():
return SentryReporter()


def test_init(sentry_reporter):
assert sentry_reporter.init('')
@patch('tribler_common.sentry_reporter.sentry_reporter.sentry_sdk.init')
def test_init(mocked_init: Mock, sentry_reporter: SentryReporter):
# test that `init` method set all necessary variables and calls `sentry_sdk.init()`
sentry_reporter.init(sentry_url='url', release_version='release', scrubber=SentryScrubber(),
strategy=SentryStrategy.SEND_SUPPRESSED)
assert sentry_reporter.scrubber
assert sentry_reporter.global_strategy == SentryStrategy.SEND_SUPPRESSED
mocked_init.assert_called_once()


@patch('tribler_common.sentry_reporter.sentry_reporter.ignore_logger')
def test_ignore_logger(mocked_ignore_logger: Mock, sentry_reporter: SentryReporter):
# test that `ignore_logger` calls `ignore_logger` from sentry_sdk
sentry_reporter.ignore_logger('logger name')
mocked_ignore_logger.assert_called_with('logger name')


@patch('tribler_common.sentry_reporter.sentry_reporter.sentry_sdk.add_breadcrumb')
def test_add_breadcrumb(mocked_add_breadcrumb: Mock, sentry_reporter: SentryReporter):
# test that `add_breadcrumb` passes all necessary arguments to `sentry_sdk`
assert sentry_reporter.add_breadcrumb('message', 'category', 'level', named_arg='some')
mocked_add_breadcrumb.assert_called_with({'message': 'message', 'category': 'category', 'level': 'level'},
named_arg='some')


def test_get_confirmation(sentry_reporter: SentryReporter):
# test that `get_confirmation` calls `QApplication` and `QMessageBox` from `PyQt5.QtWidgets`
mocked_QApplication = Mock()
mocked_QMessageBox = MagicMock()

with patch_import('PyQt5.QtWidgets', strict=True, QApplication=mocked_QApplication, QMessageBox=mocked_QMessageBox):
sentry_reporter.get_confirmation(Exception('test'))
mocked_QApplication.assert_called()
mocked_QMessageBox.assert_called()


@patch('tribler_common.sentry_reporter.sentry_reporter.sentry_sdk.capture_exception')
def test_capture_exception(mocked_capture_exception: Mock, sentry_reporter: SentryReporter):
# test that `capture_exception` passes an exception to `sentry_sdk`
exception = Exception('test')
sentry_reporter.capture_exception(exception)
mocked_capture_exception.assert_called_with(exception)


@patch('tribler_common.sentry_reporter.sentry_reporter.sentry_sdk.capture_exception')
def test_event_from_exception(mocked_capture_exception: Mock, sentry_reporter: SentryReporter):
# test that `event_from_exception` returns '{}' in case of an empty exception
assert sentry_reporter.event_from_exception(None) == {}

# test that `event_from_exception` calls `capture_exception` from `sentry_sdk`
exception = Exception('test')
sentry_reporter.thread_strategy = Mock()

def capture_exception(_):
# this behaviour normally is way more complicated, but at the end, `capture_exception` should transform
# an exception to a sentry event and this event should be stored in `sentry_reporter.last_event`
sentry_reporter.last_event = {'sentry': 'event'}

mocked_capture_exception.side_effect = capture_exception

sentry_reporter.event_from_exception(exception)

mocked_capture_exception.assert_called_with(exception)
sentry_reporter.thread_strategy.set.assert_any_call(SentryStrategy.SEND_SUPPRESSED)
assert sentry_reporter.last_event == {'sentry': 'event'}


def test_set_user(sentry_reporter):
Expand Down Expand Up @@ -175,19 +241,6 @@ def test_before_send(sentry_reporter):
assert sentry_reporter._before_send({'a': 'b'}, None) == {'a': 'b'}


def test_event_from_exception(sentry_reporter):
assert not sentry_reporter.event_from_exception(None)
# sentry sdk is not initialised, so None will be returned
assert not sentry_reporter.event_from_exception(Exception('test'))


def test_add_breadcrumb(sentry_reporter):
# test: None does not produce error
assert sentry_reporter.add_breadcrumb(None, None, None) is None
assert sentry_reporter.add_breadcrumb('message', 'category', 'level') is None
assert sentry_reporter.add_breadcrumb('message', 'category', 'level', named_arg='some') is None


def test_sentry_strategy(sentry_reporter):
sentry_reporter.thread_strategy.set(None) # default
sentry_reporter.global_strategy = SentryStrategy.SEND_ALLOWED_WITH_CONFIRMATION
Expand Down
6 changes: 6 additions & 0 deletions src/tribler-common/tribler_common/tests/test_patch_import.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,12 @@ async def test_mock_import_mocked_lib():
assert len(library_that_does_not_exist.inner_set) == 0


@patch_import('library_as_a_string')
async def test_mock_import_mocked_lib():
import library_as_a_string
assert library_as_a_string


@patch_import([])
async def test_mock_import_import_real_lib():
with pytest.raises(ImportError):
Expand Down

0 comments on commit 4f4ab66

Please sign in to comment.