Skip to content

Commit

Permalink
rewrite tests in pytest style
Browse files Browse the repository at this point in the history
  • Loading branch information
benbovy committed Jul 31, 2017
1 parent d3e877c commit f9d54bb
Show file tree
Hide file tree
Showing 5 changed files with 97 additions and 78 deletions.
10 changes: 5 additions & 5 deletions xsimlab/tests/test_formatting.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,17 @@
class TestFormatting(unittest.TestCase):

def test_maybe_truncate(self):
self.assertEqual(maybe_truncate('test', 10), 'test')
self.assertEqual(maybe_truncate('longteststring', 10), 'longtes...')
assert maybe_truncate('test', 10) == 'test'
assert maybe_truncate('longteststring', 10) == 'longtes...'

def test_pretty_print(self):
self.assertEqual(pretty_print('test', 10), 'test' + ' ' * 6)
assert pretty_print('test', 10) == 'test' + ' ' * 6

def test_wrap_indent(self):
text = "line1\nline2"

expected = '-line1\n line2'
self.assertEqual(wrap_indent(text, start='-'), expected)
assert wrap_indent(text, start='-') == expected

expected = 'line1\n line2'
self.assertEqual(wrap_indent(text, length=1), expected)
assert wrap_indent(text, length=1) == expected
38 changes: 21 additions & 17 deletions xsimlab/tests/test_model.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import unittest
from textwrap import dedent

import pytest
import numpy as np
from numpy.testing import assert_array_equal

Expand Down Expand Up @@ -92,42 +93,45 @@ class TestModel(unittest.TestCase):

def test_constructor(self):
# test invalid processes
with self.assertRaises(TypeError):
with pytest.raises(TypeError):
Model({'not_a_class': Grid()})

class OtherClass(object):
pass

with self.assertRaisesRegex(TypeError, "is not a subclass"):
with pytest.raises(TypeError) as excinfo:
Model({'invalid_class': Process})
assert "is not a subclass" in str(excinfo.value)

with self.assertRaisesRegex(TypeError, "is not a subclass"):
with pytest.raises(TypeError) as excinfo:
Model({'invalid_class': OtherClass})
assert "is not a subclass" in str(excinfo.value)

# test process ordering
model = get_test_model()
expected = ['grid', 'some_process', 'other_process', 'quantity']
self.assertEqual(list(model), expected)
assert list(model) == expected

# test dict-like vs. attribute access
self.assertIs(model['grid'], model.grid)
assert model['grid'] is model.grid

def test_input_vars(self):
model = get_test_model()
expected = {'grid': ['x_size'],
'some_process': ['some_param'],
'quantity': ['quantity']}
actual = {k: list(v.keys()) for k, v in model.input_vars.items()}
self.assertDictEqual(expected, actual)
assert expected == actual

def test_is_input(self):
model = get_test_model()
self.assertTrue(model.is_input(model.grid.x_size))
self.assertTrue(model.is_input(('grid', 'x_size')))
self.assertFalse(model.is_input(('quantity', 'all_effects')))
assert model.is_input(model.grid.x_size) is True
assert model.is_input(('grid', 'x_size')) is True
assert model.is_input(('quantity', 'all_effects')) is False
assert model.is_input(('other_process', 'copy_param')) is False

external_variable = Variable(())
self.assertFalse(model.is_input(external_variable))
assert model.is_input(external_variable) is False

def test_initialize(self):
model = get_test_model()
Expand Down Expand Up @@ -155,15 +159,15 @@ def test_finalize_step(self):
def test_finalize(self):
model = get_test_model()
model.finalize()
self.assertEqual(model.some_process.some_effect.rate, 0)
assert model.some_process.some_effect.rate == 0

def test_clone(self):
model = get_test_model()
cloned = model.clone()

for (ck, cp), (k, p) in zip(cloned.items(), model.items()):
self.assertEqual(ck, k)
self.assertIsNot(cp, p)
assert ck == k
assert cp is not p

def test_update_processes(self):
model = get_test_model()
Expand All @@ -175,7 +179,7 @@ def test_update_processes(self):
actual = model.update_processes({'plug_process': PlugProcess})

# TODO: more advanced (public?) test function to compare two models?
self.assertEqual(list(actual), list(expected))
assert list(actual) == list(expected)

def test_drop_processes(self):
model = get_test_model()
Expand All @@ -184,12 +188,12 @@ def test_drop_processes(self):
'some_process': SomeProcess,
'quantity': Quantity})
actual = model.drop_processes('other_process')
self.assertEqual(list(actual), list(expected))
assert list(actual) == list(expected)

expected = Model({'grid': Grid,
'quantity': Quantity})
actual = model.drop_processes(['some_process', 'other_process'])
self.assertEqual(list(actual), list(expected))
assert list(actual) == list(expected)

def test_repr(self):
model = get_test_model()
Expand All @@ -203,4 +207,4 @@ def test_repr(self):
quantity
quantity (in) a quantity""")

self.assertEqual(repr(model), expected)
assert repr(model) == expected
49 changes: 27 additions & 22 deletions xsimlab/tests/test_process.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
from textwrap import dedent
from io import StringIO

import pytest

from xsimlab.variable.base import (Variable, VariableList, VariableGroup,
diagnostic)
from xsimlab.process import Process
Expand All @@ -24,24 +26,26 @@ def diag(self):
class TestProcessBase(unittest.TestCase):

def test_new(self):
with self.assertRaisesRegex(TypeError, "subclassing a subclass"):
with pytest.raises(TypeError) as excinfo:
class InvalidProcess(MyProcess):
var = Variable(())
assert "subclassing a subclass" in str(excinfo.value)

with self.assertRaisesRegex(AttributeError, "invalid attribute"):
with pytest.raises(AttributeError) as excinfo:
class InvalidProcess2(Process):
class Meta:
time_dependent = True
invalid_meta_attr = 'invalid'
assert "invalid attribute" in str(excinfo.value)

# test extract variable objects vs. other attributes
self.assertTrue(getattr(MyProcess, 'no_var', False))
self.assertFalse(getattr(MyProcess, 'var', False))
self.assertEqual(set(['var', 'var_list', 'var_group', 'diag']),
set(MyProcess._variables.keys()))
assert getattr(MyProcess, 'no_var', False)
assert not getattr(MyProcess, 'var', False)
assert set(['var', 'var_list', 'var_group', 'diag']) == (
set(MyProcess._variables.keys()))

# test Meta attributes
self.assertDictEqual(MyProcess._meta, {'time_dependent': False})
assert MyProcess._meta == {'time_dependent': False}


class TestProcess(unittest.TestCase):
Expand All @@ -61,37 +65,38 @@ def setUp(self):

def test_constructor(self):
# test dict-like vs. attribute access
self.assertIs(self.my_process['var'], self.my_process._variables['var'])
self.assertIs(self.my_process.var, self.my_process._variables['var'])
assert self.my_process['var'] is self.my_process._variables['var']
assert self.my_process.var is self.my_process._variables['var']

# test deep copy variable objects
MyProcess._variables['var'].state = 2
self.assertNotEqual(self.my_process._variables['var'].state,
MyProcess._variables['var'].state)
assert self.my_process._variables['var'].state != (
MyProcess._variables['var'].state)

# test assign process to diagnostics
self.assertIs(self.my_process['diag']._process_obj, self.my_process)
assert self.my_process['diag']._process_obj is self.my_process

def test_clone(self):
cloned_process = self.my_process.clone()
self.assertIsNot(self.my_process['var'], cloned_process['var'])
assert self.my_process['var'] is not cloned_process['var']

def test_variables(self):
self.assertEqual(set(['var', 'var_list', 'var_group', 'diag']),
set(self.my_process.variables.keys()))
assert set(['var', 'var_list', 'var_group', 'diag']) == (
set(self.my_process.variables.keys()))

def test_meta(self):
self.assertDictEqual(self.my_process.meta, {'time_dependent': False})
assert self.my_process.meta == {'time_dependent': False}

def test_name(self):
self.assertEqual(self.my_process.name, "MyProcess")
assert self.my_process.name == "MyProcess"

self.my_process._name = "my_process"
self.assertEqual(self.my_process.name, "my_process")
assert self.my_process.name == "my_process"

def test_run_step(self):
with self.assertRaisesRegex(NotImplementedError, "no method"):
with pytest.raises(NotImplementedError) as excinfo:
self.my_process.run_step(1)
assert "no method" in str(excinfo.value)

def test_info(self):
expected = self.my_process_str
Expand All @@ -100,7 +105,7 @@ def test_info(self):
buf = StringIO()
cls_or_obj.info(buf=buf)
actual = buf.getvalue()
self.assertEqual(actual, expected)
assert actual == expected

class OtherProcess(Process):
pass
Expand All @@ -114,11 +119,11 @@ class OtherProcess(Process):
buf = StringIO()
OtherProcess.info(buf=buf)
actual = buf.getvalue()
self.assertEqual(actual, expected)
assert actual == expected

def test_repr(self):
expected = '\n'.join(
["<xsimlab.Process 'xsimlab.tests.test_process.MyProcess'>",
self.my_process_str]
)
self.assertEqual(repr(self.my_process), expected)
assert repr(self.my_process) == expected
5 changes: 4 additions & 1 deletion xsimlab/tests/test_utils.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import unittest

import pytest

from xsimlab import utils


class TestImportRequired(unittest.TestCase):

def test(self):
err_msg = "no module"
with self.assertRaisesRegex(RuntimeError, err_msg):
with pytest.raises(RuntimeError) as excinfo:
utils.import_required('this_module_doesnt_exits', err_msg)
assert err_msg in str(excinfo.value)

0 comments on commit f9d54bb

Please sign in to comment.