Skip to content

Commit

Permalink
Modernize all tests to pytests.
Browse files Browse the repository at this point in the history
  • Loading branch information
Shyue Ping Ong committed Sep 5, 2023
1 parent 618cd26 commit f796f09
Show file tree
Hide file tree
Showing 22 changed files with 142 additions and 140 deletions.
2 changes: 1 addition & 1 deletion tests/test_bisect.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from monty.bisect import find_ge, find_gt, find_le, find_lt, index


class FuncTestCase(unittest.TestCase):
class TestFunc:
def test_funcs(self):
l = [0, 1, 2, 3, 4]
assert index(l, 1) == 1
Expand Down
28 changes: 14 additions & 14 deletions tests/test_collections.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,25 @@
import os
import unittest

import pytest

from monty.collections import AttrDict, FrozenAttrDict, Namespace, frozendict, tree

test_dir = os.path.join(os.path.dirname(__file__), "test_files")


class FrozenDictTest(unittest.TestCase):
class TestFrozenDict:
def test_frozen_dict(self):
d = frozendict({"hello": "world"})
self.assertRaises(KeyError, d.__setitem__, "k", "v")
self.assertRaises(KeyError, d.update, {"k": "v"})
with pytest.raises(KeyError):
d["k"] == "v"
assert d["hello"] == "world"

def test_namespace_dict(self):
d = Namespace(foo="bar")
d["hello"] = "world"
assert d["foo"] == "bar"
self.assertRaises(KeyError, d.__setitem__, "foo", "spam")
with pytest.raises(KeyError):
d.update({"foo": "spam"})

def test_attr_dict(self):
d = AttrDict(foo=1, bar=2)
Expand All @@ -30,24 +32,22 @@ def test_frozen_attrdict(self):
d = FrozenAttrDict({"hello": "world", 1: 2})
assert d["hello"] == "world"
assert d.hello == "world"
self.assertRaises(KeyError, d.update, {"updating": 2})
with self.assertRaises(KeyError):
with pytest.raises(KeyError):
d["updating"] == 2

with pytest.raises(KeyError):
d["foo"] = "bar"
with self.assertRaises(KeyError):
with pytest.raises(KeyError):
d.foo = "bar"
with self.assertRaises(KeyError):
with pytest.raises(KeyError):
d.hello = "new"


class TreeTest(unittest.TestCase):
class TestTree:
def test_tree(self):
x = tree()
x["a"]["b"]["c"]["d"] = 1
assert "b" in x["a"]
assert "c" not in x["a"]
assert "c" in x["a"]["b"]
assert x["a"]["b"]["c"]["d"] == 1


if __name__ == "__main__":
unittest.main()
4 changes: 2 additions & 2 deletions tests/test_design_patterns.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from monty.design_patterns import cached_class, singleton


class SingletonTest(unittest.TestCase):
class TestSingleton:
def test_singleton(self):
@singleton
class A:
Expand All @@ -30,7 +30,7 @@ def __getnewargs__(self):
return (self.val,)


class CachedClassTest(unittest.TestCase):
class TestCachedClass:
def test_cached_class(self):
a1a = A(1)
a1b = A(1)
Expand Down
7 changes: 5 additions & 2 deletions tests/test_dev.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
import unittest
import warnings

import pytest

from monty.dev import deprecated, get_ncpus, install_excepthook, requires


Expand All @@ -16,7 +18,7 @@ def prop(self):
pass


class DecoratorTest(unittest.TestCase):
class TestDecorator:
def test_deprecated(self):
def func_a():
pass
Expand Down Expand Up @@ -121,7 +123,8 @@ def test_requires(self):
def use_fictitious_mod():
print("success")

self.assertRaises(RuntimeError, use_fictitious_mod)
with pytest.raises(RuntimeError):
use_fictitious_mod()

@requires(unittest is not None, "scipy is not present.")
def use_unittest():
Expand Down
Binary file modified tests/test_files/3000_lines.txt.gz
Binary file not shown.
2 changes: 1 addition & 1 deletion tests/test_fnmatch.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from monty.fnmatch import WildCard


class FuncTest(unittest.TestCase):
class TestFunc:
def test_match(self):
wc = WildCard("*.pdf")
assert wc.match("A.pdf")
Expand Down
6 changes: 4 additions & 2 deletions tests/test_fractions.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import unittest

import pytest

from monty.fractions import gcd, gcd_float, lcm


class FuncTestCase(unittest.TestCase):
class TestFunc:
def test_gcd(self):
assert gcd(7, 14, 63) == 7

Expand All @@ -12,7 +14,7 @@ def test_lcm(self):

def test_gcd_float(self):
vs = [6.2, 12.4, 15.5 + 5e-9]
self.assertAlmostEqual(gcd_float(vs, 1e-8), 3.1)
assert gcd_float(vs, 1e-8) == pytest.approx(3.1)


if __name__ == "__main__":
Expand Down
2 changes: 1 addition & 1 deletion tests/test_inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ class LittleCatD(LittleCatB):
pass


class InspectTest(unittest.TestCase):
class TestInspect:
def test_func(self):
# Not a real test. Need something better.
assert find_top_pyfile()
Expand Down
50 changes: 18 additions & 32 deletions tests/test_io.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import os
import unittest

import pytest

try:
from pathlib import Path
except ImportError:
Expand All @@ -17,7 +19,7 @@
test_dir = os.path.join(os.path.dirname(__file__), "test_files")


class ReverseReadlineTest(unittest.TestCase):
class TestReverseReadline:
NUMLINES = 3000

def test_reverse_readline(self):
Expand All @@ -28,23 +30,19 @@ def test_reverse_readline(self):
"""
with open(os.path.join(test_dir, "3000_lines.txt")) as f:
for idx, line in enumerate(reverse_readline(f)):
self.assertEqual(
int(line),
self.NUMLINES - idx,
"read_backwards read {} whereas it should " "have read {}".format(int(line), self.NUMLINES - idx),
)
assert int(line) == self.NUMLINES - idx, "read_backwards read {} whereas it should "(
"have read {" "}"
).format(int(line), self.NUMLINES - idx)

def test_reverse_readline_fake_big(self):
"""
Make sure that large textfiles are read properly
"""
with open(os.path.join(test_dir, "3000_lines.txt")) as f:
for idx, line in enumerate(reverse_readline(f, max_mem=0)):
self.assertEqual(
int(line),
self.NUMLINES - idx,
"read_backwards read {} whereas it should " "have read {}".format(int(line), self.NUMLINES - idx),
)
assert int(line) == self.NUMLINES - idx, "read_backwards read {} whereas it should "(
"have read {" "}"
).format(int(line), self.NUMLINES - idx)

def test_reverse_readline_bz2(self):
"""
Expand All @@ -68,7 +66,7 @@ def test_empty_file(self):
raise ValueError("an empty file is being read!")


class ReverseReadfileTest(unittest.TestCase):
class TestReverseReadfile:
NUMLINES = 3000

def test_reverse_readfile(self):
Expand All @@ -79,11 +77,7 @@ def test_reverse_readfile(self):
"""
fname = os.path.join(test_dir, "3000_lines.txt")
for idx, line in enumerate(reverse_readfile(fname)):
self.assertEqual(
int(line),
self.NUMLINES - idx,
"read_backwards read {} whereas it should " "have read {}".format(int(line), self.NUMLINES - idx),
)
assert int(line) == self.NUMLINES - idx

def test_reverse_readfile_gz(self):
"""
Expand All @@ -93,11 +87,7 @@ def test_reverse_readfile_gz(self):
"""
fname = os.path.join(test_dir, "3000_lines.txt.gz")
for idx, line in enumerate(reverse_readfile(fname)):
self.assertEqual(
int(line),
self.NUMLINES - idx,
"read_backwards read {} whereas it should " "have read {}".format(int(line), self.NUMLINES - idx),
)
assert int(line) == self.NUMLINES - idx

def test_reverse_readfile_bz2(self):
"""
Expand All @@ -107,11 +97,7 @@ def test_reverse_readfile_bz2(self):
"""
fname = os.path.join(test_dir, "3000_lines.txt.bz2")
for idx, line in enumerate(reverse_readfile(fname)):
self.assertEqual(
int(line),
self.NUMLINES - idx,
"read_backwards read {} whereas it should " "have read {}".format(int(line), self.NUMLINES - idx),
)
assert int(line) == self.NUMLINES - idx

def test_empty_file(self):
"""
Expand All @@ -122,7 +108,7 @@ def test_empty_file(self):
raise ValueError("an empty file is being read!")


class ZopenTest(unittest.TestCase):
class TestZopen:
def test_zopen(self):
with zopen(os.path.join(test_dir, "myfile_gz.gz"), mode="rt") as f:
assert f.read() == "HelloWorld.\n\n"
Expand All @@ -145,18 +131,18 @@ def test_Path_objects(self):
assert f.read() == "HelloWorld.\n\n"


class FileLockTest(unittest.TestCase):
def setUp(self):
class TestFileLock:
def setup_method(self):
self.file_name = "__lock__"
self.lock = FileLock(self.file_name, timeout=1)
self.lock.acquire()

def test_raise(self):
with self.assertRaises(FileLockException):
with pytest.raises(FileLockException):
new_lock = FileLock(self.file_name, timeout=1)
new_lock.acquire()

def tearDown(self):
def teardown_method(self):
self.lock.release()


Expand Down
Loading

0 comments on commit f796f09

Please sign in to comment.