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

Android tests refactoring #940

Merged
merged 6 commits into from
Oct 25, 2017
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
4 changes: 3 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,9 @@ at anytime.
* Use the first port available for the peer and dht ports, starting with the provided values (defaults of 3333 and 4444). This allows multiple lbrynet instances in a LAN with UPnP.
* Detect a UPnP redirect that didn't get cleaned up on a previous run and use it
* Bumped jsonschema requirement to 2.6.0

* Moved tests into the lbrynet package.
* Refactor some assert statements to accommodate the PYTHONOPTIMIZE flag set for Android.

### Added
*
*
Expand Down
11 changes: 6 additions & 5 deletions lbrynet/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -352,7 +352,8 @@ def _parse_environment(environment):
return env_settings

def _assert_valid_data_type(self, data_type):
assert data_type in self._data, KeyError('{} in is not a valid data type'.format(data_type))
if not data_type in self._data:
raise KeyError('{} in is not a valid data type'.format(data_type))

def get_valid_setting_names(self):
return self._data[TYPE_DEFAULT].keys()
Expand All @@ -361,8 +362,8 @@ def _is_valid_setting(self, name):
return name in self.get_valid_setting_names()

def _assert_valid_setting(self, name):
assert self._is_valid_setting(name), \
KeyError('{} is not a valid setting'.format(name))
if not self._is_valid_setting(name):
raise KeyError('{} is not a valid setting'.format(name))

def _validate_settings(self, data):
invalid_settings = set(data.keys()) - set(self.get_valid_setting_names())
Expand All @@ -371,8 +372,8 @@ def _validate_settings(self, data):

def _assert_editable_setting(self, name):
self._assert_valid_setting(name)
assert name not in self._fixed_defaults, \
ValueError('{} is not an editable setting'.format(name))
if name in self._fixed_defaults:
raise ValueError('{} is not an editable setting'.format(name))

def _validate_currency(self, currency):
if currency not in self._fixed_defaults['CURRENCIES'].keys():
Expand Down
2 changes: 1 addition & 1 deletion lbrynet/daemon/Daemon.py
Original file line number Diff line number Diff line change
Expand Up @@ -1231,7 +1231,7 @@ def jsonrpc_help(self, command=None):
)

return self._render_response({
'help': textwrap.dedent(fn.__doc__)
'help': textwrap.dedent(fn.__doc__ or '')
})

def jsonrpc_commands(self):
Expand Down
6 changes: 4 additions & 2 deletions lbrynet/daemon/ExchangeRateManager.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,10 @@

class ExchangeRate(object):
def __init__(self, market, spot, ts):
assert int(time.time()) - ts < 600
assert spot > 0
if not int(time.time()) - ts < 600:
raise ValueError('The timestamp is too dated.')
if not spot > 0:
raise ValueError('Spot must be greater than 0.')
self.currency_pair = (market[0:3], market[3:6])
self.spot = spot
self.ts = ts
Expand Down
11 changes: 10 additions & 1 deletion lbrynet/tests/functional/test_misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
from lbrynet.core.server.ServerProtocol import ServerProtocolFactory

from lbrynet.tests import mocks
from lbrynet.tests.util import mk_db_and_blob_dir, rm_db_and_blob_dir
from lbrynet.tests.util import mk_db_and_blob_dir, rm_db_and_blob_dir, is_android

FakeNode = mocks.Node
FakeWallet = mocks.Wallet
Expand Down Expand Up @@ -490,6 +490,9 @@ def check_for_start():

return d

@unittest.skipIf(is_android(),
'Test cannot pass on Android because multiprocessing '
'is not supported at the OS level.')
def test_lbry_transfer(self):
sd_hash_queue = Queue()
kill_event = Event()
Expand Down Expand Up @@ -577,6 +580,9 @@ def print_shutting_down():

return d

@unittest.skipIf(is_android(),
'Test cannot pass on Android because multiprocessing '
'is not supported at the OS level.')
def test_last_blob_retrieval(self):
kill_event = Event()
dead_event_1 = Event()
Expand Down Expand Up @@ -659,6 +665,9 @@ def print_shutting_down():
d.addBoth(stop)
return d

@unittest.skipIf(is_android(),
'Test cannot pass on Android because multiprocessing '
'is not supported at the OS level.')
def test_double_download(self):
sd_hash_queue = Queue()
kill_event = Event()
Expand Down
11 changes: 8 additions & 3 deletions lbrynet/tests/unit/core/test_log_support.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@
import logging

import mock
import unittest
from twisted.internet import defer
from twisted.trial import unittest
from twisted import trial

from lbrynet.core import log_support
from lbrynet.tests.util import is_android


class TestLogger(unittest.TestCase):
class TestLogger(trial.unittest.TestCase):
def raiseError(self):
raise Exception('terrible things happened')

Expand All @@ -26,12 +28,15 @@ def setUp(self):
handler.setFormatter(logging.Formatter("%(filename)s:%(lineno)d - %(message)s"))
self.log.addHandler(handler)

@unittest.skipIf(is_android(),
'Test cannot pass on Android because the tests package is compiled '
'which results in a different method call stack')
def test_can_log_failure(self):
def output_lines():
return self.stream.getvalue().split('\n')

# the line number could change if this file gets refactored
expected_first_line = 'test_log_support.py:18 - My message: terrible things happened'
expected_first_line = 'test_log_support.py:20 - My message: terrible things happened'

# testing the entirety of the message is futile as the
# traceback will depend on the system the test is being run on
Expand Down
11 changes: 8 additions & 3 deletions lbrynet/tests/unit/lbrynet_daemon/test_Daemon.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import mock
import json
import unittest

from twisted.internet import defer
from twisted.trial import unittest
from twisted import trial

from lbryschema.decode import smart_decode
from lbrynet import conf
Expand All @@ -14,6 +15,8 @@
from lbrynet.tests.mocks import BlobAvailabilityTracker as DummyBlobAvailabilityTracker
from lbrynet.tests.mocks import ExchangeRateManager as DummyExchangeRateManager
from lbrynet.tests.mocks import BTCLBCFeed, USDBTCFeed
from lbrynet.tests.util import is_android


import logging
logging.getLogger("lbryum").setLevel(logging.WARNING)
Expand Down Expand Up @@ -63,7 +66,7 @@ def get_test_daemon(data_rate=None, generous=True, with_fee=False):
return daemon


class TestCostEst(unittest.TestCase):
class TestCostEst(trial.unittest.TestCase):
def setUp(self):
mock_conf_settings(self)
util.resetTime(self)
Expand Down Expand Up @@ -96,7 +99,7 @@ def test_ungenerous_data_and_no_fee(self):
self.assertEquals(daemon.get_est_cost("test", size).result, correct_result)


class TestJsonRpc(unittest.TestCase):
class TestJsonRpc(trial.unittest.TestCase):
def setUp(self):
def noop():
return None
Expand All @@ -112,6 +115,8 @@ def test_status(self):
d = defer.maybeDeferred(self.test_daemon.jsonrpc_status)
d.addCallback(lambda status: self.assertDictContainsSubset({'is_running': False}, status))

@unittest.skipIf(is_android(),
'Test cannot pass on Android because PYTHONOPTIMIZE removes the docstrings.')
def test_help(self):
d = defer.maybeDeferred(self.test_daemon.jsonrpc_help, command='status')
d.addCallback(lambda result: self.assertSubstring('daemon status', result['help']))
Expand Down
4 changes: 2 additions & 2 deletions lbrynet/tests/unit/lbrynet_daemon/test_ExchangeRateManager.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,9 @@ def setUp(self):
util.resetTime(self)

def test_invalid_rates(self):
with self.assertRaises(AssertionError):
with self.assertRaises(ValueError):
ExchangeRateManager.ExchangeRate('USDBTC', 0, util.DEFAULT_ISO_TIME)
with self.assertRaises(AssertionError):
with self.assertRaises(ValueError):
ExchangeRateManager.ExchangeRate('USDBTC', -1, util.DEFAULT_ISO_TIME)


Expand Down
4 changes: 2 additions & 2 deletions lbrynet/tests/unit/test_conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,12 @@ def test_setting_is_in_dict(self):

def test_invalid_setting_raises_exception(self):
settings = self.get_mock_config_instance()
self.assertRaises(AssertionError, settings.set, 'invalid_name', 123)
self.assertRaises(KeyError, settings.set, 'invalid_name', 123)

def test_invalid_data_type_raises_exception(self):
settings = self.get_mock_config_instance()
self.assertIsNone(settings.set('test', 123))
self.assertRaises(AssertionError, settings.set, 'test', 123, ('fake_data_type',))
self.assertRaises(KeyError, settings.set, 'test', 123, ('fake_data_type',))

def test_setting_precedence(self):
settings = self.get_mock_config_instance()
Expand Down
3 changes: 3 additions & 0 deletions lbrynet/tests/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,6 @@ def resetTime(test_case, timestamp=DEFAULT_TIMESTAMP):
patcher = mock.patch('lbrynet.core.utils.utcnow')
patcher.start().return_value = timestamp
test_case.addCleanup(patcher.stop)

def is_android():
return 'ANDROID_ARGUMENT' in os.environ # detect Android using the Kivy way