From de97d74b50b62cd2f0cddc2a04e150575d9c6bc7 Mon Sep 17 00:00:00 2001 From: Charles-Henri de Boysson Date: Tue, 7 Apr 2020 23:35:58 -0400 Subject: feat(test): Move to pytest --- .travis.yml | 16 +- CONTRIBUTING.md | 4 +- constraints.txt | 12 + docs/testing.rst | 2 +- kazoo/tests/test_barrier.py | 57 ++- kazoo/tests/test_build.py | 7 +- kazoo/tests/test_cache.py | 220 +++++++----- kazoo/tests/test_client.py | 658 +++++++++++++++++++--------------- kazoo/tests/test_connection.py | 74 ++-- kazoo/tests/test_counter.py | 47 +-- kazoo/tests/test_election.py | 18 +- kazoo/tests/test_eventlet_handler.py | 61 ++-- kazoo/tests/test_exceptions.py | 10 +- kazoo/tests/test_gevent_handler.py | 53 +-- kazoo/tests/test_hosts.py | 41 +-- kazoo/tests/test_interrupt.py | 8 +- kazoo/tests/test_lease.py | 70 ++-- kazoo/tests/test_lock.py | 118 +++--- kazoo/tests/test_partitioner.py | 17 +- kazoo/tests/test_party.py | 38 +- kazoo/tests/test_paths.py | 82 +++-- kazoo/tests/test_queue.py | 181 +++++----- kazoo/tests/test_retry.py | 35 +- kazoo/tests/test_sasl.py | 36 +- kazoo/tests/test_security.py | 22 +- kazoo/tests/test_threading_handler.py | 63 ++-- kazoo/tests/test_utils.py | 12 +- kazoo/tests/test_watchers.py | 179 ++++----- requirements_sasl.txt | 2 +- requirements_sphinx.txt | 8 +- requirements_test.txt | 10 +- run_failure.py | 14 +- setup.cfg | 8 +- setup.py | 7 +- tox.ini | 5 +- 35 files changed, 1153 insertions(+), 1042 deletions(-) create mode 100644 constraints.txt diff --git a/.travis.yml b/.travis.yml index 85f105b..c5fa0e8 100644 --- a/.travis.yml +++ b/.travis.yml @@ -20,35 +20,35 @@ matrix: - python: '2.7' env: ZOOKEEPER_VERSION=3.4.14 TOX_VENV=py27 - python: '2.7' - env: ZOOKEEPER_VERSION=3.5.6 ZOOKEEPER_PREFIX="apache-" ZOOKEEPER_SUFFIX="-bin" ZOOKEEPER_LIB="lib" TOX_VENV=py27 + env: ZOOKEEPER_VERSION=3.5.7 ZOOKEEPER_PREFIX="apache-" ZOOKEEPER_SUFFIX="-bin" ZOOKEEPER_LIB="lib" TOX_VENV=py27 - python: '2.7' env: ZOOKEEPER_VERSION=3.4.14 TOX_VENV=py27-gevent - python: '2.7' - env: ZOOKEEPER_VERSION=3.5.6 ZOOKEEPER_PREFIX="apache-" ZOOKEEPER_SUFFIX="-bin" ZOOKEEPER_LIB="lib" TOX_VENV=py27-gevent + env: ZOOKEEPER_VERSION=3.5.7 ZOOKEEPER_PREFIX="apache-" ZOOKEEPER_SUFFIX="-bin" ZOOKEEPER_LIB="lib" TOX_VENV=py27-gevent - python: '2.7' env: ZOOKEEPER_VERSION=3.4.14 TOX_VENV=py27-eventlet - python: '2.7' - env: ZOOKEEPER_VERSION=3.5.6 ZOOKEEPER_PREFIX="apache-" ZOOKEEPER_SUFFIX="-bin" ZOOKEEPER_LIB="lib" TOX_VENV=py27-eventlet + env: ZOOKEEPER_VERSION=3.5.7 ZOOKEEPER_PREFIX="apache-" ZOOKEEPER_SUFFIX="-bin" ZOOKEEPER_LIB="lib" TOX_VENV=py27-eventlet - python: '3.6' env: ZOOKEEPER_VERSION=3.4.14 TOX_VENV=py36 - python: '3.6' env: ZOOKEEPER_VERSION=3.4.14 TOX_VENV=py36-sasl - python: '3.6' - env: ZOOKEEPER_VERSION=3.5.6 ZOOKEEPER_PREFIX="apache-" ZOOKEEPER_SUFFIX="-bin" ZOOKEEPER_LIB="lib" TOX_VENV=py36 + env: ZOOKEEPER_VERSION=3.5.7 ZOOKEEPER_PREFIX="apache-" ZOOKEEPER_SUFFIX="-bin" ZOOKEEPER_LIB="lib" TOX_VENV=py36 - python: '3.6' - env: ZOOKEEPER_VERSION=3.5.6 ZOOKEEPER_PREFIX="apache-" ZOOKEEPER_SUFFIX="-bin" ZOOKEEPER_LIB="lib" TOX_VENV=py36-sasl + env: ZOOKEEPER_VERSION=3.5.7 ZOOKEEPER_PREFIX="apache-" ZOOKEEPER_SUFFIX="-bin" ZOOKEEPER_LIB="lib" TOX_VENV=py36-sasl - python: '3.7' env: ZOOKEEPER_VERSION=3.4.14 TOX_VENV=py37 - python: '3.7' env: ZOOKEEPER_VERSION=3.4.14 TOX_VENV=py37-sasl - python: '3.7' - env: ZOOKEEPER_VERSION=3.5.6 ZOOKEEPER_PREFIX="apache-" ZOOKEEPER_SUFFIX="-bin" ZOOKEEPER_LIB="lib" TOX_VENV=py37 DEPLOY=true + env: ZOOKEEPER_VERSION=3.5.7 ZOOKEEPER_PREFIX="apache-" ZOOKEEPER_SUFFIX="-bin" ZOOKEEPER_LIB="lib" TOX_VENV=py37 DEPLOY=true - python: '3.7' - env: ZOOKEEPER_VERSION=3.5.6 ZOOKEEPER_PREFIX="apache-" ZOOKEEPER_SUFFIX="-bin" ZOOKEEPER_LIB="lib" TOX_VENV=py37-sasl + env: ZOOKEEPER_VERSION=3.5.7 ZOOKEEPER_PREFIX="apache-" ZOOKEEPER_SUFFIX="-bin" ZOOKEEPER_LIB="lib" TOX_VENV=py37-sasl - python: pypy env: ZOOKEEPER_VERSION=3.4.14 TOX_VENV=pypy - python: 'pypy' - env: ZOOKEEPER_VERSION=3.5.6 ZOOKEEPER_PREFIX="apache-" ZOOKEEPER_SUFFIX="-bin" ZOOKEEPER_LIB="lib" TOX_VENV=pypy + env: ZOOKEEPER_VERSION=3.5.7 ZOOKEEPER_PREFIX="apache-" ZOOKEEPER_SUFFIX="-bin" ZOOKEEPER_LIB="lib" TOX_VENV=pypy notifications: email: false install: diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 5ee79ac..423a9f1 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -41,10 +41,10 @@ Or to run individual tests: ``` export ZOOKEEPER_PATH=//bin/zookeeper/ - bin/nosetests -s -d kazoo.tests.test_client:TestClient.test_create + bin/pytest -v kazoo/tests/test_client.py::TestClient::test_create ``` -The nose test runner allows you to filter by test module, class or +The pytest test runner allows you to filter by test module, class or individual test method. If you made changes to the documentation, you can build it locally: diff --git a/constraints.txt b/constraints.txt new file mode 100644 index 0000000..26c28c4 --- /dev/null +++ b/constraints.txt @@ -0,0 +1,12 @@ +# Consistent testing environment. +flake8==3.7.9 +mock==3.0.5 +objgraph==3.4.1 +pytest==4.6.9 +pytest-cov==2.8.1 + +# Documentation building. +Jinja2==2.7.3 +Pygments==1.6 +Sphinx==1.2.2 +docutils==0.12 diff --git a/docs/testing.rst b/docs/testing.rst index 1051be7..c98e35a 100644 --- a/docs/testing.rst +++ b/docs/testing.rst @@ -7,7 +7,7 @@ Testing Kazoo has several test harnesses used internally for its own tests that are exposed as public API's for use in your own tests for common Zookeeper cluster management and session testing. They can be mixed in with your own `unittest` -or `nose` tests along with a `mock` object that allows you to force specific +or `pytest` tests along with a `mock` object that allows you to force specific `KazooClient` commands to fail in various ways. The test harness needs to be able to find the Zookeeper Java libraries. You diff --git a/kazoo/tests/test_barrier.py b/kazoo/tests/test_barrier.py index 94b6e92..d0ea870 100644 --- a/kazoo/tests/test_barrier.py +++ b/kazoo/tests/test_barrier.py @@ -1,36 +1,33 @@ import threading -from nose.tools import eq_ - from kazoo.testing import KazooTestCase class KazooBarrierTests(KazooTestCase): def test_barrier_not_exist(self): b = self.client.Barrier("/some/path") - eq_(b.wait(), True) + assert b.wait() def test_barrier_exists(self): b = self.client.Barrier("/some/path") b.create() - eq_(b.wait(0), False) + assert not b.wait(0) b.remove() - eq_(b.wait(), True) + assert b.wait() def test_remove_nonexistent_barrier(self): b = self.client.Barrier("/some/path") - eq_(b.remove(), False) + assert not b.remove() class KazooDoubleBarrierTests(KazooTestCase): - def test_basic_barrier(self): b = self.client.DoubleBarrier("/some/path", 1) - eq_(b.participating, False) + assert not b.participating b.enter() - eq_(b.participating, True) + assert b.participating b.leave() - eq_(b.participating, False) + assert not b.participating def test_two_barrier(self): av = threading.Event() @@ -61,14 +58,14 @@ class KazooDoubleBarrierTests(KazooTestCase): t2 = threading.Thread(target=make_barrier_two) t2.start() - eq_(b1.participating, False) - eq_(b2.participating, False) + assert not b1.participating + assert not b2.participating bv.set() av.wait() ev.wait() - eq_(b1.participating, True) - eq_(b2.participating, True) + assert b1.participating + assert b2.participating av.clear() ev.clear() @@ -76,8 +73,8 @@ class KazooDoubleBarrierTests(KazooTestCase): release_all.set() av.wait() ev.wait() - eq_(b1.participating, False) - eq_(b2.participating, False) + assert not b1.participating + assert not b2.participating t1.join() t2.join() @@ -111,19 +108,19 @@ class KazooDoubleBarrierTests(KazooTestCase): t2 = threading.Thread(target=make_barrier_two) t2.start() - eq_(b1.participating, False) - eq_(b2.participating, False) + assert not b1.participating + assert not b2.participating bv.set() - eq_(b1.participating, False) - eq_(b2.participating, False) + assert not b1.participating + assert not b2.participating b3.enter() ev.wait() av.wait() - eq_(b1.participating, True) - eq_(b2.participating, True) - eq_(b3.participating, True) + assert b1.participating + assert b2.participating + assert b3.participating av.clear() ev.clear() @@ -132,26 +129,26 @@ class KazooDoubleBarrierTests(KazooTestCase): b3.leave() av.wait() ev.wait() - eq_(b1.participating, False) - eq_(b2.participating, False) - eq_(b3.participating, False) + assert not b1.participating + assert not b2.participating + assert not b3.participating t1.join() t2.join() def test_barrier_existing_parent_node(self): b = self.client.DoubleBarrier('/some/path', 1) - self.assertFalse(b.participating) + assert b.participating is False self.client.create('/some', ephemeral=True) # the barrier cannot create children under an ephemeral node b.enter() - self.assertFalse(b.participating) + assert b.participating is False def test_barrier_existing_node(self): b = self.client.DoubleBarrier('/some', 1) - self.assertFalse(b.participating) + assert b.participating is False self.client.ensure_path(b.path) self.client.create(b.create_path, ephemeral=True) # the barrier will re-use an existing node b.enter() - self.assertTrue(b.participating) + assert b.participating is True b.leave() diff --git a/kazoo/tests/test_build.py b/kazoo/tests/test_build.py index b8e4bbc..253027f 100644 --- a/kazoo/tests/test_build.py +++ b/kazoo/tests/test_build.py @@ -1,16 +1,15 @@ import os -from nose import SkipTest +import pytest from kazoo.testing import KazooTestCase class TestBuildEnvironment(KazooTestCase): - def setUp(self): KazooTestCase.setUp(self) if not os.environ.get('TRAVIS'): - raise SkipTest('Only run build config tests on Travis.') + pytest.skip('Only run build config tests on Travis.') def test_zookeeper_version(self): server_version = self.client.server_version() @@ -20,4 +19,4 @@ class TestBuildEnvironment(KazooTestCase): if '-' in env_version: # Ignore pre-release markers like -alpha env_version = env_version.split('-')[0] - self.assertEqual(env_version, server_version) + assert env_version == server_version diff --git a/kazoo/tests/test_cache.py b/kazoo/tests/test_cache.py index 3a73880..33dafac 100644 --- a/kazoo/tests/test_cache.py +++ b/kazoo/tests/test_cache.py @@ -3,7 +3,7 @@ import importlib import uuid from mock import patch, call, Mock -from nose.tools import eq_, ok_, assert_not_equal, raises +import pytest from objgraph import count as count_refs_by_type from kazoo.testing import KazooTestHarness @@ -72,7 +72,7 @@ class KazooTreeCacheTests(KazooAdaptiveHandlerTestCase): event = self._event_queue.get(timeout=timeout) if started: if expect is not None: - eq_(event.event_type, expect) + assert event.event_type == expect return event if event.event_type == since: started = True @@ -111,25 +111,24 @@ class KazooTreeCacheTests(KazooAdaptiveHandlerTestCase): self.wait_cache(since=TreeEvent.INITIALIZED) stat = self.client.exists(self.path) - eq_(stat.version, 0) + assert stat.version == 0 - eq_(self.cache._state, TreeCache.STATE_STARTED) - eq_(self.cache._root._state, TreeNode.STATE_LIVE) + assert self.cache._state == TreeCache.STATE_STARTED + assert self.cache._root._state == TreeNode.STATE_LIVE - @raises(KazooException) def test_start_started(self): self.make_cache() - self.cache.start() + with pytest.raises(KazooException): + self.cache.start() - @raises(KazooException) def test_start_closed(self): self.make_cache() - self.cache.start() self.cache.close() - self.cache.start() + with pytest.raises(KazooException): + self.cache.start() def test_close(self): - eq_(self.count_tree_node(), 0) + assert self.count_tree_node() == 0 self.make_cache() self.wait_cache(since=TreeEvent.INITIALIZED) @@ -145,49 +144,57 @@ class KazooTreeCacheTests(KazooAdaptiveHandlerTestCase): # watchers inside tree cache should be here root_path = self.client.chroot + self.path - eq_(len(self.client._data_watchers[root_path + '/foo']), 2) - eq_(len(self.client._data_watchers[root_path + '/foo/bar']), 1) - eq_(len(self.client._data_watchers[root_path + '/foo/bar/baz']), 1) - eq_(len(self.client._child_watchers[root_path + '/foo']), 2) - eq_(len(self.client._child_watchers[root_path + '/foo/bar']), 1) - eq_(len(self.client._child_watchers[root_path + '/foo/bar/baz']), 1) + assert len(self.client._data_watchers[root_path + '/foo']) == 2 + assert len(self.client._data_watchers[root_path + '/foo/bar']) == 1 + assert len(self.client._data_watchers[root_path + '/foo/bar/baz']) == 1 + assert len(self.client._child_watchers[root_path + '/foo']) == 2 + assert len(self.client._child_watchers[root_path + '/foo/bar']) == 1 + assert ( + len(self.client._child_watchers[root_path + '/foo/bar/baz']) == 1 + ) self.cache.close() # nothing should be published since tree closed - ok_(self._event_queue.empty()) + assert self._event_queue.empty() # tree should be empty - eq_(self.cache._root._children, {}) - eq_(self.cache._root._data, None) - eq_(self.cache._state, TreeCache.STATE_CLOSED) + assert self.cache._root._children == {} + assert self.cache._root._data is None + assert self.cache._state == TreeCache.STATE_CLOSED # node state should not be changed - assert_not_equal(self.cache._root._state, TreeNode.STATE_DEAD) + assert self.cache._root._state != TreeNode.STATE_DEAD # watchers should be reset - eq_(len(self.client._data_watchers[root_path + '/foo']), 1) - eq_(len(self.client._data_watchers[root_path + '/foo/bar']), 0) - eq_(len(self.client._data_watchers[root_path + '/foo/bar/baz']), 0) - eq_(len(self.client._child_watchers[root_path + '/foo']), 1) - eq_(len(self.client._child_watchers[root_path + '/foo/bar']), 0) - eq_(len(self.client._child_watchers[root_path + '/foo/bar/baz']), 0) + assert len(self.client._data_watchers[root_path + '/foo']) == 1 + assert len(self.client._data_watchers[root_path + '/foo/bar']) == 0 + assert len(self.client._data_watchers[root_path + '/foo/bar/baz']) == 0 + assert len(self.client._child_watchers[root_path + '/foo']) == 1 + assert len(self.client._child_watchers[root_path + '/foo/bar']) == 0 + assert ( + len(self.client._child_watchers[root_path + '/foo/bar/baz']) == 0 + ) # outside watchers should not be deleted - eq_(list(self.client._data_watchers[root_path + '/foo'])[0], - stub_data_watcher) - eq_(list(self.client._child_watchers[root_path + '/foo'])[0], - stub_child_watcher) + assert ( + list(self.client._data_watchers[root_path + '/foo'])[0] + == stub_data_watcher + ) + assert ( + list(self.client._child_watchers[root_path + '/foo'])[0] + == stub_child_watcher + ) # should not be any leaked memory (tree node) here self.cache = None - eq_(self.count_tree_node(), 0) + assert self.count_tree_node() == 0 def test_delete_operation(self): self.make_cache() self.wait_cache(since=TreeEvent.INITIALIZED) - eq_(self.count_tree_node(), 1) + assert self.count_tree_node() == 1 self.client.create(self.path + '/foo/bar/baz', makepath=True) for _ in range(3): @@ -198,19 +205,19 @@ class KazooTreeCacheTests(KazooAdaptiveHandlerTestCase): self.wait_cache(TreeEvent.NODE_REMOVED) # tree should be empty - eq_(self.cache._root._children, {}) + assert self.cache._root._children == {} # watchers should be reset root_path = self.client.chroot + self.path - eq_(self.client._data_watchers[root_path + '/foo'], set()) - eq_(self.client._data_watchers[root_path + '/foo/bar'], set()) - eq_(self.client._data_watchers[root_path + '/foo/bar/baz'], set()) - eq_(self.client._child_watchers[root_path + '/foo'], set()) - eq_(self.client._child_watchers[root_path + '/foo/bar'], set()) - eq_(self.client._child_watchers[root_path + '/foo/bar/baz'], set()) + assert self.client._data_watchers[root_path + '/foo'] == set() + assert self.client._data_watchers[root_path + '/foo/bar'] == set() + assert self.client._data_watchers[root_path + '/foo/bar/baz'] == set() + assert self.client._child_watchers[root_path + '/foo'] == set() + assert self.client._child_watchers[root_path + '/foo/bar'] == set() + assert self.client._child_watchers[root_path + '/foo/bar/baz'] == set() # should not be any leaked memory (tree node) here - eq_(self.count_tree_node(), 1) + assert self.count_tree_node() == 1 def test_children_operation(self): self.make_cache() @@ -218,24 +225,24 @@ class KazooTreeCacheTests(KazooAdaptiveHandlerTestCase): self.client.create(self.path + '/test_children', b'test_children_1') event = self.wait_cache(TreeEvent.NODE_ADDED) - eq_(event.event_type, TreeEvent.NODE_ADDED) - eq_(event.event_data.path, self.path + '/test_children') - eq_(event.event_data.data, b'test_children_1') - eq_(event.event_data.stat.version, 0) + assert event.event_type == TreeEvent.NODE_ADDED + assert event.event_data.path == self.path + '/test_children' + assert event.event_data.data == b'test_children_1' + assert event.event_data.stat.version == 0 self.client.set(self.path + '/test_children', b'test_children_2') event = self.wait_cache(TreeEvent.NODE_UPDATED) - eq_(event.event_type, TreeEvent.NODE_UPDATED) - eq_(event.event_data.path, self.path + '/test_children') - eq_(event.event_data.data, b'test_children_2') - eq_(event.event_data.stat.version, 1) + assert event.event_type == TreeEvent.NODE_UPDATED + assert event.event_data.path == self.path + '/test_children' + assert event.event_data.data == b'test_children_2' + assert event.event_data.stat.version == 1 self.client.delete(self.path + '/test_children') event = self.wait_cache(TreeEvent.NODE_REMOVED) - eq_(event.event_type, TreeEvent.NODE_REMOVED) - eq_(event.event_data.path, self.path + '/test_children') - eq_(event.event_data.data, b'test_children_2') - eq_(event.event_data.stat.version, 1) + assert event.event_type == TreeEvent.NODE_REMOVED + assert event.event_data.path == self.path + '/test_children' + assert event.event_data.data == b'test_children_2' + assert event.event_data.stat.version == 1 def test_subtree_operation(self): self.make_cache() @@ -244,16 +251,16 @@ class KazooTreeCacheTests(KazooAdaptiveHandlerTestCase): self.client.create(self.path + '/foo/bar/baz', makepath=True) for relative_path in ('/foo', '/foo/bar', '/foo/bar/baz'): event = self.wait_cache(TreeEvent.NODE_ADDED) - eq_(event.event_type, TreeEvent.NODE_ADDED) - eq_(event.event_data.path, self.path + relative_path) - eq_(event.event_data.data, b'') - eq_(event.event_data.stat.version, 0) + assert event.event_type == TreeEvent.NODE_ADDED + assert event.event_data.path == self.path + relative_path + assert event.event_data.data == b'' + assert event.event_data.stat.version == 0 self.client.delete(self.path + '/foo', recursive=True) for relative_path in ('/foo/bar/baz', '/foo/bar', '/foo'): event = self.wait_cache(TreeEvent.NODE_REMOVED) - eq_(event.event_type, TreeEvent.NODE_REMOVED) - eq_(event.event_data.path, self.path + relative_path) + assert event.event_type == TreeEvent.NODE_REMOVED + assert event.event_data.path == self.path + relative_path def test_get_data(self): cache = self.make_cache() @@ -264,17 +271,17 @@ class KazooTreeCacheTests(KazooAdaptiveHandlerTestCase): self.wait_cache(TreeEvent.NODE_ADDED) with patch.object(cache, '_client'): # disable any remote operation - eq_(cache.get_data(self.path).data, b'') - eq_(cache.get_data(self.path).stat.version, 0) + assert cache.get_data(self.path).data == b'' + assert cache.get_data(self.path).stat.version == 0 - eq_(cache.get_data(self.path + '/foo').data, b'') - eq_(cache.get_data(self.path + '/foo').stat.version, 0) + assert cache.get_data(self.path + '/foo').data == b'' + assert cache.get_data(self.path + '/foo').stat.version == 0 - eq_(cache.get_data(self.path + '/foo/bar').data, b'') - eq_(cache.get_data(self.path + '/foo/bar').stat.version, 0) + assert cache.get_data(self.path + '/foo/bar').data == b'' + assert cache.get_data(self.path + '/foo/bar').stat.version == 0 - eq_(cache.get_data(self.path + '/foo/bar/baz').data, b'@') - eq_(cache.get_data(self.path + '/foo/bar/baz').stat.version, 0) + assert cache.get_data(self.path + '/foo/bar/baz').data == b'@' + assert cache.get_data(self.path + '/foo/bar/baz').stat.version == 0 def test_get_children(self): cache = self.make_cache() @@ -285,36 +292,41 @@ class KazooTreeCacheTests(KazooAdaptiveHandlerTestCase): self.wait_cache(TreeEvent.NODE_ADDED) with patch.object(cache, '_client'): # disable any remote operation - eq_(cache.get_children(self.path + '/foo/bar/baz'), frozenset()) - eq_(cache.get_children(self.path + '/foo/bar'), frozenset(['baz'])) - eq_(cache.get_children(self.path + '/foo'), frozenset(['bar'])) - eq_(cache.get_children(self.path), frozenset(['foo'])) + assert ( + cache.get_children(self.path + '/foo/bar/baz') == frozenset() + ) + assert ( + cache.get_children(self.path + '/foo/bar') + == frozenset(['baz']) + ) + assert cache.get_children(self.path + '/foo') == frozenset(['bar']) + assert cache.get_children(self.path) == frozenset(['foo']) - @raises(ValueError) def test_get_data_out_of_tree(self): self.make_cache() self.wait_cache(since=TreeEvent.INITIALIZED) - self.cache.get_data('/out_of_tree') + with pytest.raises(ValueError): + self.cache.get_data('/out_of_tree') - @raises(ValueError) def test_get_children_out_of_tree(self): self.make_cache() self.wait_cache(since=TreeEvent.INITIALIZED) - self.cache.get_children('/out_of_tree') + with pytest.raises(ValueError): + self.cache.get_children('/out_of_tree') def test_get_data_no_node(self): cache = self.make_cache() self.wait_cache(since=TreeEvent.INITIALIZED) with patch.object(cache, '_client'): # disable any remote operation - eq_(cache.get_data(self.path + '/non_exists'), None) + assert cache.get_data(self.path + '/non_exists') is None def test_get_children_no_node(self): cache = self.make_cache() self.wait_cache(since=TreeEvent.INITIALIZED) with patch.object(cache, '_client'): # disable any remote operation - eq_(cache.get_children(self.path + '/non_exists'), None) + assert cache.get_children(self.path + '/non_exists') is None def test_session_reconnected(self): self.make_cache() @@ -322,7 +334,7 @@ class KazooTreeCacheTests(KazooAdaptiveHandlerTestCase): self.client.create(self.path + '/foo') event = self.wait_cache(TreeEvent.NODE_ADDED) - eq_(event.event_data.path, self.path + '/foo') + assert event.event_data.path == self.path + '/foo' with self.spy_client('get_async') as get_data: with self.spy_client('get_children_async') as get_children: @@ -346,14 +358,24 @@ class KazooTreeCacheTests(KazooAdaptiveHandlerTestCase): _node_foo = self.cache._root._children['foo'] # make sure that all nodes are refreshed - get_data.assert_has_calls([ - call(self.path, watch=_node_root._process_watch), - call(self.path + '/foo', watch=_node_foo._process_watch), - ], any_order=True) - get_children.assert_has_calls([ - call(self.path, watch=_node_root._process_watch), - call(self.path + '/foo', watch=_node_foo._process_watch), - ], any_order=True) + get_data.assert_has_calls( + [ + call(self.path, watch=_node_root._process_watch), + call( + self.path + '/foo', watch=_node_foo._process_watch + ), + ], + any_order=True, + ) + get_children.assert_has_calls( + [ + call(self.path, watch=_node_root._process_watch), + call( + self.path + '/foo', watch=_node_foo._process_watch + ), + ], + any_order=True, + ) def test_root_recreated(self): self.make_cache() @@ -362,22 +384,22 @@ class KazooTreeCacheTests(KazooAdaptiveHandlerTestCase): # remove root node self.client.delete(self.path) event = self.wait_cache(TreeEvent.NODE_REMOVED) - eq_(event.event_type, TreeEvent.NODE_REMOVED) - eq_(event.event_data.data, b'') - eq_(event.event_data.path, self.path) - eq_(event.event_data.stat.version, 0) + assert event.event_type == TreeEvent.NODE_REMOVED + assert event.event_data.data == b'' + assert event.event_data.path == self.path + assert event.event_data.stat.version == 0 # re-create root node self.client.ensure_path(self.path) event = self.wait_cache(TreeEvent.NODE_ADDED) - eq_(event.event_type, TreeEvent.NODE_ADDED) - eq_(event.event_data.data, b'') - eq_(event.event_data.path, self.path) - eq_(event.event_data.stat.version, 0) + assert event.event_type == TreeEvent.NODE_ADDED + assert event.event_data.data == b'' + assert event.event_data.path == self.path + assert event.event_data.stat.version == 0 - self.assertTrue( - self.cache._outstanding_ops >= 0, - 'unexpected outstanding ops %r' % self.cache._outstanding_ops) + assert self.cache._outstanding_ops >= 0, ( + 'unexpected outstanding ops %r' % self.cache._outstanding_ops + ) def test_exception_handler(self): error_value = FakeException() @@ -409,7 +431,7 @@ class KazooTreeCacheTests(KazooAdaptiveHandlerTestCase): self.wait_cache(since=TreeEvent.INITIALIZED) on_created.assert_not_called() - eq_(self.cache._outstanding_ops, 0) + assert self.cache._outstanding_ops == 0 class FakeException(Exception): diff --git a/kazoo/tests/test_client.py b/kazoo/tests/test_client.py index 32cc0d1..1800c57 100644 --- a/kazoo/tests/test_client.py +++ b/kazoo/tests/test_client.py @@ -7,9 +7,7 @@ import unittest import mock from mock import patch -from nose import SkipTest -from nose.tools import eq_, ok_, assert_not_equal -from nose.tools import raises +import pytest from kazoo.testing import KazooTestCase from kazoo.exceptions import ( @@ -55,77 +53,82 @@ class TestClientTransitions(KazooTestCase): rc.set() self.client.stop() - eq_(states, [KazooState.LOST]) + assert states == [KazooState.LOST] states.pop() self.client.start() rc.wait(2) - eq_(states, [KazooState.CONNECTED]) + assert states == [KazooState.CONNECTED] rc.clear() states.pop() self.expire_session(self.make_event) rc.wait(2) req_states = [KazooState.LOST, KazooState.CONNECTED] - eq_(states, req_states) + assert states == req_states class TestClientConstructor(unittest.TestCase): - def _makeOne(self, *args, **kw): from kazoo.client import KazooClient + return KazooClient(*args, **kw) def test_invalid_handler(self): from kazoo.handlers.threading import SequentialThreadingHandler - self.assertRaises( - ConfigurationError, - self._makeOne, handler=SequentialThreadingHandler) + + with pytest.raises(ConfigurationError): + self._makeOne(handler=SequentialThreadingHandler) def test_chroot(self): - self.assertEqual(self._makeOne(hosts='127.0.0.1:2181/').chroot, '') - self.assertEqual(self._makeOne(hosts='127.0.0.1:2181/a').chroot, '/a') - self.assertEqual(self._makeOne(hosts='127.0.0.1/a').chroot, '/a') - self.assertEqual(self._makeOne(hosts='127.0.0.1/a/b').chroot, '/a/b') - self.assertEqual(self._makeOne( - hosts='127.0.0.1:2181,127.0.0.1:2182/a/b').chroot, '/a/b') + assert self._makeOne(hosts='127.0.0.1:2181/').chroot == '' + assert self._makeOne(hosts='127.0.0.1:2181/a').chroot == '/a' + assert self._makeOne(hosts='127.0.0.1/a').chroot == '/a' + assert self._makeOne(hosts='127.0.0.1/a/b').chroot == '/a/b' + assert ( + self._makeOne(hosts='127.0.0.1:2181,127.0.0.1:2182/a/b').chroot + == '/a/b' + ) def test_connection_timeout(self): from kazoo.handlers.threading import KazooTimeoutError + client = self._makeOne(hosts='127.0.0.1:9') - self.assertTrue(client.handler.timeout_exception is KazooTimeoutError) - self.assertRaises(KazooTimeoutError, client.start, 0.1) + assert client.handler.timeout_exception is KazooTimeoutError + + with pytest.raises(KazooTimeoutError): + client.start(0.1) def test_ordered_host_selection(self): client = self._makeOne(hosts='127.0.0.1:9,127.0.0.2:9/a', randomize_hosts=False) hosts = [h for h in client.hosts] - eq_(hosts, [('127.0.0.1', 9), ('127.0.0.2', 9)]) + assert hosts == [('127.0.0.1', 9), ('127.0.0.2', 9)] def test_invalid_hostname(self): client = self._makeOne(hosts='nosuchhost/a') timeout = client.handler.timeout_exception - self.assertRaises(timeout, client.start, 0.1) + with pytest.raises(timeout): + client.start(0.1) def test_another_invalid_hostname(self): - self.assertRaises( - ValueError, - self._makeOne, hosts='/nosuchhost/a') + with pytest.raises(ValueError): + self._makeOne(hosts='/nosuchhost/a') def test_retry_options_dict(self): from kazoo.retry import KazooRetry client = self._makeOne(command_retry=dict(max_tries=99), connection_retry=dict(delay=99)) - self.assertTrue(type(client._conn_retry) is KazooRetry) - self.assertTrue(type(client._retry) is KazooRetry) - eq_(client._retry.max_tries, 99) - eq_(client._conn_retry.delay, 99) + assert type(client._conn_retry) is KazooRetry + assert type(client._retry) is KazooRetry + assert client._retry.max_tries == 99 + assert client._conn_retry.delay == 99 class TestAuthentication(KazooTestCase): - def _makeAuth(self, *args, **kwargs): from kazoo.security import make_digest_acl + return make_digest_acl(*args, **kwargs) def test_auth(self): @@ -146,14 +149,18 @@ class TestAuthentication(KazooTestCase): client.ensure_path("/1/2/3") eve = self._get_client() + eve.start() - self.assertRaises(NoAuthError, eve.get, "/1/2") + with pytest.raises(NoAuthError): + eve.get("/1/2") # try again with the wrong auth token eve.add_auth("digest", "badbad:bad") - self.assertRaises(NoAuthError, eve.get, "/1/2") + with pytest.raises(NoAuthError): + eve.get("/1/2") + finally: # Ensure we remove the ACL protected nodes client.delete("/1", recursive=True) @@ -173,7 +180,10 @@ class TestAuthentication(KazooTestCase): client.create('/1', acl=(acl,)) # give ZK a chance to copy data to other node time.sleep(0.1) - self.assertRaises(NoAuthError, self.client.get, "/1") + + with pytest.raises(NoAuthError): + self.client.get("/1") + finally: client.delete('/1') client.stop() @@ -197,12 +207,15 @@ class TestAuthentication(KazooTestCase): eve = self._get_client() eve.start() - self.assertRaises(NoAuthError, eve.get, "/1/2") + with pytest.raises(NoAuthError): + eve.get("/1/2") # try again with the wrong auth token eve.add_auth("digest", "badbad:bad") - self.assertRaises(NoAuthError, eve.get, "/1/2") + with pytest.raises(NoAuthError): + eve.get("/1/2") + finally: # Ensure we remove the ACL protected nodes client.delete("/1", recursive=True) @@ -212,10 +225,12 @@ class TestAuthentication(KazooTestCase): def test_invalid_auth(self): client = self._get_client() client.start() - self.assertRaises(TypeError, client.add_auth, - 'digest', ('user', 'pass')) - self.assertRaises(TypeError, client.add_auth, - None, ('user', 'pass')) + + with pytest.raises(TypeError): + client.add_auth('digest', ('user', 'pass')) + + with pytest.raises(TypeError): + client.add_auth(None, ('user', 'pass')) def test_async_auth(self): client = self._get_client() @@ -224,7 +239,7 @@ class TestAuthentication(KazooTestCase): password = uuid.uuid4().hex digest_auth = "%s:%s" % (username, password) result = client.add_auth_async("digest", digest_auth) - self.assertTrue(result.get()) + assert result.get() is True def test_async_auth_failure(self): client = self._get_client() @@ -233,8 +248,8 @@ class TestAuthentication(KazooTestCase): password = uuid.uuid4().hex digest_auth = "%s:%s" % (username, password) - self.assertRaises(AuthFailedError, client.add_auth, - "unknown-scheme", digest_auth) + with pytest.raises(AuthFailedError): + client.add_auth("unknown-scheme", digest_auth) def test_add_auth_on_reconnect(self): client = self._get_client() @@ -243,7 +258,7 @@ class TestAuthentication(KazooTestCase): client._connection._socket.shutdown(socket.SHUT_RDWR) while not client.connected: time.sleep(0.1) - self.assertTrue(("digest", "jsmith:jsmith") in client.auth_data) + assert ("digest", "jsmith:jsmith") in client.auth_data class TestConnection(KazooTestCase): @@ -300,6 +315,7 @@ class TestConnection(KazooTestCase): def test_state_listener(self): from kazoo.protocol.states import KazooState + states = [] condition = self.make_condition() @@ -309,7 +325,7 @@ class TestConnection(KazooTestCase): condition.notify_all() self.client.stop() - eq_(self.client.state, KazooState.LOST) + assert self.client.state == KazooState.LOST self.client.add_listener(listener) self.client.start(5) @@ -317,15 +333,17 @@ class TestConnection(KazooTestCase): if not states: condition.wait(5) - eq_(len(states), 1) - eq_(states[0], KazooState.CONNECTED) + assert len(states) == 1 + assert states[0] == KazooState.CONNECTED def test_invalid_listener(self): - self.assertRaises(ConfigurationError, self.client.add_listener, 15) + with pytest.raises(ConfigurationError): + self.client.add_listener(15) def test_listener_only_called_on_real_state_change(self): from kazoo.protocol.states import KazooState - self.assertTrue(self.client.state, KazooState.CONNECTED) + + assert self.client.state == KazooState.CONNECTED called = [False] condition = self.make_event() @@ -336,14 +354,16 @@ class TestConnection(KazooTestCase): self.client.add_listener(listener) self.client._make_state_change(KazooState.CONNECTED) condition.wait(3) - self.assertFalse(called[0]) + assert called[0] is False def test_no_connection(self): client = self.client client.stop() - self.assertFalse(client.connected) - self.assertTrue(client.client_id is None) - self.assertRaises(ConnectionClosedError, client.exists, '/') + assert client.connected is False + assert client.client_id is None + + with pytest.raises(ConnectionClosedError): + client.exists('/') def test_close_connecting_connection(self): client = self.client @@ -367,24 +387,24 @@ class TestConnection(KazooTestCase): # ...and then wait until the connection is lost ev.wait(5) - self.assertRaises(ConnectionClosedError, - self.client.create, '/foobar') + with pytest.raises(ConnectionClosedError): + self.client.create('/foobar') def test_double_start(self): - self.assertTrue(self.client.connected) + assert self.client.connected is True self.client.start() - self.assertTrue(self.client.connected) + assert self.client.connected is True def test_double_stop(self): self.client.stop() - self.assertFalse(self.client.connected) + assert self.client.connected is False self.client.stop() - self.assertFalse(self.client.connected) + assert self.client.connected is False def test_restart(self): - self.assertTrue(self.client.connected) + assert self.client.connected is True self.client.restart() - self.assertTrue(self.client.connected) + assert self.client.connected is True def test_closed(self): client = self.client @@ -394,20 +414,24 @@ class TestConnection(KazooTestCase): # close the connection to free the socket client.close() - eq_(client._connection._write_sock, None) + assert client._connection._write_sock is None # sneak in and patch client to simulate race between a thread # calling stop(); close() and one running a command oldstate = client._state client._state = KeeperState.CONNECTED client._connection._write_sock = write_sock + try: # simulate call made after write socket is closed - self.assertRaises(ConnectionClosedError, client.exists, '/') + with pytest.raises(ConnectionClosedError): + client.exists('/') # simulate call made after write socket is set to None client._connection._write_sock = None - self.assertRaises(ConnectionClosedError, client.exists, '/') + + with pytest.raises(ConnectionClosedError): + client.exists('/') finally: # reset for teardown @@ -433,10 +457,12 @@ class TestConnection(KazooTestCase): class TestClient(KazooTestCase): def _makeOne(self, *args): from kazoo.handlers.threading import SequentialThreadingHandler + return SequentialThreadingHandler(*args) def _getKazooState(self): from kazoo.protocol.states import KazooState + return KazooState def test_server_version_retries_fail(self): @@ -449,9 +475,8 @@ class TestClient(KazooTestCase): ] client.command = mock.MagicMock() client.command.side_effect = side_effects - self.assertRaises(KazooException, - client.server_version, - retries=len(side_effects) - 1) + with pytest.raises(KazooException): + client.server_version(retries=len(side_effects) - 1) def test_server_version_retries_eventually_ok(self): client = self.client @@ -461,106 +486,120 @@ class TestClient(KazooTestCase): side_effects.append(actual_version[0:i]) client.command = mock.MagicMock() client.command.side_effect = side_effects - self.assertEqual((1, 2), - client.server_version(retries=len(side_effects) - 1)) + assert client.server_version(retries=len(side_effects) - 1) == (1, 2) def test_client_id(self): client_id = self.client.client_id - self.assertEqual(type(client_id), tuple) + assert type(client_id) is tuple # make sure password is of correct length - self.assertEqual(len(client_id[1]), 16) + assert len(client_id[1]) == 16 def test_connected(self): client = self.client - self.assertTrue(client.connected) + assert client.connected def test_create(self): client = self.client path = client.create("/1") - eq_(path, "/1") - self.assertTrue(client.exists("/1")) + assert path == "/1" + assert client.exists("/1") def test_create_on_broken_connection(self): client = self.client client.start() client._state = KeeperState.EXPIRED_SESSION - self.assertRaises(SessionExpiredError, client.create, - '/closedpath', b'bar') + with pytest.raises(SessionExpiredError): + client.create('/closedpath', b'bar') client._state = KeeperState.AUTH_FAILED - self.assertRaises(AuthFailedError, client.create, - '/closedpath', b'bar') + with pytest.raises(AuthFailedError): + client.create('/closedpath', b'bar') client.stop() client.close() - self.assertRaises(ConnectionClosedError, client.create, - '/closedpath', b'bar') + with pytest.raises(ConnectionClosedError): + client.create('/closedpath', b'bar') def test_create_null_data(self): client = self.client client.create("/nulldata", None) value, _ = client.get("/nulldata") - self.assertEqual(value, None) + assert value is None def test_create_empty_string(self): client = self.client client.create("/empty", b"") value, _ = client.get("/empty") - eq_(value, b"") + assert value == b"" def test_create_unicode_path(self): client = self.client path = client.create(u("/ascii")) - eq_(path, u("/ascii")) + assert path == u("/ascii") path = client.create(u("/\xe4hm")) - eq_(path, u("/\xe4hm")) + assert path == u("/\xe4hm") def test_create_async_returns_unchrooted_path(self): client = self.client path = client.create_async('/1').get() - eq_(path, "/1") + assert path == "/1" def test_create_invalid_path(self): client = self.client - self.assertRaises(TypeError, client.create, ('a', )) - self.assertRaises(ValueError, client.create, ".") - self.assertRaises(ValueError, client.create, "/a/../b") - self.assertRaises(BadArgumentsError, client.create, "/b\x00") - self.assertRaises(BadArgumentsError, client.create, "/b\x1e") + with pytest.raises(TypeError): + client.create(('a',)) + with pytest.raises(ValueError): + client.create(".") + with pytest.raises(ValueError): + client.create("/a/../b") + with pytest.raises(BadArgumentsError): + client.create("/b\x00") + with pytest.raises(BadArgumentsError): + client.create("/b\x1e") def test_create_invalid_arguments(self): from kazoo.security import OPEN_ACL_UNSAFE + single_acl = OPEN_ACL_UNSAFE[0] client = self.client - self.assertRaises(TypeError, client.create, 'a', acl='all') - self.assertRaises(TypeError, client.create, 'a', acl=single_acl) - self.assertRaises(TypeError, client.create, 'a', value=['a']) - self.assertRaises(TypeError, client.create, 'a', ephemeral='yes') - self.assertRaises(TypeError, client.create, 'a', sequence='yes') - self.assertRaises(TypeError, client.create, 'a', makepath='yes') + with pytest.raises(TypeError): + client.create('a', acl='all') + with pytest.raises(TypeError): + client.create('a', acl=single_acl) + with pytest.raises(TypeError): + client.create('a', value=['a']) + with pytest.raises(TypeError): + client.create('a', ephemeral='yes') + with pytest.raises(TypeError): + client.create('a', sequence='yes') + with pytest.raises(TypeError): + client.create('a', makepath='yes') def test_create_value(self): client = self.client client.create("/1", b"bytes") data, stat = client.get("/1") - eq_(data, b"bytes") + assert data == b"bytes" def test_create_unicode_value(self): client = self.client - self.assertRaises(TypeError, client.create, "/1", u("\xe4hm")) + with pytest.raises(TypeError): + client.create("/1", u("\xe4hm")) def test_create_large_value(self): client = self.client kb_512 = b"a" * (512 * 1024) client.create("/1", kb_512) - self.assertTrue(client.exists("/1")) + assert client.exists("/1") mb_2 = b"a" * (2 * 1024 * 1024) - self.assertRaises(ConnectionLoss, client.create, "/2", mb_2) + with pytest.raises(ConnectionLoss): + client.create("/2", mb_2) def test_create_acl_duplicate(self): from kazoo.security import OPEN_ACL_UNSAFE + single_acl = OPEN_ACL_UNSAFE[0] client = self.client client.create("/1", acl=[single_acl, single_acl]) @@ -570,107 +609,113 @@ class TestClient(KazooTestCase): version = TRAVIS_ZK_VERSION else: version = client.server_version() - self.assertEqual(len(acls), 1 if version > (3, 4) else 2) + assert len(acls) == 1 if version > (3, 4) else 2 def test_create_acl_empty_list(self): from kazoo.security import OPEN_ACL_UNSAFE + client = self.client client.create("/1", acl=[]) acls, stat = client.get_acls("/1") - self.assertEqual(acls, OPEN_ACL_UNSAFE) + assert acls == OPEN_ACL_UNSAFE def test_version_no_connection(self): - @raises(ConnectionLoss) - def testit(): - self.client.server_version() self.client.stop() - testit() + with pytest.raises(ConnectionLoss): + self.client.server_version() def test_create_ephemeral(self): client = self.client client.create("/1", b"ephemeral", ephemeral=True) data, stat = client.get("/1") - eq_(data, b"ephemeral") - eq_(stat.ephemeralOwner, client.client_id[0]) + assert data == b"ephemeral" + assert stat.ephemeralOwner == client.client_id[0] def test_create_no_ephemeral(self): client = self.client client.create("/1", b"val1") data, stat = client.get("/1") - self.assertFalse(stat.ephemeralOwner) + assert not stat.ephemeralOwner def test_create_ephemeral_no_children(self): from kazoo.exceptions import NoChildrenForEphemeralsError + client = self.client client.create("/1", b"ephemeral", ephemeral=True) - self.assertRaises(NoChildrenForEphemeralsError, - client.create, "/1/2", b"val1") - self.assertRaises(NoChildrenForEphemeralsError, - client.create, "/1/2", b"val1", ephemeral=True) + with pytest.raises(NoChildrenForEphemeralsError): + client.create("/1/2", b"val1") + with pytest.raises(NoChildrenForEphemeralsError): + client.create("/1/2", b"val1", ephemeral=True) def test_create_sequence(self): client = self.client client.create("/folder") path = client.create("/folder/a", b"sequence", sequence=True) - eq_(path, "/folder/a0000000000") + assert path == "/folder/a0000000000" path2 = client.create("/folder/a", b"sequence", sequence=True) - eq_(path2, "/folder/a0000000001") + assert path2 == "/folder/a0000000001" path3 = client.create("/folder/", b"sequence", sequence=True) - eq_(path3, "/folder/0000000002") + assert path3 == "/folder/0000000002" def test_create_ephemeral_sequence(self): basepath = "/" + uuid.uuid4().hex realpath = self.client.create(basepath, b"sandwich", sequence=True, ephemeral=True) - self.assertTrue(basepath != realpath and realpath.startswith(basepath)) + assert basepath != realpath and realpath.startswith(basepath) data, stat = self.client.get(realpath) - eq_(data, b"sandwich") + assert data == b"sandwich" def test_create_makepath(self): self.client.create("/1/2", b"val1", makepath=True) data, stat = self.client.get("/1/2") - eq_(data, b"val1") + assert data == b"val1" self.client.create("/1/2/3/4/5", b"val2", makepath=True) data, stat = self.client.get("/1/2/3/4/5") - eq_(data, b"val2") + assert data == b"val2" - self.assertRaises(NodeExistsError, self.client.create, - "/1/2/3/4/5", b"val2", makepath=True) + with pytest.raises(NodeExistsError): + self.client.create("/1/2/3/4/5", b"val2", makepath=True) def test_create_makepath_incompatible_acls(self): from kazoo.client import KazooClient from kazoo.security import make_digest_acl_credential, CREATOR_ALL_ACL + credential = make_digest_acl_credential("username", "password") alt_client = KazooClient( self.cluster[0].address + self.client.chroot, - max_retries=5, auth_data=[("digest", credential)], - handler=self._makeOne()) + max_retries=5, + auth_data=[("digest", credential)], + handler=self._makeOne(), + ) alt_client.start() alt_client.create("/1/2", b"val2", makepath=True, acl=CREATOR_ALL_ACL) try: - self.assertRaises(NoAuthError, self.client.create, - "/1/2/3/4/5", b"val2", makepath=True) + with pytest.raises(NoAuthError): + self.client.create("/1/2/3/4/5", b"val2", makepath=True) + finally: alt_client.delete('/', recursive=True) alt_client.stop() def test_create_no_makepath(self): - self.assertRaises(NoNodeError, self.client.create, - "/1/2", b"val1") - self.assertRaises(NoNodeError, self.client.create, - "/1/2", b"val1", makepath=False) + with pytest.raises(NoNodeError): + self.client.create("/1/2", b"val1") + with pytest.raises(NoNodeError): + self.client.create("/1/2", b"val1", makepath=False) self.client.create("/1/2", b"val1", makepath=True) - self.assertRaises(NoNodeError, self.client.create, - "/1/2/3/4", b"val1", makepath=False) + with pytest.raises(NoNodeError): + self.client.create("/1/2/3/4", b"val1", makepath=False) def test_create_exists(self): from kazoo.exceptions import NodeExistsError + client = self.client path = client.create("/1") - self.assertRaises(NodeExistsError, client.create, path) + with pytest.raises(NodeExistsError): + client.create(path) def test_create_stat(self): if TRAVIS_ZK_VERSION: @@ -678,12 +723,12 @@ class TestClient(KazooTestCase): else: version = self.client.server_version() if not version or version < (3, 5): - raise SkipTest("Must use Zookeeper 3.5 or above") + pytest.skip("Must use Zookeeper 3.5 or above") client = self.client path, stat1 = client.create("/1", b"bytes", include_data=True) data, stat2 = client.get("/1") - eq_(data, b"bytes") - eq_(stat1, stat2) + assert data == b"bytes" + assert stat1 == stat2 def test_create_get_set(self): nodepath = "/" + uuid.uuid4().hex @@ -691,80 +736,86 @@ class TestClient(KazooTestCase): self.client.create(nodepath, b"sandwich", ephemeral=True) data, stat = self.client.get(nodepath) - eq_(data, b"sandwich") + assert data == b"sandwich" newstat = self.client.set(nodepath, b"hats", stat.version) - self.assertTrue(newstat) + assert newstat assert newstat.version > stat.version # Some other checks of the ZnodeStat object we got - eq_(newstat.acl_version, stat.acl_version) - eq_(newstat.created, stat.ctime / 1000.0) - eq_(newstat.last_modified, newstat.mtime / 1000.0) - eq_(newstat.owner_session_id, stat.ephemeralOwner) - eq_(newstat.creation_transaction_id, stat.czxid) - eq_(newstat.last_modified_transaction_id, newstat.mzxid) - eq_(newstat.data_length, newstat.dataLength) - eq_(newstat.children_count, stat.numChildren) - eq_(newstat.children_version, stat.cversion) + assert newstat.acl_version == stat.acl_version + assert newstat.created == stat.ctime / 1000.0 + assert newstat.last_modified == newstat.mtime / 1000.0 + assert newstat.owner_session_id == stat.ephemeralOwner + assert newstat.creation_transaction_id == stat.czxid + assert newstat.last_modified_transaction_id == newstat.mzxid + assert newstat.data_length == newstat.dataLength + assert newstat.children_count == stat.numChildren + assert newstat.children_version == stat.cversion def test_get_invalid_arguments(self): client = self.client - self.assertRaises(TypeError, client.get, ('a', 'b')) - self.assertRaises(TypeError, client.get, 'a', watch=True) + with pytest.raises(TypeError): + client.get(('a', 'b')) + with pytest.raises(TypeError): + client.get('a', watch=True) def test_bad_argument(self): client = self.client client.ensure_path("/1") - self.assertRaises(TypeError, self.client.set, "/1", 1) + with pytest.raises(TypeError): + self.client.set("/1", 1) def test_ensure_path(self): client = self.client client.ensure_path("/1/2") - self.assertTrue(client.exists("/1/2")) + assert client.exists("/1/2") client.ensure_path("/1/2/3/4") - self.assertTrue(client.exists("/1/2/3/4")) + assert client.exists("/1/2/3/4") + @pytest.mark.skip("BUG: sync() call is not chroot'd") def test_sync(self): client = self.client - self.assertTrue(client.sync('/'), '/') + assert client.sync('/') == '/' def test_exists(self): nodepath = "/" + uuid.uuid4().hex exists = self.client.exists(nodepath) - eq_(exists, None) + assert exists is None self.client.create(nodepath, b"sandwich", ephemeral=True) exists = self.client.exists(nodepath) - self.assertTrue(exists) + assert exists assert isinstance(exists.version, int) multi_node_nonexistent = "/" + uuid.uuid4().hex + "/hats" exists = self.client.exists(multi_node_nonexistent) - eq_(exists, None) + assert exists is None def test_exists_invalid_arguments(self): client = self.client - self.assertRaises(TypeError, client.exists, ('a', 'b')) - self.assertRaises(TypeError, client.exists, 'a', watch=True) + with pytest.raises(TypeError): + client.exists(('a', 'b')) + with pytest.raises(TypeError): + client.exists('a', watch=True) def test_exists_watch(self): nodepath = "/" + uuid.uuid4().hex event = self.client.handler.event_object() def w(watch_event): - eq_(watch_event.path, nodepath) + assert watch_event.path == nodepath event.set() exists = self.client.exists(nodepath, watch=w) - eq_(exists, None) + assert exists is None self.client.create(nodepath, ephemeral=True) event.wait(1) - self.assertTrue(event.is_set()) + assert event.is_set() is True def test_exists_watcher_exception(self): nodepath = "/" + uuid.uuid4().hex @@ -772,18 +823,18 @@ class TestClient(KazooTestCase): # if the watcher throws an exception, all we can really do is log it def w(watch_event): - eq_(watch_event.path, nodepath) + assert watch_event.path == nodepath event.set() raise Exception("test exception in callback") exists = self.client.exists(nodepath, watch=w) - eq_(exists, None) + assert exists is None self.client.create(nodepath, ephemeral=True) event.wait(1) - self.assertTrue(event.is_set()) + assert event.is_set() is True def test_create_delete(self): nodepath = "/" + uuid.uuid4().hex @@ -793,10 +844,11 @@ class TestClient(KazooTestCase): self.client.delete(nodepath) exists = self.client.exists(nodepath) - eq_(exists, None) + assert exists is None def test_get_acls(self): from kazoo.security import make_digest_acl + user = 'user' passw = 'pass' acl = make_digest_acl(user, passw, all=True) @@ -804,16 +856,18 @@ class TestClient(KazooTestCase): try: client.create('/a', acl=[acl]) client.add_auth('digest', '{}:{}'.format(user, passw)) - self.assertTrue(acl in client.get_acls('/a')[0]) + assert acl in client.get_acls('/a')[0] finally: client.delete('/a') def test_get_acls_invalid_arguments(self): client = self.client - self.assertRaises(TypeError, client.get_acls, ('a', 'b')) + with pytest.raises(TypeError): + client.get_acls(('a', 'b')) def test_set_acls(self): from kazoo.security import make_digest_acl + user = 'user' passw = 'pass' acl = make_digest_acl(user, passw, all=True) @@ -822,64 +876,75 @@ class TestClient(KazooTestCase): try: client.set_acls('/a', [acl]) client.add_auth('digest', '{}:{}'.format(user, passw)) - self.assertTrue(acl in client.get_acls('/a')[0]) + assert acl in client.get_acls('/a')[0] finally: client.delete('/a') def test_set_acls_empty(self): client = self.client client.create('/a') - self.assertRaises(InvalidACLError, client.set_acls, '/a', []) + with pytest.raises(InvalidACLError): + client.set_acls('/a', []) def test_set_acls_no_node(self): from kazoo.security import OPEN_ACL_UNSAFE + client = self.client - self.assertRaises(NoNodeError, client.set_acls, '/a', OPEN_ACL_UNSAFE) + with pytest.raises(NoNodeError): + client.set_acls('/a', OPEN_ACL_UNSAFE) def test_set_acls_invalid_arguments(self): from kazoo.security import OPEN_ACL_UNSAFE + single_acl = OPEN_ACL_UNSAFE[0] client = self.client - self.assertRaises(TypeError, client.set_acls, ('a', 'b'), ()) - self.assertRaises(TypeError, client.set_acls, 'a', single_acl) - self.assertRaises(TypeError, client.set_acls, 'a', 'all') - self.assertRaises(TypeError, client.set_acls, 'a', [single_acl], 'V1') + with pytest.raises(TypeError): + client.set_acls(('a', 'b'), ()) + with pytest.raises(TypeError): + client.set_acls('a', single_acl) + with pytest.raises(TypeError): + client.set_acls('a', 'all') + with pytest.raises(TypeError): + client.set_acls('a', [single_acl], 'V1') def test_set(self): client = self.client client.create('a', b'first') stat = client.set('a', b'second') data, stat2 = client.get('a') - self.assertEqual(data, b'second') - self.assertEqual(stat, stat2) + assert data == b'second' + assert stat == stat2 def test_set_null_data(self): client = self.client client.create("/nulldata", b"not none") client.set("/nulldata", None) value, _ = client.get("/nulldata") - self.assertEqual(value, None) + assert value is None def test_set_empty_string(self): client = self.client client.create("/empty", b"not empty") client.set("/empty", b"") value, _ = client.get("/empty") - eq_(value, b"") + assert value == b"" def test_set_invalid_arguments(self): client = self.client client.create('a', b'first') - self.assertRaises(TypeError, client.set, ('a', 'b'), b'value') - self.assertRaises(TypeError, client.set, 'a', ['v', 'w']) - self.assertRaises(TypeError, client.set, 'a', b'value', 'V1') + with pytest.raises(TypeError): + client.set(('a', 'b'), b'value') + with pytest.raises(TypeError): + client.set('a', ['v', 'w']) + with pytest.raises(TypeError): + client.set('a', b'value', 'V1') def test_delete(self): client = self.client client.ensure_path('/a/b') - self.assertTrue('b' in client.get_children('a')) + assert 'b' in client.get_children('a') client.delete('/a/b') - self.assertFalse('b' in client.get_children('a')) + assert 'b' not in client.get_children('a') def test_delete_recursive(self): client = self.client @@ -887,30 +952,33 @@ class TestClient(KazooTestCase): client.ensure_path('/a/b/d') client.delete('/a/b', recursive=True) client.delete('/a/b/c', recursive=True) - self.assertFalse('b' in client.get_children('a')) + assert 'b' not in client.get_children('a') def test_delete_invalid_arguments(self): client = self.client client.ensure_path('/a/b') - self.assertRaises(TypeError, client.delete, '/a/b', recursive='all') - self.assertRaises(TypeError, client.delete, ('a', 'b')) - self.assertRaises(TypeError, client.delete, '/a/b', version='V1') + with pytest.raises(TypeError): + client.delete('/a/b', recursive='all') + with pytest.raises(TypeError): + client.delete(('a', 'b')) + with pytest.raises(TypeError): + client.delete('/a/b', version='V1') def test_get_children(self): client = self.client client.ensure_path('/a/b/c') client.ensure_path('/a/b/d') - self.assertEqual(client.get_children('/a'), ['b']) - self.assertEqual(set(client.get_children('/a/b')), set(['c', 'd'])) - self.assertEqual(client.get_children('/a/b/c'), []) + assert client.get_children('/a') == ['b'] + assert set(client.get_children('/a/b')) == set(['c', 'd']) + assert client.get_children('/a/b/c') == [] def test_get_children2(self): client = self.client client.ensure_path('/a/b') children, stat = client.get_children('/a', include_data=True) value, stat2 = client.get('/a') - self.assertEqual(children, ['b']) - self.assertEqual(stat2.version, stat.version) + assert children == ['b'] + assert stat2.version == stat.version def test_get_children2_many_nodes(self): client = self.client @@ -919,25 +987,29 @@ class TestClient(KazooTestCase): client.ensure_path('/a/d') children, stat = client.get_children('/a', include_data=True) value, stat2 = client.get('/a') - self.assertEqual(set(children), set(['b', 'c', 'd'])) - self.assertEqual(stat2.version, stat.version) + assert set(children) == set(['b', 'c', 'd']) + assert stat2.version == stat.version def test_get_children_no_node(self): client = self.client - self.assertRaises(NoNodeError, client.get_children, '/none') - self.assertRaises(NoNodeError, client.get_children, - '/none', include_data=True) + with pytest.raises(NoNodeError): + client.get_children('/none') + with pytest.raises(NoNodeError): + client.get_children('/none', include_data=True) def test_get_children_invalid_path(self): client = self.client - self.assertRaises(ValueError, client.get_children, '../a') + with pytest.raises(ValueError): + client.get_children('../a') def test_get_children_invalid_arguments(self): client = self.client - self.assertRaises(TypeError, client.get_children, ('a', 'b')) - self.assertRaises(TypeError, client.get_children, 'a', watch=True) - self.assertRaises(TypeError, client.get_children, - 'a', include_data='yes') + with pytest.raises(TypeError): + client.get_children(('a', 'b')) + with pytest.raises(TypeError): + client.get_children('a', watch=True) + with pytest.raises(TypeError): + client.get_children('a', include_data='yes') def test_invalid_auth(self): from kazoo.exceptions import AuthFailedError @@ -947,26 +1019,26 @@ class TestClient(KazooTestCase): client.stop() client._state = KeeperState.AUTH_FAILED - @raises(AuthFailedError) - def testit(): + with pytest.raises(AuthFailedError): client.get('/') - testit() def test_client_state(self): from kazoo.protocol.states import KeeperState - eq_(self.client.client_state, KeeperState.CONNECTED) + + assert self.client.client_state == KeeperState.CONNECTED def test_update_host_list(self): from kazoo.client import KazooClient from kazoo.protocol.states import KeeperState + hosts = self.cluster[0].address # create a client with only one server in its list client = KazooClient(hosts=hosts) client.start() # try to change the chroot, not currently allowed - self.assertRaises(ConfigurationError, - client.set_hosts, hosts + '/new_chroot') + with pytest.raises(ConfigurationError): + client.set_hosts(hosts + '/new_chroot') # grow the cluster to 3 client.set_hosts(self.servers) @@ -975,13 +1047,14 @@ class TestClient(KazooTestCase): try: self.cluster[0].stop() time.sleep(5) - eq_(client.client_state, KeeperState.CONNECTED) + assert client.client_state == KeeperState.CONNECTED finally: self.cluster[0].run() # utility for test_request_queuing* def _make_request_queuing_client(self): from kazoo.client import KazooClient + server = self.cluster[0] handler = self._makeOne() # create a client with only one server in its list, and @@ -994,8 +1067,8 @@ class TestClient(KazooTestCase): delay=0.1, backoff=1, max_jitter=0.0, - sleep_func=handler.sleep_func - ) + sleep_func=handler.sleep_func, + ), ) return client, server @@ -1010,6 +1083,7 @@ class TestClient(KazooTestCase): ev_suspended.set() elif state == KazooState.CONNECTED: ev_connected.set() + client.add_listener(listener) # wait for the client to connect @@ -1020,14 +1094,14 @@ class TestClient(KazooTestCase): server.stop() ev_suspended.wait(5) - ok_(ev_suspended.is_set()) + assert ev_suspended.is_set() ev_connected.clear() # submit a request, expecting it to be queued result = client.create_async(path) - assert_not_equal(len(client._queue), 0) - eq_(result.ready(), False) - eq_(client.state, KazooState.SUSPENDED) + assert len(client._queue) != 0 + assert result.ready() is False + assert client.state == KazooState.SUSPENDED # optionally cause a SessionExpiredError to occur by # mangling the first byte of the session password. @@ -1042,7 +1116,7 @@ class TestClient(KazooTestCase): # wait for the client to reconnect (either with a recovered # session, or with a new one if expire_session was set) ev_connected.wait(5) - ok_(ev_connected.is_set()) + assert ev_connected.is_set() return result @@ -1058,8 +1132,8 @@ class TestClient(KazooTestCase): expire_session=False ) - eq_(result.get(), path) - assert_not_equal(client.exists(path), None) + assert result.get() == path + assert client.exists(path) is not None finally: client.stop() @@ -1075,21 +1149,29 @@ class TestClient(KazooTestCase): expire_session=True ) - eq_(len(client._queue), 0) - self.assertRaises(SessionExpiredError, result.get) + assert len(client._queue) == 0 + with pytest.raises(SessionExpiredError): + result.get() finally: client.stop() dummy_dict = { - 'aversion': 1, 'ctime': 0, 'cversion': 1, - 'czxid': 110, 'dataLength': 1, 'ephemeralOwner': 'ben', - 'mtime': 1, 'mzxid': 1, 'numChildren': 0, 'pzxid': 1, 'version': 1 + 'aversion': 1, + 'ctime': 0, + 'cversion': 1, + 'czxid': 110, + 'dataLength': 1, + 'ephemeralOwner': 'ben', + 'mtime': 1, + 'mzxid': 1, + 'numChildren': 0, + 'pzxid': 1, + 'version': 1, } class TestClientTransactions(KazooTestCase): - def setUp(self): KazooTestCase.setUp(self) skip = False @@ -1102,7 +1184,7 @@ class TestClientTransactions(KazooTestCase): if ver[1] < 4: skip = True if skip: - raise SkipTest("Must use Zookeeper 3.4 or above") + pytest.skip("Must use Zookeeper 3.4 or above") def test_basic_create(self): t = self.client.transaction() @@ -1110,25 +1192,23 @@ class TestClientTransactions(KazooTestCase): t.create('/fred', ephemeral=True) t.create('/smith', sequence=True) results = t.commit() - eq_(len(results), 3) - eq_(results[0], '/freddy') - self.assertTrue(results[2].startswith('/smith0')) + assert len(results) == 3 + assert results[0] == '/freddy' + assert results[2].startswith('/smith0') is True def test_bad_creates(self): args_list = [(True,), ('/smith', 0), ('/smith', b'', 'bleh'), ('/smith', b'', None, 'fred'), ('/smith', b'', None, True, 'fred')] - @raises(TypeError) - def testit(args): - t = self.client.transaction() - t.create(*args) - for args in args_list: - testit(args) + with pytest.raises(TypeError): + t = self.client.transaction() + t.create(*args) def test_default_acl(self): from kazoo.security import make_digest_acl + username = uuid.uuid4().hex password = uuid.uuid4().hex @@ -1141,25 +1221,22 @@ class TestClientTransactions(KazooTestCase): t = self.client.transaction() t.create('/freddy') results = t.commit() - eq_(results[0], '/freddy') + assert results[0] == '/freddy' def test_basic_delete(self): self.client.create('/fred') t = self.client.transaction() t.delete('/fred') results = t.commit() - eq_(results[0], True) + assert results[0] is True def test_bad_deletes(self): args_list = [(True,), ('/smith', 'woops'), ] - @raises(TypeError) - def testit(args): - t = self.client.transaction() - t.delete(*args) - for args in args_list: - testit(args) + with pytest.raises(TypeError): + t = self.client.transaction() + t.delete(*args) def test_set(self): self.client.create('/fred', b'01') @@ -1167,18 +1244,15 @@ class TestClientTransactions(KazooTestCase): t.set_data('/fred', b'oops') t.commit() res = self.client.get('/fred') - eq_(res[0], b'oops') + assert res[0] == b'oops' def test_bad_sets(self): args_list = [(42, 52), ('/smith', False), ('/smith', b'', 'oops')] - @raises(TypeError) - def testit(args): - t = self.client.transaction() - t.set_data(*args) - for args in args_list: - testit(args) + with pytest.raises(TypeError): + t = self.client.transaction() + t.set_data(*args) def test_check(self): self.client.create('/fred') @@ -1187,50 +1261,43 @@ class TestClientTransactions(KazooTestCase): t.check('/fred', version) t.create('/blah') results = t.commit() - eq_(results[0], True) - eq_(results[1], '/blah') + assert results[0] is True + assert results[1] == '/blah' def test_bad_checks(self): args_list = [(42, 52), ('/smith', 'oops')] - @raises(TypeError) - def testit(args): - t = self.client.transaction() - t.check(*args) - for args in args_list: - testit(args) + with pytest.raises(TypeError): + t = self.client.transaction() + t.check(*args) def test_bad_transaction(self): from kazoo.exceptions import RolledBackError, NoNodeError + t = self.client.transaction() t.create('/fred') t.delete('/smith') results = t.commit() - eq_(results[0].__class__, RolledBackError) - eq_(results[1].__class__, NoNodeError) + assert results[0].__class__ == RolledBackError + assert results[1].__class__ == NoNodeError def test_bad_commit(self): t = self.client.transaction() + t.committed = True - @raises(ValueError) - def testit(): + with pytest.raises(ValueError): t.commit() - t.committed = True - testit() - def test_bad_context(self): - @raises(TypeError) - def testit(): + with pytest.raises(TypeError): with self.client.transaction() as t: t.check(4232) - testit() def test_context(self): with self.client.transaction() as t: t.create('/smith', b'32') - eq_(self.client.get('/smith')[0], b'32') + assert self.client.get('/smith')[0] == b'32' class TestSessionCallbacks(unittest.TestCase): @@ -1243,25 +1310,25 @@ class TestSessionCallbacks(unittest.TestCase): client._live.set() result = client._session_callback(KeeperState.CONNECTED) - eq_(result, None) + assert result is None # Now with stopped client._stopped.set() result = client._session_callback(KeeperState.CONNECTED) - eq_(result, None) + assert result is None # Test several state transitions client._stopped.clear() client.start_async = lambda: True client._session_callback(KeeperState.CONNECTED) - eq_(client.state, KazooState.CONNECTED) + assert client.state == KazooState.CONNECTED client._session_callback(KeeperState.AUTH_FAILED) - eq_(client.state, KazooState.LOST) + assert client.state == KazooState.LOST client._handle = 1 client._session_callback(-250) - eq_(client.state, KazooState.SUSPENDED) + assert client.state == KazooState.SUSPENDED class TestCallbacks(KazooTestCase): @@ -1280,17 +1347,17 @@ class TestCallbacks(KazooTestCase): # this should be on another thread, # simultaneously with the stop procedure async_result.set_exception( - Exception("Anything that throws an exception")) + Exception("Anything that throws an exception") + ) # with the fix the callback should be called - self.assertGreater(callback_mock.call_count, 0) + assert callback_mock.call_count > 0 class TestNonChrootClient(KazooTestCase): - def test_create(self): client = self._get_nonchroot_client() - self.assertEqual(client.chroot, '') + assert client.chroot == '' client.start() node = uuid.uuid4().hex path = client.create(node, ephemeral=True) @@ -1300,8 +1367,8 @@ class TestNonChrootClient(KazooTestCase): def test_unchroot(self): client = self._get_nonchroot_client() client.chroot = '/a' - self.assertEquals(client.unchroot('/a/b'), '/b') - self.assertEquals(client.unchroot('/b/c'), '/b/c') + assert client.unchroot('/a/b') == '/b' + assert client.unchroot('/b/c') == '/b/c' class TestReconfig(KazooTestCase): @@ -1313,14 +1380,15 @@ class TestReconfig(KazooTestCase): else: version = self.client.server_version() if not version or version < (3, 5): - raise SkipTest("Must use Zookeeper 3.5 or above") + pytest.skip("Must use Zookeeper 3.5 or above") def test_no_super_auth(self): - self.assertRaises(NoAuthError, - self.client.reconfig, - joining='server.999=0.0.0.0:1234:2345:observer;3456', - leaving=None, - new_members=None) + with pytest.raises(NoAuthError): + self.client.reconfig( + joining='server.999=0.0.0.0:1234:2345:observer;3456', + leaving=None, + new_members=None, + ) def test_add_remove_observer(self): def free_sock_port(): @@ -1347,25 +1415,25 @@ class TestReconfig(KazooTestCase): data, _ = client.reconfig(joining=joining, leaving=None, new_members=None) - self.assertIn(joining.encode('utf8'), data) + assert joining.encode('utf8') in data data, _ = client.reconfig(joining=None, leaving='100', new_members=None) - self.assertNotIn(joining.encode('utf8'), data) + assert joining.encode('utf8') not in data # try to add it again, but a config number in the future curver = int(data.decode().split('\n')[-1].split('=')[1], base=16) - self.assertRaises(BadVersionError, - self.client.reconfig, - joining=joining, - leaving=None, - new_members=None, - from_config=curver + 1) + with pytest.raises(BadVersionError): + self.client.reconfig( + joining=joining, + leaving=None, + new_members=None, + from_config=curver + 1, + ) def test_bad_input(self): - self.assertRaises(BadArgumentsError, - self.client.reconfig, - joining='some thing', - leaving=None, - new_members=None) + with pytest.raises(BadArgumentsError): + self.client.reconfig( + joining='some thing', leaving=None, new_members=None + ) diff --git a/kazoo/tests/test_connection.py b/kazoo/tests/test_connection.py index cda6b6f..411d2d0 100644 --- a/kazoo/tests/test_connection.py +++ b/kazoo/tests/test_connection.py @@ -6,9 +6,7 @@ import uuid import struct import sys -from nose import SkipTest -from nose.tools import eq_ -from nose.tools import raises +import pytest import mock from kazoo.exceptions import ConnectionLoss @@ -42,13 +40,12 @@ class TestConnectionHandler(KazooTestCase): def test_bad_deserialization(self): async_object = self.client.handler.async_result() self.client._queue.append( - (Delete(self.client.chroot, -1), async_object)) + (Delete(self.client.chroot, -1), async_object) + ) self.client._connection._write_sock.send(b'\0') - @raises(ValueError) - def testit(): + with pytest.raises(ValueError): async_object.get() - testit() def test_with_bad_sessionid(self): ev = threading.Event() @@ -63,7 +60,7 @@ class TestConnectionHandler(KazooTestCase): client.start() try: ev.wait(15) - eq_(ev.is_set(), True) + assert ev.is_set() finally: client.stop() @@ -90,13 +87,14 @@ class TestConnectionHandler(KazooTestCase): client.create(path, b"1") try: handler.select = delayed_select - self.assertRaises(ConnectionLoss, client.get, path) + with pytest.raises(ConnectionLoss): + client.get(path) finally: handler.select = _select # the client reconnects automatically ev.wait(5) - eq_(ev.is_set(), True) - eq_(client.get(path)[0], b"1") + assert ev.is_set() + assert client.get(path)[0] == b"1" def test_connection_write_timeout(self): client = self.client @@ -116,17 +114,19 @@ class TestConnectionHandler(KazooTestCase): def back(state): if state == KazooState.CONNECTED: ev.set() + client.add_listener(back) try: handler.select = delayed_select - self.assertRaises(ConnectionLoss, client.create, path) + with pytest.raises(ConnectionLoss): + client.create(path) finally: handler.select = _select # the client reconnects automatically ev.wait(5) - eq_(ev.is_set(), True) - eq_(client.exists(path), None) + assert ev.is_set() + assert client.exists(path) is None def test_connection_deserialize_fail(self): client = self.client @@ -146,6 +146,7 @@ class TestConnectionHandler(KazooTestCase): def back(state): if state == KazooState.CONNECTED: ev.set() + client.add_listener(back) deserialize_ev = threading.Event() @@ -163,21 +164,23 @@ class TestConnectionHandler(KazooTestCase): mock_deserialize.side_effect = bad_deserialize try: handler.select = delayed_select - self.assertRaises(ConnectionLoss, client.create, path) + with pytest.raises(ConnectionLoss): + client.create(path) finally: handler.select = _select # the client reconnects automatically but the first attempt will # hit a deserialize failure. wait for that. deserialize_ev.wait(5) - eq_(deserialize_ev.is_set(), True) + assert deserialize_ev.is_set() # this time should succeed ev.wait(5) - eq_(ev.is_set(), True) - eq_(client.exists(path), None) + assert ev.is_set() + assert client.exists(path) is None def test_connection_close(self): - self.assertRaises(Exception, self.client.close) + with pytest.raises(Exception): + self.client.close() self.client.stop() self.client.close() @@ -245,14 +248,14 @@ class TestConnectionDrop(KazooTestCase): result = self.client.set_async(path, b'a' * 1000 * 1024) self.client._call(_CONNECTION_DROP, None) - self.assertRaises(ConnectionLoss, result.get) + with pytest.raises(ConnectionLoss): + result.get() # we have a working connection to a new node ev.wait(30) - eq_(ev.is_set(), True) + assert ev.is_set() class TestReadOnlyMode(KazooTestCase): - def setUp(self): self.setup_zookeeper(read_only=True) skip = False @@ -265,7 +268,7 @@ class TestReadOnlyMode(KazooTestCase): if ver[1] < 4: skip = True if skip: - raise SkipTest("Must use Zookeeper 3.4 or above") + pytest.skip("Must use Zookeeper 3.4 or above") def tearDown(self): self.client.stop() @@ -283,21 +286,20 @@ class TestReadOnlyMode(KazooTestCase): states.append(state) if client.client_state == KeeperState.CONNECTED_RO: ev.set() + try: self.cluster[1].stop() self.cluster[2].stop() ev.wait(6) - eq_(ev.is_set(), True) - eq_(client.client_state, KeeperState.CONNECTED_RO) + assert ev.is_set() + assert client.client_state == KeeperState.CONNECTED_RO # Test read only command - eq_(client.get_children('/'), []) + assert client.get_children('/') == [] # Test error with write command - @raises(NotReadOnlyCallError) - def testit(): + with pytest.raises(NotReadOnlyCallError): client.create('/fred') - testit() # Wait for a ping time.sleep(15) @@ -308,7 +310,6 @@ class TestReadOnlyMode(KazooTestCase): class TestUnorderedXids(KazooTestCase): - def setUp(self): super(TestUnorderedXids, self).setUp() @@ -354,16 +355,17 @@ class TestUnorderedXids(KazooTestCase): self.connection.logger.exception = log_exception ev.clear() - self.assertRaises(RuntimeError, self.client.get_children, '/') + with pytest.raises(RuntimeError): + self.client.get_children('/') ev.wait() - eq_(self.client.connected, False) - eq_(self.client.state, 'LOST') - eq_(self.client.client_state, KeeperState.CLOSED) + assert self.client.connected is False + assert self.client.state == 'LOST' + assert self.client.client_state == KeeperState.CLOSED args, exc_info = error_stack[-1] - eq_(args, ('Unhandled exception in connection loop',)) - eq_(exc_info[0], RuntimeError) + assert args == ('Unhandled exception in connection loop',) + assert exc_info[0] == RuntimeError self.client.handler.sleep_func(0.2) assert not self.connection_routine.is_alive() diff --git a/kazoo/tests/test_counter.py b/kazoo/tests/test_counter.py index 47e077e..a786673 100644 --- a/kazoo/tests/test_counter.py +++ b/kazoo/tests/test_counter.py @@ -1,65 +1,66 @@ import uuid -from nose.tools import eq_ +import pytest from kazoo.testing import KazooTestCase class KazooCounterTests(KazooTestCase): - def _makeOne(self, **kw): path = "/" + uuid.uuid4().hex return self.client.Counter(path, **kw) def test_int_counter(self): counter = self._makeOne() - eq_(counter.value, 0) + assert counter.value == 0 counter += 2 counter + 1 - eq_(counter.value, 3) + assert counter.value == 3 counter -= 3 counter - 1 - eq_(counter.value, -1) + assert counter.value == -1 def test_int_curator_counter(self): counter = self._makeOne(support_curator=True) - eq_(counter.value, 0) + assert counter.value == 0 counter += 2 counter + 1 - eq_(counter.value, 3) + assert counter.value == 3 counter -= 3 counter - 1 - eq_(counter.value, -1) + assert counter.value == -1 counter += 1 counter += 2147483647 - eq_(counter.value, 2147483647) + assert counter.value == 2147483647 counter -= 2147483647 counter -= 2147483647 - eq_(counter.value, -2147483647) + assert counter.value == -2147483647 def test_float_counter(self): counter = self._makeOne(default=0.0) - eq_(counter.value, 0.0) + assert counter.value == 0.0 counter += 2.1 - eq_(counter.value, 2.1) + assert counter.value == 2.1 counter -= 3.1 - eq_(counter.value, -1.0) + assert counter.value == -1.0 def test_errors(self): counter = self._makeOne() - self.assertRaises(TypeError, counter.__add__, 2.1) - self.assertRaises(TypeError, counter.__add__, b"a") - with self.assertRaises(TypeError): + with pytest.raises(TypeError): + counter.__add__(2.1) + with pytest.raises(TypeError): + counter.__add__(b"a") + with pytest.raises(TypeError): counter = self._makeOne(default=0.0, support_curator=True) def test_pre_post_values(self): counter = self._makeOne() - eq_(counter.value, 0) - eq_(counter.pre_value, None) - eq_(counter.post_value, None) + assert counter.value == 0 + assert counter.pre_value is None + assert counter.post_value is None counter += 2 - eq_(counter.pre_value, 0) - eq_(counter.post_value, 2) + assert counter.pre_value == 0 + assert counter.post_value == 2 counter -= 3 - eq_(counter.pre_value, 2) - eq_(counter.post_value, -1) + assert counter.pre_value == 2 + assert counter.post_value == -1 diff --git a/kazoo/tests/test_election.py b/kazoo/tests/test_election.py index cddacc8..45ef0be 100644 --- a/kazoo/tests/test_election.py +++ b/kazoo/tests/test_election.py @@ -2,7 +2,7 @@ import uuid import sys import threading -from nose.tools import eq_ +import pytest from kazoo.testing import KazooTestCase from kazoo.tests.util import wait @@ -93,11 +93,11 @@ class KazooElectionTests(KazooTestCase): wait(lambda: len(election.contenders()) == len(elections)) contenders = election.contenders() - eq_(set(contenders), set(elections.keys())) + assert set(contenders) == set(elections.keys()) # first one in list should be leader first_leader = contenders[0] - eq_(first_leader, self.leader_id) + assert first_leader == self.leader_id # tell second one to cancel election. should never get elected. elections[contenders[1]].cancel() @@ -107,18 +107,19 @@ class KazooElectionTests(KazooTestCase): with self.condition: while self.leader_id == first_leader: self.condition.wait(45) - eq_(self.leader_id, contenders[2]) + assert self.leader_id == contenders[2] self._check_thread_error() # make first contender re-enter the race threads[first_leader].join() threads[first_leader] = self._spawn_contender( - first_leader, elections[first_leader]) + first_leader, elections[first_leader] + ) # contender set should now be the current leader plus the first leader wait(lambda: len(election.contenders()) == 2) contenders = election.contenders() - eq_(set(contenders), set([self.leader_id, first_leader])) + assert set(contenders), set([self.leader_id == first_leader]) # make current leader raise an exception. first should be reelected self.raise_exception = True @@ -126,7 +127,7 @@ class KazooElectionTests(KazooTestCase): with self.condition: while self.leader_id != first_leader: self.condition.wait(45) - eq_(self.leader_id, first_leader) + assert self.leader_id == first_leader self._check_thread_error() self.exit_event.set() @@ -136,4 +137,5 @@ class KazooElectionTests(KazooTestCase): def test_bad_func(self): election = self.client.Election(self.path) - self.assertRaises(ValueError, election.run, "not a callable") + with pytest.raises(ValueError): + election.run("not a callable") diff --git a/kazoo/tests/test_eventlet_handler.py b/kazoo/tests/test_eventlet_handler.py index 5a5f60b..69af400 100644 --- a/kazoo/tests/test_eventlet_handler.py +++ b/kazoo/tests/test_eventlet_handler.py @@ -1,8 +1,7 @@ import contextlib import unittest -from nose import SkipTest -from nose.tools import raises +import pytest from kazoo.client import KazooClient from kazoo.handlers import utils @@ -15,6 +14,7 @@ try: import eventlet from eventlet.green import threading from kazoo.handlers import eventlet as eventlet_handler + EVENTLET_HANDLER_AVAILABLE = True except ImportError: EVENTLET_HANDLER_AVAILABLE = False @@ -34,15 +34,15 @@ def start_stop_one(handler=None): class TestEventletHandler(unittest.TestCase): def setUp(self): if not EVENTLET_HANDLER_AVAILABLE: - raise SkipTest('eventlet handler not available.') + pytest.skip("eventlet handler not available.") super(TestEventletHandler, self).setUp() def test_started(self): with start_stop_one() as handler: - self.assertTrue(handler.running) - self.assertNotEqual(0, len(handler._workers)) - self.assertFalse(handler.running) - self.assertEqual(0, len(handler._workers)) + assert handler.running is True + assert len(handler._workers) != 0 + assert handler.running is False + assert len(handler._workers) == 0 def test_spawn(self): captures = [] @@ -53,7 +53,7 @@ class TestEventletHandler(unittest.TestCase): with start_stop_one() as handler: handler.spawn(cb) - self.assertEqual(1, len(captures)) + assert len(captures) == 1 def test_dispatch(self): captures = [] @@ -62,9 +62,9 @@ class TestEventletHandler(unittest.TestCase): captures.append(1) with start_stop_one() as handler: - handler.dispatch_callback(kazoo_states.Callback('watch', cb, [])) + handler.dispatch_callback(kazoo_states.Callback("watch", cb, [])) - self.assertEqual(1, len(captures)) + assert len(captures) == 1 def test_async_link(self): captures = [] @@ -77,18 +77,15 @@ class TestEventletHandler(unittest.TestCase): r.rawlink(cb) r.set(2) - self.assertEqual(1, len(captures)) - self.assertEqual(2, r.get()) + assert len(captures) == 1 + assert r.get() == 2 def test_timeout_raising(self): handler = eventlet_handler.SequentialEventletHandler() - @raises(handler.timeout_exception) - def raise_it(): + with pytest.raises(handler.timeout_exception): raise handler.timeout_exception("This is a timeout") - raise_it() - def test_async_ok(self): captures = [] @@ -105,29 +102,22 @@ class TestEventletHandler(unittest.TestCase): w = handler.spawn(utils.wrap(r)(delayed)) w.join() - self.assertEqual(2, len(captures)) - self.assertEqual(1, captures[0]) - self.assertEqual(1, r.get()) + assert len(captures) == 2 + assert captures[0] == 1 + assert r.get() == 1 def test_get_with_no_block(self): handler = eventlet_handler.SequentialEventletHandler() - @raises(handler.timeout_exception) - def test_no_block(r): - r.get(block=False) - with start_stop_one(handler): r = handler.async_result() - test_no_block(r) + + with pytest.raises(handler.timeout_exception): + r.get(block=False) r.set(1) - self.assertEqual(1, r.get()) + assert r.get() == 1 def test_async_exception(self): - - @raises(IOError) - def check_exc(r): - r.get() - def broken(): raise IOError("Failed") @@ -136,14 +126,15 @@ class TestEventletHandler(unittest.TestCase): w = handler.spawn(utils.wrap(r)(broken)) w.join() - self.assertFalse(r.successful()) - check_exc(r) + assert r.successful() is False + with pytest.raises(IOError): + r.get() class TestEventletClient(test_client.TestClient): def setUp(self): if not EVENTLET_HANDLER_AVAILABLE: - raise SkipTest('eventlet handler not available.') + pytest.skip("eventlet handler not available.") super(TestEventletClient, self).setUp() @staticmethod @@ -165,7 +156,7 @@ class TestEventletClient(test_client.TestClient): class TestEventletSemaphore(test_lock.TestSemaphore): def setUp(self): if not EVENTLET_HANDLER_AVAILABLE: - raise SkipTest('eventlet handler not available.') + pytest.skip("eventlet handler not available.") super(TestEventletSemaphore, self).setUp() @staticmethod @@ -196,7 +187,7 @@ class TestEventletSemaphore(test_lock.TestSemaphore): class TestEventletLock(test_lock.KazooLockTests): def setUp(self): if not EVENTLET_HANDLER_AVAILABLE: - raise SkipTest('eventlet handler not available.') + pytest.skip("eventlet handler not available.") super(TestEventletLock, self).setUp() @staticmethod diff --git a/kazoo/tests/test_exceptions.py b/kazoo/tests/test_exceptions.py index eac65c4..ae869f4 100644 --- a/kazoo/tests/test_exceptions.py +++ b/kazoo/tests/test_exceptions.py @@ -1,5 +1,6 @@ from unittest import TestCase +import pytest class ExceptionsTestCase(TestCase): @@ -9,17 +10,18 @@ class ExceptionsTestCase(TestCase): def test_backwards_alias(self): module = self._get() - self.assertTrue(getattr(module, 'NoNodeException')) - self.assertTrue(module.NoNodeException, module.NoNodeError) + assert hasattr(module, 'NoNodeException') + assert module.NoNodeException is module.NoNodeError def test_exceptions_code(self): module = self._get() exc_8 = module.EXCEPTIONS[-8] - self.assertTrue(isinstance(exc_8(), module.BadArgumentsError)) + assert isinstance(exc_8(), module.BadArgumentsError) def test_invalid_code(self): module = self._get() - self.assertRaises(RuntimeError, module.EXCEPTIONS.__getitem__, 666) + with pytest.raises(RuntimeError): + module.EXCEPTIONS.__getitem__(666) def test_exceptions_construction(self): module = self._get() diff --git a/kazoo/tests/test_gevent_handler.py b/kazoo/tests/test_gevent_handler.py index 77ed8ed..9bf1029 100644 --- a/kazoo/tests/test_gevent_handler.py +++ b/kazoo/tests/test_gevent_handler.py @@ -1,8 +1,6 @@ import unittest -from nose import SkipTest -from nose.tools import eq_ -from nose.tools import raises +import pytest from kazoo.client import KazooClient from kazoo.exceptions import NoNodeError @@ -12,23 +10,25 @@ from kazoo.tests import test_client class TestGeventHandler(unittest.TestCase): - def setUp(self): try: import gevent # NOQA except ImportError: - raise SkipTest('gevent not available.') + pytest.skip("gevent not available.") def _makeOne(self, *args): from kazoo.handlers.gevent import SequentialGeventHandler + return SequentialGeventHandler(*args) def _getAsync(self, *args): from kazoo.handlers.gevent import AsyncResult + return AsyncResult def _getEvent(self): from gevent.event import Event + return Event def test_proper_threading(self): @@ -45,10 +45,8 @@ class TestGeventHandler(unittest.TestCase): def test_exception_raising(self): h = self._makeOne() - @raises(h.timeout_exception) - def testit(): + with pytest.raises(h.timeout_exception): raise h.timeout_exception("This is a timeout") - testit() def test_exception_in_queue(self): h = self._makeOne() @@ -57,14 +55,15 @@ class TestGeventHandler(unittest.TestCase): def func(): ev.set() - raise ValueError('bang') + raise ValueError("bang") - call1 = Callback('completion', func, ()) + call1 = Callback("completion", func, ()) h.dispatch_callback(call1) ev.wait() def test_queue_empty_exception(self): from gevent.queue import Empty + h = self._makeOne() h.start() ev = self._getEvent()() @@ -73,38 +72,39 @@ class TestGeventHandler(unittest.TestCase): ev.set() raise Empty() - call1 = Callback('completion', func, ()) + call1 = Callback("completion", func, ()) h.dispatch_callback(call1) ev.wait() class TestBasicGeventClient(KazooTestCase): - def setUp(self): try: import gevent # NOQA except ImportError: - raise SkipTest('gevent not available.') + pytest.skip("gevent not available.") KazooTestCase.setUp(self) def _makeOne(self, *args): from kazoo.handlers.gevent import SequentialGeventHandler + return SequentialGeventHandler(*args) def _getEvent(self): from gevent.event import Event + return Event def test_start(self): client = self._get_client(handler=self._makeOne()) client.start() - self.assertEqual(client.state, 'CONNECTED') + assert client.state == "CONNECTED" client.stop() def test_start_stop_double(self): client = self._get_client(handler=self._makeOne()) client.start() - self.assertEqual(client.state, 'CONNECTED') + assert client.state == "CONNECTED" client.handler.start() client.handler.stop() client.stop() @@ -112,47 +112,48 @@ class TestBasicGeventClient(KazooTestCase): def test_basic_commands(self): client = self._get_client(handler=self._makeOne()) client.start() - self.assertEqual(client.state, 'CONNECTED') - client.create('/anode', 'fred') - eq_(client.get('/anode')[0], 'fred') - eq_(client.delete('/anode'), True) - eq_(client.exists('/anode'), None) + assert client.state == "CONNECTED" + client.create("/anode", b"fred") + assert client.get("/anode")[0] == b"fred" + assert client.delete("/anode") + assert client.exists("/anode") is None client.stop() def test_failures(self): client = self._get_client(handler=self._makeOne()) client.start() - self.assertRaises(NoNodeError, client.get, '/none') + with pytest.raises(NoNodeError): + client.get("/none") client.stop() def test_data_watcher(self): client = self._get_client(handler=self._makeOne()) client.start() - client.ensure_path('/some/node') + client.ensure_path("/some/node") ev = self._getEvent()() - @client.DataWatch('/some/node') + @client.DataWatch("/some/node") def changed(d, stat): ev.set() ev.wait() ev.clear() - client.set('/some/node', 'newvalue') + client.set("/some/node", b"newvalue") ev.wait() client.stop() class TestGeventClient(test_client.TestClient): - def setUp(self): try: import gevent # NOQA except ImportError: - raise SkipTest('gevent not available.') + pytest.skip("gevent not available.") KazooTestCase.setUp(self) def _makeOne(self, *args): from kazoo.handlers.gevent import SequentialGeventHandler + return SequentialGeventHandler(*args) def _get_client(self, **kwargs): diff --git a/kazoo/tests/test_hosts.py b/kazoo/tests/test_hosts.py index cce623c..0ad83cf 100644 --- a/kazoo/tests/test_hosts.py +++ b/kazoo/tests/test_hosts.py @@ -1,4 +1,5 @@ from unittest import TestCase + from kazoo.hosts import collect_hosts @@ -7,46 +8,46 @@ class HostsTestCase(TestCase): def test_ipv4(self): hosts, chroot = collect_hosts('127.0.0.1:2181, 192.168.1.2:2181, \ 132.254.111.10:2181') - self.assertEquals([('127.0.0.1', 2181), - ('192.168.1.2', 2181), - ('132.254.111.10', 2181)], hosts) - self.assertEquals(None, chroot) + assert hosts == [('127.0.0.1', 2181), + ('192.168.1.2', 2181), + ('132.254.111.10', 2181)] + assert chroot is None hosts, chroot = collect_hosts(['127.0.0.1:2181', '192.168.1.2:2181', '132.254.111.10:2181']) - self.assertEquals([('127.0.0.1', 2181), - ('192.168.1.2', 2181), - ('132.254.111.10', 2181)], hosts) - self.assertEquals(None, chroot) + assert hosts == [('127.0.0.1', 2181), + ('192.168.1.2', 2181), + ('132.254.111.10', 2181)] + assert chroot is None def test_ipv6(self): hosts, chroot = collect_hosts('[fe80::200:5aee:feaa:20a2]:2181') - self.assertEquals([('fe80::200:5aee:feaa:20a2', 2181)], hosts) - self.assertEquals(None, chroot) + assert hosts == [('fe80::200:5aee:feaa:20a2', 2181)] + assert chroot is None hosts, chroot = collect_hosts(['[fe80::200:5aee:feaa:20a2]:2181']) - self.assertEquals([('fe80::200:5aee:feaa:20a2', 2181)], hosts) - self.assertEquals(None, chroot) + assert hosts == [('fe80::200:5aee:feaa:20a2', 2181)] + assert chroot is None def test_hosts_list(self): hosts, chroot = collect_hosts('zk01:2181, zk02:2181, zk03:2181') expected1 = [('zk01', 2181), ('zk02', 2181), ('zk03', 2181)] - self.assertEquals(expected1, hosts) - self.assertEquals(None, chroot) + assert hosts == expected1 + assert chroot is None hosts, chroot = collect_hosts(['zk01:2181', 'zk02:2181', 'zk03:2181']) - self.assertEquals(expected1, hosts) - self.assertEquals(None, chroot) + assert hosts == expected1 + assert chroot is None expected2 = '/test' hosts, chroot = collect_hosts('zk01:2181, zk02:2181, zk03:2181/test') - self.assertEquals(expected1, hosts) - self.assertEquals(expected2, chroot) + assert hosts == expected1 + assert chroot == expected2 hosts, chroot = collect_hosts(['zk01:2181', 'zk02:2181', 'zk03:2181', '/test']) - self.assertEquals(expected1, hosts) - self.assertEquals(expected2, chroot) + assert hosts == expected1 + assert chroot == expected2 diff --git a/kazoo/tests/test_interrupt.py b/kazoo/tests/test_interrupt.py index e131755..4f4a997 100644 --- a/kazoo/tests/test_interrupt.py +++ b/kazoo/tests/test_interrupt.py @@ -1,7 +1,8 @@ import os -from nose import SkipTest from sys import platform +import pytest + from kazoo.testing import KazooTestCase @@ -12,8 +13,9 @@ class KazooInterruptTests(KazooTestCase): can't control what all signals our connection thread will get ''' if 'linux' not in platform: - raise SkipTest('Unable to reproduce error case on' - ' non-linux platforms') + pytest.skip( + 'Unable to reproduce error case on non-linux platforms' + ) path = 'interrupt_test' value = b"1" diff --git a/kazoo/tests/test_lease.py b/kazoo/tests/test_lease.py index 74990c4..5e7a6f2 100644 --- a/kazoo/tests/test_lease.py +++ b/kazoo/tests/test_lease.py @@ -45,92 +45,92 @@ class NonBlockingLeaseTests(KazooLeaseTests): lease = self.client.NonBlockingLease(self.path, datetime.timedelta(seconds=3), utcnow=self.clock) - self.assertTrue(lease) - self.assertTrue(lease.obtained) + assert lease + assert lease.obtained is True self.clock.forward(2) renewed_lease = self.client.NonBlockingLease( self.path, datetime.timedelta(seconds=3), utcnow=self.clock) - self.assertTrue(renewed_lease) + assert renewed_lease def test_busy(self): lease = NonBlockingLease(self.client, self.path, datetime.timedelta(seconds=3), utcnow=self.clock) - self.assertTrue(lease) + assert lease self.clock.forward(2) foreigner_lease = NonBlockingLease( self.client2, self.path, datetime.timedelta(seconds=3), identifier="some.other.host", utcnow=self.clock) - self.assertFalse(foreigner_lease) - self.assertFalse(foreigner_lease.obtained) + assert not foreigner_lease + assert foreigner_lease.obtained is False def test_overtake(self): lease = NonBlockingLease(self.client, self.path, datetime.timedelta(seconds=3), utcnow=self.clock) - self.assertTrue(lease) + assert lease self.clock.forward(4) foreigner_lease = NonBlockingLease( self.client2, self.path, datetime.timedelta(seconds=3), identifier="some.other.host", utcnow=self.clock) - self.assertTrue(foreigner_lease) + assert foreigner_lease def test_renew_no_overtake(self): lease = self.client.NonBlockingLease(self.path, datetime.timedelta(seconds=3), utcnow=self.clock) - self.assertTrue(lease) - self.assertTrue(lease.obtained) + assert lease + assert lease.obtained is True self.clock.forward(2) renewed_lease = self.client.NonBlockingLease( self.path, datetime.timedelta(seconds=3), utcnow=self.clock) - self.assertTrue(renewed_lease) + assert renewed_lease self.clock.forward(2) foreigner_lease = NonBlockingLease( self.client2, self.path, datetime.timedelta(seconds=3), identifier="some.other.host", utcnow=self.clock) - self.assertFalse(foreigner_lease) + assert not foreigner_lease def test_overtaker_renews(self): lease = NonBlockingLease(self.client, self.path, datetime.timedelta(seconds=3), utcnow=self.clock) - self.assertTrue(lease) + assert lease self.clock.forward(4) foreigner_lease = NonBlockingLease( self.client2, self.path, datetime.timedelta(seconds=3), identifier="some.other.host", utcnow=self.clock) - self.assertTrue(foreigner_lease) + assert foreigner_lease self.clock.forward(2) foreigner_renew = NonBlockingLease( self.client2, self.path, datetime.timedelta(seconds=3), identifier="some.other.host", utcnow=self.clock) - self.assertTrue(foreigner_renew) + assert foreigner_renew def test_overtake_refuse_first(self): lease = NonBlockingLease(self.client, self.path, datetime.timedelta(seconds=3), utcnow=self.clock) - self.assertTrue(lease) + assert lease self.clock.forward(4) foreigner_lease = NonBlockingLease( self.client2, self.path, datetime.timedelta(seconds=3), identifier="some.other.host", utcnow=self.clock) - self.assertTrue(foreigner_lease) + assert foreigner_lease self.clock.forward(2) first_again_lease = NonBlockingLease( self.client, self.path, datetime.timedelta(seconds=3), utcnow=self.clock) - self.assertFalse(first_again_lease) + assert not first_again_lease def test_old_version(self): # Skip to a future version @@ -138,7 +138,7 @@ class NonBlockingLeaseTests(KazooLeaseTests): lease = NonBlockingLease(self.client, self.path, datetime.timedelta(seconds=3), utcnow=self.clock) - self.assertTrue(lease) + assert lease # Then back to today. NonBlockingLease._version -= 1 @@ -147,7 +147,7 @@ class NonBlockingLeaseTests(KazooLeaseTests): self.client2, self.path, datetime.timedelta(seconds=3), identifier="some.other.host", utcnow=self.clock) # Since a newer version wrote the lease file, the lease is not taken. - self.assertFalse(foreigner_lease) + assert not foreigner_lease class MultiNonBlockingLeaseTest(KazooLeaseTests): @@ -155,79 +155,79 @@ class MultiNonBlockingLeaseTest(KazooLeaseTests): ls = self.client.MultiNonBlockingLease(1, self.path, datetime.timedelta(seconds=4), utcnow=self.clock) - self.assertTrue(ls) + assert ls self.clock.forward(2) ls2 = MultiNonBlockingLease(self.client, 1, self.path, datetime.timedelta(seconds=4), utcnow=self.clock) - self.assertTrue(ls2) + assert ls2 def test_1_reject(self): ls = MultiNonBlockingLease(self.client, 1, self.path, datetime.timedelta(seconds=4), utcnow=self.clock) - self.assertTrue(ls) + assert ls self.clock.forward(2) ls2 = MultiNonBlockingLease(self.client2, 1, self.path, datetime.timedelta(seconds=4), identifier="some.other.host", utcnow=self.clock) - self.assertFalse(ls2) + assert not ls2 def test_2_renew(self): ls = MultiNonBlockingLease(self.client, 2, self.path, datetime.timedelta(seconds=7), utcnow=self.clock) - self.assertTrue(ls) + assert ls self.clock.forward(2) ls2 = MultiNonBlockingLease(self.client2, 2, self.path, datetime.timedelta(seconds=7), identifier="host2", utcnow=self.clock) - self.assertTrue(ls2) + assert ls2 self.clock.forward(2) ls3 = MultiNonBlockingLease(self.client, 2, self.path, datetime.timedelta(seconds=7), utcnow=self.clock) - self.assertTrue(ls3) + assert ls3 self.clock.forward(2) ls4 = MultiNonBlockingLease(self.client2, 2, self.path, datetime.timedelta(seconds=7), identifier="host2", utcnow=self.clock) - self.assertTrue(ls4) + assert ls4 def test_2_reject(self): ls = MultiNonBlockingLease(self.client, 2, self.path, datetime.timedelta(seconds=7), utcnow=self.clock) - self.assertTrue(ls) + assert ls self.clock.forward(2) ls2 = MultiNonBlockingLease(self.client2, 2, self.path, datetime.timedelta(seconds=7), identifier="host2", utcnow=self.clock) - self.assertTrue(ls2) + assert ls2 self.clock.forward(2) ls3 = MultiNonBlockingLease(self.client3, 2, self.path, datetime.timedelta(seconds=7), identifier="host3", utcnow=self.clock) - self.assertFalse(ls3) + assert not ls3 def test_2_handover(self): ls = MultiNonBlockingLease(self.client, 2, self.path, datetime.timedelta(seconds=4), utcnow=self.clock) - self.assertTrue(ls) + assert ls self.clock.forward(2) ls2 = MultiNonBlockingLease(self.client2, 2, self.path, datetime.timedelta(seconds=4), identifier="host2", utcnow=self.clock) - self.assertTrue(ls2) + assert ls2 self.clock.forward(3) ls3 = MultiNonBlockingLease(self.client3, 2, self.path, datetime.timedelta(seconds=4), identifier="host3", utcnow=self.clock) - self.assertTrue(ls3) + assert ls3 self.clock.forward(2) ls4 = MultiNonBlockingLease(self.client, 2, self.path, datetime.timedelta(seconds=4), utcnow=self.clock) - self.assertTrue(ls4) + assert ls4 diff --git a/kazoo/tests/test_lock.py b/kazoo/tests/test_lock.py index ae907ed..ee0ff3d 100644 --- a/kazoo/tests/test_lock.py +++ b/kazoo/tests/test_lock.py @@ -2,7 +2,7 @@ import collections import threading import uuid -from nose.tools import eq_, ok_ +import pytest from kazoo.exceptions import CancelledError from kazoo.exceptions import LockTimeout @@ -77,14 +77,14 @@ class KazooLockTests(KazooTestCase): try: with lock: with self.condition: - eq_(self.active_thread, None) + assert self.active_thread is None self.active_thread = name self.condition.notify_all() event.wait() with self.condition: - eq_(self.active_thread, name) + assert self.active_thread == name self.active_thread = None self.condition.notify_all() self.released.set() @@ -107,7 +107,7 @@ class KazooLockTests(KazooTestCase): # wait for any contender to show up on the lock wait = self.make_wait() wait(anotherlock.contenders) - eq_(anotherlock.contenders(), [lock_name]) + assert anotherlock.contenders() == [lock_name] with self.condition: while self.active_thread != lock_name: @@ -148,7 +148,7 @@ class KazooLockTests(KazooTestCase): wait(lambda: len(lock.contenders()) == 6) contenders = lock.contenders() - eq_(contenders[0], "test") + assert contenders[0] == "test" contenders = contenders[1:] remaining = list(contenders) @@ -161,9 +161,9 @@ class KazooLockTests(KazooTestCase): with self.condition: while not self.active_thread: self.condition.wait() - eq_(self.active_thread, contender) + assert self.active_thread == contender - eq_(lock.contenders(), remaining) + assert lock.contenders() == remaining remaining = remaining[1:] event.set() @@ -188,7 +188,7 @@ class KazooLockTests(KazooTestCase): # wait for the contender to line up on the lock wait = self.make_wait() wait(lambda: len(lock.contenders()) == 2) - eq_(lock.contenders(), ['test', 'contender']) + assert lock.contenders() == ['test', 'contender'] self.expire_session(self.make_event) @@ -197,7 +197,7 @@ class KazooLockTests(KazooTestCase): with self.condition: while not self.active_thread: self.condition.wait() - eq_(self.active_thread, 'contender') + assert self.active_thread == 'contender' event.set() thread.join() @@ -218,8 +218,8 @@ class KazooLockTests(KazooTestCase): if not self.active_thread: self.condition.wait(5) - ok_(not lock1.acquire(blocking=False)) - eq_(lock.contenders(), [lock_name]) # just one - itself + assert not lock1.acquire(blocking=False) + assert lock.contenders() == [lock_name] # just one - itself event.set() thread.join() @@ -235,8 +235,8 @@ class KazooLockTests(KazooTestCase): with self.condition: if not self.active_thread: self.condition.wait(5) - eq_(self.active_thread, "one") - eq_(lock1.contenders(), ["one"]) + assert self.active_thread == "one" + assert lock1.contenders() == ["one"] event1.set() thread1.join() @@ -251,7 +251,7 @@ class KazooLockTests(KazooTestCase): with self.condition: if not self.active_thread: self.condition.wait(5) - eq_(self.active_thread, "one") + assert self.active_thread == "one" client2 = self._get_client() client2.start() @@ -264,7 +264,7 @@ class KazooLockTests(KazooTestCase): # this one should block in acquire. check that it is a contender wait = self.make_wait() wait(lambda: len(lock2.contenders()) > 1) - eq_(lock2.contenders(), ["one", "two"]) + assert lock2.contenders() == ["one", "two"] lock2.cancel() with self.condition: @@ -272,7 +272,7 @@ class KazooLockTests(KazooTestCase): self.condition.wait() assert "two" in self.cancelled_threads - eq_(lock2.contenders(), ["one"]) + assert lock2.contenders() == ["one"] thread2.join() event1.set() @@ -282,19 +282,19 @@ class KazooLockTests(KazooTestCase): def test_lock_no_double_calls(self): lock1 = self.client.Lock(self.lockpath, "one") lock1.acquire() - self.assertTrue(lock1.is_acquired) - self.assertFalse(lock1.acquire(timeout=0.5)) - self.assertTrue(lock1.is_acquired) + assert lock1.is_acquired is True + assert lock1.acquire(timeout=0.5) is False + assert lock1.is_acquired is True lock1.release() - self.assertFalse(lock1.is_acquired) + assert lock1.is_acquired is False def test_lock_same_thread_no_block(self): lock = self.client.Lock(self.lockpath, "one") gotten = lock.acquire(blocking=False) - self.assertTrue(gotten) - self.assertTrue(lock.is_acquired) + assert gotten is True + assert lock.is_acquired is True gotten = lock.acquire(blocking=False) - self.assertFalse(gotten) + assert gotten is False def test_lock_many_threads_no_block(self): lock = self.client.Lock(self.lockpath, "one") @@ -313,7 +313,7 @@ class KazooLockTests(KazooTestCase): t = threads.pop() t.join() - self.assertEqual(1, sum(list(attempts))) + assert sum(list(attempts)) == 1 def test_lock_many_threads(self): sleep_func = self.client.handler.sleep_func @@ -346,8 +346,8 @@ class KazooLockTests(KazooTestCase): t = threads.pop() t.join() - self.assertEqual(self.thread_count, len(acquires)) - self.assertEqual([1] * self.thread_count, list(differences)) + assert len(acquires) == self.thread_count + assert list(differences) == [1] * self.thread_count def test_lock_reacquire(self): lock = self.client.Lock(self.lockpath, "one") @@ -393,7 +393,7 @@ class KazooLockTests(KazooTestCase): client2 = self._get_client() client2.start() started.wait(5) - self.assertTrue(started.isSet()) + assert started.isSet() is True lock2 = client2.Lock(self.lockpath, "two") try: lock2.acquire(timeout=timeout) @@ -413,37 +413,37 @@ class KazooLockTests(KazooTestCase): # Test that we can obtain a read lock lock = self.client.ReadLock(self.lockpath, "reader one") gotten = lock.acquire(blocking=False) - self.assertTrue(gotten) - self.assertTrue(lock.is_acquired) + assert gotten is True + assert lock.is_acquired is True # and that it's still not reentrant. gotten = lock.acquire(blocking=False) - self.assertFalse(gotten) + assert gotten is False # Test that a second client we can share the same read lock client2 = self._get_client() client2.start() lock2 = client2.ReadLock(self.lockpath, "reader two") gotten = lock2.acquire(blocking=False) - self.assertTrue(gotten) - self.assertTrue(lock2.is_acquired) + assert gotten is True + assert lock2.is_acquired is True gotten = lock2.acquire(blocking=False) - self.assertFalse(gotten) + assert gotten is False # Test that a writer is unable to share it client3 = self._get_client() client3.start() lock3 = client3.WriteLock(self.lockpath, "writer") gotten = lock3.acquire(blocking=False) - self.assertFalse(gotten) + assert gotten is False def test_write_lock(self): # Test that we can obtain a write lock lock = self.client.WriteLock(self.lockpath, "writer") gotten = lock.acquire(blocking=False) - self.assertTrue(gotten) - self.assertTrue(lock.is_acquired) + assert gotten is True + assert lock.is_acquired is True gotten = lock.acquire(blocking=False) - self.assertFalse(gotten) + assert gotten is False # Test that we are unable to obtain a read lock while the # write lock is held. @@ -451,11 +451,10 @@ class KazooLockTests(KazooTestCase): client2.start() lock2 = client2.ReadLock(self.lockpath, "reader") gotten = lock2.acquire(blocking=False) - self.assertFalse(gotten) + assert gotten is False class TestSemaphore(KazooTestCase): - def __init__(self, *args, **kw): super(TestSemaphore, self).__init__(*args, **kw) self.threads_made = [] @@ -510,11 +509,11 @@ class TestSemaphore(KazooTestCase): thread.start() started.wait(10) - self.assertFalse(event.is_set()) + assert event.is_set() is False sem1.release() event.wait(10) - self.assert_(event.is_set()) + assert event.is_set() is True thread.join() def test_non_blocking(self): @@ -527,12 +526,12 @@ class TestSemaphore(KazooTestCase): sem1.acquire() sem2.acquire() - ok_(not sem3.acquire(blocking=False)) - eq_(set(sem1.lease_holders()), set(['sem1', 'sem2'])) + assert not sem3.acquire(blocking=False) + assert set(sem1.lease_holders()) == set(['sem1', 'sem2']) sem2.release() # the next line isn't required, but avoids timing issues in tests sem3.acquire() - eq_(set(sem1.lease_holders()), set(['sem1', 'sem3'])) + assert set(sem1.lease_holders()) == set(['sem1', 'sem3']) sem1.release() sem3.release() @@ -562,7 +561,7 @@ class TestSemaphore(KazooTestCase): started.wait() sem1 = self.client.Semaphore(self.lockpath) holders = sem1.lease_holders() - eq_(holders, ['fred']) + assert holders == ['fred'] event.set() thread.join() @@ -584,11 +583,11 @@ class TestSemaphore(KazooTestCase): thread = self.make_thread(target=sema_one, args=()) thread.start() started.wait() - eq_(sem1.lease_holders(), ['fred']) - eq_(event.is_set(), False) + assert sem1.lease_holders() == ['fred'] + assert not event.is_set() sem2.cancel() event.wait() - eq_(event.is_set(), True) + assert event.is_set() thread.join() def test_multiple_acquire_and_release(self): @@ -596,8 +595,8 @@ class TestSemaphore(KazooTestCase): sem1.acquire() sem1.acquire() - eq_(True, sem1.release()) - eq_(False, sem1.release()) + assert sem1.release() + assert not sem1.release() def test_handle_session_loss(self): expire_semaphore = self.client.Semaphore(self.lockpath, 'fred', @@ -622,7 +621,7 @@ class TestSemaphore(KazooTestCase): thread1.start() started.wait() - eq_(lh_semaphore.lease_holders(), ['george']) + assert lh_semaphore.lease_holders() == ['george'] # Fired in a separate thread to make sure we can see the effect expired = self.make_event() @@ -640,7 +639,7 @@ class TestSemaphore(KazooTestCase): client.stop() event.wait(15) - eq_(expire_semaphore.lease_holders(), ['fred']) + assert expire_semaphore.lease_holders() == ['fred'] event2.set() for t in (thread1, thread2): @@ -651,7 +650,8 @@ class TestSemaphore(KazooTestCase): sem2 = self.client.Semaphore(self.lockpath, max_leases=2) sem1.acquire() - self.assertRaises(ValueError, sem2.acquire) + with pytest.raises(ValueError): + sem2.acquire() def test_inconsistent_max_leases_other_data(self): sem1 = self.client.Semaphore(self.lockpath, max_leases=1) @@ -662,7 +662,7 @@ class TestSemaphore(KazooTestCase): sem1.acquire() # sem2 thinks it's ok to have two lease holders - ok_(sem2.acquire(blocking=False)) + assert sem2.acquire(blocking=False) def test_reacquire(self): lock = self.client.Semaphore(self.lockpath) @@ -673,11 +673,11 @@ class TestSemaphore(KazooTestCase): def test_acquire_after_cancelled(self): lock = self.client.Semaphore(self.lockpath) - self.assertTrue(lock.acquire()) - self.assertTrue(lock.release()) + assert lock.acquire() is True + assert lock.release() is True lock.cancel() - self.assertTrue(lock.cancelled) - self.assertTrue(lock.acquire()) + assert lock.cancelled is True + assert lock.acquire() is True def test_timeout(self): timeout = 3 @@ -704,7 +704,7 @@ class TestSemaphore(KazooTestCase): client2 = self._get_client() client2.start() started.wait(5) - self.assertTrue(started.isSet()) + assert started.isSet() is True sem2 = client2.Semaphore(self.lockpath, "two") try: sem2.acquire(timeout=timeout) diff --git a/kazoo/tests/test_partitioner.py b/kazoo/tests/test_partitioner.py index 0aa5049..aebc766 100644 --- a/kazoo/tests/test_partitioner.py +++ b/kazoo/tests/test_partitioner.py @@ -3,14 +3,13 @@ import threading import time import mock -from nose.tools import eq_ from kazoo.exceptions import LockTimeout from kazoo.testing import KazooTestCase from kazoo.recipe.partitioner import PartitionState -class SlowLockMock(): +class SlowLockMock: """Emulates a slow ZooKeeper lock.""" default_delay_time = 3 @@ -68,7 +67,7 @@ class KazooPartitionerTests(KazooTestCase): self.__partitioners[0].finish() self.__wait() - eq_(self.__partitioners[1].release, True) + assert self.__partitioners[1].release self.__partitioners[1].finish() def test_party_expansion(self): @@ -89,7 +88,7 @@ class KazooPartitionerTests(KazooTestCase): self.__assert_state(PartitionState.RELEASE, partitioners=self.__partitioners[:-1]) for partitioner in self.__partitioners[-1]: - eq_(partitioner.state_change_event.is_set(), True) + assert partitioner.state_change_event.is_set() self.__release(self.__partitioners[:-1]) self.__wait_for_acquire() @@ -110,11 +109,11 @@ class KazooPartitionerTests(KazooTestCase): def test_party_session_failure(self): partitioner = self.__create_partitioner(size=3) self.__wait_for_acquire() - eq_(partitioner.state, PartitionState.ACQUIRED) + assert partitioner.state == PartitionState.ACQUIRED # simulate session failure partitioner._fail_out() partitioner.release_set() - self.assertTrue(partitioner.failed) + assert partitioner.failed is True def test_connection_loss(self): self.__create_partitioner(identifier="0", size=3) @@ -229,13 +228,13 @@ class KazooPartitionerTests(KazooTestCase): partitioners = self.__partitioners for partitioner in partitioners: - eq_(partitioner.state, state) + assert partitioner.state == state def __assert_partitions(self, *partitions): - eq_(len(partitions), len(self.__partitioners)) + assert len(partitions) == len(self.__partitioners) for partitioner, own_partitions in zip(self.__partitioners, partitions): - eq_(list(partitioner), own_partitions) + assert list(partitioner) == own_partitions def __wait(self): time.sleep(0.1) diff --git a/kazoo/tests/test_party.py b/kazoo/tests/test_party.py index d44eec7..2089d54 100644 --- a/kazoo/tests/test_party.py +++ b/kazoo/tests/test_party.py @@ -1,7 +1,5 @@ import uuid -from nose.tools import eq_ - from kazoo.testing import KazooTestCase @@ -16,42 +14,42 @@ class KazooPartyTests(KazooTestCase): one_party = parties[0] - eq_(list(one_party), []) - eq_(len(one_party), 0) + assert list(one_party) == [] + assert len(one_party) == 0 participants = set() for party in parties: party.join() participants.add(party.data.decode('utf-8')) - eq_(set(party), participants) - eq_(len(party), len(participants)) + assert set(party) == participants + assert len(party) == len(participants) for party in parties: party.leave() participants.remove(party.data.decode('utf-8')) - eq_(set(party), participants) - eq_(len(party), len(participants)) + assert set(party) == participants + assert len(party) == len(participants) def test_party_reuse_node(self): party = self.client.Party(self.path, "p1") self.client.ensure_path(self.path) self.client.create(party.create_path) party.join() - self.assertTrue(party.participating) + assert party.participating is True party.leave() - self.assertFalse(party.participating) - self.assertEqual(len(party), 0) + assert party.participating is False + assert len(party) == 0 def test_party_vanishing_node(self): party = self.client.Party(self.path, "p1") party.join() - self.assertTrue(party.participating) + assert party.participating is True self.client.delete(party.create_path) party.leave() - self.assertFalse(party.participating) - self.assertEqual(len(party), 0) + assert party.participating is False + assert len(party) == 0 class KazooShallowPartyTests(KazooTestCase): @@ -65,20 +63,20 @@ class KazooShallowPartyTests(KazooTestCase): one_party = parties[0] - eq_(list(one_party), []) - eq_(len(one_party), 0) + assert list(one_party) == [] + assert len(one_party) == 0 participants = set() for party in parties: party.join() participants.add(party.data.decode('utf-8')) - eq_(set(party), participants) - eq_(len(party), len(participants)) + assert set(party) == participants + assert len(party) == len(participants) for party in parties: party.leave() participants.remove(party.data.decode('utf-8')) - eq_(set(party), participants) - eq_(len(party), len(participants)) + assert set(party) == participants + assert len(party) == len(participants) diff --git a/kazoo/tests/test_paths.py b/kazoo/tests/test_paths.py index 4f7fe94..730a189 100644 --- a/kazoo/tests/test_paths.py +++ b/kazoo/tests/test_paths.py @@ -1,6 +1,8 @@ import sys from unittest import TestCase +import pytest + from kazoo.protocol import paths @@ -15,87 +17,89 @@ else: # pragma: nocover class NormPathTestCase(TestCase): def test_normpath(self): - self.assertEqual(paths.normpath('/a/b'), '/a/b') + assert paths.normpath('/a/b') == '/a/b' def test_normpath_empty(self): - self.assertEqual(paths.normpath(''), '') + assert paths.normpath('') == '' def test_normpath_unicode(self): - self.assertEqual(paths.normpath(u('/\xe4/b')), u('/\xe4/b')) + assert paths.normpath(u('/\xe4/b')) == u('/\xe4/b') def test_normpath_dots(self): - self.assertEqual(paths.normpath('/a./b../c'), '/a./b../c') + assert paths.normpath('/a./b../c') == '/a./b../c' def test_normpath_slash(self): - self.assertEqual(paths.normpath('/'), '/') + assert paths.normpath('/') == '/' def test_normpath_multiple_slashes(self): - self.assertEqual(paths.normpath('//'), '/') - self.assertEqual(paths.normpath('//a/b'), '/a/b') - self.assertEqual(paths.normpath('/a//b//'), '/a/b') - self.assertEqual(paths.normpath('//a////b///c/'), '/a/b/c') + assert paths.normpath('//') == '/' + assert paths.normpath('//a/b') == '/a/b' + assert paths.normpath('/a//b//') == '/a/b' + assert paths.normpath('//a////b///c/') == '/a/b/c' def test_normpath_relative(self): - self.assertRaises(ValueError, paths.normpath, './a/b') - self.assertRaises(ValueError, paths.normpath, '/a/../b') + with pytest.raises(ValueError): + paths.normpath('./a/b') + with pytest.raises(ValueError): + paths.normpath('/a/../b') def test_normpath_trailing(self): - self.assertEqual(paths.normpath('/', trailing=True), '/') + assert paths.normpath('/', trailing=True) == '/' class JoinTestCase(TestCase): def test_join(self): - self.assertEqual(paths.join('/a'), '/a') - self.assertEqual(paths.join('/a', 'b/'), '/a/b/') - self.assertEqual(paths.join('/a', 'b', 'c'), '/a/b/c') + assert paths.join('/a') == '/a' + assert paths.join('/a', 'b/') == '/a/b/' + assert paths.join('/a', 'b', 'c') == '/a/b/c' def test_join_empty(self): - self.assertEqual(paths.join(''), '') - self.assertEqual(paths.join('', 'a', 'b'), 'a/b') - self.assertEqual(paths.join('/a', '', 'b/', 'c'), '/a/b/c') + assert paths.join('') == '' + assert paths.join('', 'a', 'b') == 'a/b' + assert paths.join('/a', '', 'b/', 'c') == '/a/b/c' def test_join_absolute(self): - self.assertEqual(paths.join('/a/b', '/c'), '/c') + assert paths.join('/a/b', '/c') == '/c' class IsAbsTestCase(TestCase): def test_isabs(self): - self.assertTrue(paths.isabs('/')) - self.assertTrue(paths.isabs('/a')) - self.assertTrue(paths.isabs('/a//b/c')) - self.assertTrue(paths.isabs('//a/b')) + assert paths.isabs('/') is True + assert paths.isabs('/a') is True + assert paths.isabs('/a//b/c') is True + assert paths.isabs('//a/b') is True def test_isabs_false(self): - self.assertFalse(paths.isabs('')) - self.assertFalse(paths.isabs('a/')) - self.assertFalse(paths.isabs('a/../')) + assert paths.isabs('') is False + assert paths.isabs('a/') is False + assert paths.isabs('a/../') is False class BaseNameTestCase(TestCase): def test_basename(self): - self.assertEquals(paths.basename(''), '') - self.assertEquals(paths.basename('/'), '') - self.assertEquals(paths.basename('//a'), 'a') - self.assertEquals(paths.basename('//a/'), '') - self.assertEquals(paths.basename('/a/b.//c..'), 'c..') + assert paths.basename('') == '' + assert paths.basename('/') == '' + assert paths.basename('//a') == 'a' + assert paths.basename('//a/') == '' + assert paths.basename('/a/b.//c..') == 'c..' class PrefixRootTestCase(TestCase): def test_prefix_root(self): - self.assertEquals(paths._prefix_root('/a/', 'b/c'), '/a/b/c') - self.assertEquals(paths._prefix_root('/a/b', 'c/d'), '/a/b/c/d') - self.assertEquals(paths._prefix_root('/a', '/b/c'), '/a/b/c') - self.assertEquals(paths._prefix_root('/a', '//b/c.'), '/a/b/c.') + assert paths._prefix_root('/a/', 'b/c') == '/a/b/c' + assert paths._prefix_root('/a/b', 'c/d') == '/a/b/c/d' + assert paths._prefix_root('/a', '/b/c') == '/a/b/c' + assert paths._prefix_root('/a', '//b/c.') == '/a/b/c.' class NormRootTestCase(TestCase): def test_norm_root(self): - self.assertEquals(paths._norm_root(''), '/') - self.assertEquals(paths._norm_root('/'), '/') - self.assertEquals(paths._norm_root('//a'), '/a') - self.assertEquals(paths._norm_root('//a./b'), '/a./b') + assert paths._norm_root('') == '/' + assert paths._norm_root('/') == '/' + assert paths._norm_root('//a') == '/a' + assert paths._norm_root('//a./b') == '/a./b' diff --git a/kazoo/tests/test_queue.py b/kazoo/tests/test_queue.py index b54b63f..59ece16 100644 --- a/kazoo/tests/test_queue.py +++ b/kazoo/tests/test_queue.py @@ -1,43 +1,46 @@ import uuid -from nose import SkipTest -from nose.tools import eq_, ok_ +import pytest from kazoo.testing import KazooTestCase from kazoo.tests.util import TRAVIS_ZK_VERSION class KazooQueueTests(KazooTestCase): - def _makeOne(self): path = "/" + uuid.uuid4().hex return self.client.Queue(path) def test_queue_validation(self): queue = self._makeOne() - self.assertRaises(TypeError, queue.put, {}) - self.assertRaises(TypeError, queue.put, b"one", b"100") - self.assertRaises(TypeError, queue.put, b"one", 10.0) - self.assertRaises(ValueError, queue.put, b"one", -100) - self.assertRaises(ValueError, queue.put, b"one", 100000) + with pytest.raises(TypeError): + queue.put({}) + with pytest.raises(TypeError): + queue.put(b"one", b"100") + with pytest.raises(TypeError): + queue.put(b"one", 10.0) + with pytest.raises(ValueError): + queue.put(b"one", -100) + with pytest.raises(ValueError): + queue.put(b"one", 100000) def test_empty_queue(self): queue = self._makeOne() - eq_(len(queue), 0) - self.assertTrue(queue.get() is None) - eq_(len(queue), 0) + assert len(queue) == 0 + assert queue.get() is None + assert len(queue) == 0 def test_queue(self): queue = self._makeOne() queue.put(b"one") queue.put(b"two") queue.put(b"three") - eq_(len(queue), 3) + assert len(queue) == 3 - eq_(queue.get(), b"one") - eq_(queue.get(), b"two") - eq_(queue.get(), b"three") - eq_(len(queue), 0) + assert queue.get() == b"one" + assert queue.get() == b"two" + assert queue.get() == b"three" + assert len(queue) == 0 def test_priority(self): queue = self._makeOne() @@ -46,14 +49,13 @@ class KazooQueueTests(KazooTestCase): queue.put(b"two", priority=0) queue.put(b"three", priority=10) - eq_(queue.get(), b"one") - eq_(queue.get(), b"two") - eq_(queue.get(), b"three") - eq_(queue.get(), b"four") + assert queue.get() == b"one" + assert queue.get() == b"two" + assert queue.get() == b"three" + assert queue.get() == b"four" class KazooLockingQueueTests(KazooTestCase): - def setUp(self): KazooTestCase.setUp(self) skip = False @@ -66,7 +68,7 @@ class KazooLockingQueueTests(KazooTestCase): if ver[1] < 4: skip = True if skip: - raise SkipTest("Must use Zookeeper 3.4 or above") + pytest.skip("Must use Zookeeper 3.4 or above") def _makeOne(self): path = "/" + uuid.uuid4().hex @@ -74,80 +76,91 @@ class KazooLockingQueueTests(KazooTestCase): def test_queue_validation(self): queue = self._makeOne() - self.assertRaises(TypeError, queue.put, {}) - self.assertRaises(TypeError, queue.put, b"one", b"100") - self.assertRaises(TypeError, queue.put, b"one", 10.0) - self.assertRaises(ValueError, queue.put, b"one", -100) - self.assertRaises(ValueError, queue.put, b"one", 100000) - self.assertRaises(TypeError, queue.put_all, {}) - self.assertRaises(TypeError, queue.put_all, [{}]) - self.assertRaises(TypeError, queue.put_all, [b"one"], b"100") - self.assertRaises(TypeError, queue.put_all, [b"one"], 10.0) - self.assertRaises(ValueError, queue.put_all, [b"one"], -100) - self.assertRaises(ValueError, queue.put_all, [b"one"], 100000) + with pytest.raises(TypeError): + queue.put({}) + with pytest.raises(TypeError): + queue.put(b"one", b"100") + with pytest.raises(TypeError): + queue.put(b"one", 10.0) + with pytest.raises(ValueError): + queue.put(b"one", -100) + with pytest.raises(ValueError): + queue.put(b"one", 100000) + with pytest.raises(TypeError): + queue.put_all({}) + with pytest.raises(TypeError): + queue.put_all([{}]) + with pytest.raises(TypeError): + queue.put_all([b"one"], b"100") + with pytest.raises(TypeError): + queue.put_all([b"one"], 10.0) + with pytest.raises(ValueError): + queue.put_all([b"one"], -100) + with pytest.raises(ValueError): + queue.put_all([b"one"], 100000) def test_empty_queue(self): queue = self._makeOne() - eq_(len(queue), 0) - self.assertTrue(queue.get(0) is None) - eq_(len(queue), 0) + assert len(queue) == 0 + assert queue.get(0) is None + assert len(queue) == 0 def test_queue(self): queue = self._makeOne() queue.put(b"one") queue.put_all([b"two", b"three"]) - eq_(len(queue), 3) + assert len(queue) == 3 - ok_(not queue.consume()) - ok_(not queue.holds_lock()) - eq_(queue.get(1), b"one") - ok_(queue.holds_lock()) + assert not queue.consume() + assert not queue.holds_lock() + assert queue.get(1) == b"one" + assert queue.holds_lock() # Without consuming, should return the same element - eq_(queue.get(1), b"one") - ok_(queue.consume()) - ok_(not queue.holds_lock()) - eq_(queue.get(1), b"two") - ok_(queue.holds_lock()) - ok_(queue.consume()) - ok_(not queue.holds_lock()) - eq_(queue.get(1), b"three") - ok_(queue.holds_lock()) - ok_(queue.consume()) - ok_(not queue.holds_lock()) - ok_(not queue.consume()) - eq_(len(queue), 0) + assert queue.get(1) == b"one" + assert queue.consume() + assert not queue.holds_lock() + assert queue.get(1) == b"two" + assert queue.holds_lock() + assert queue.consume() + assert not queue.holds_lock() + assert queue.get(1) == b"three" + assert queue.holds_lock() + assert queue.consume() + assert not queue.holds_lock() + assert not queue.consume() + assert len(queue) == 0 def test_consume(self): queue = self._makeOne() queue.put(b"one") - ok_(not queue.consume()) - queue.get(.1) - ok_(queue.consume()) - ok_(not queue.consume()) + assert not queue.consume() + queue.get(0.1) + assert queue.consume() + assert not queue.consume() def test_release(self): queue = self._makeOne() queue.put(b"one") - eq_(queue.get(1), b"one") - ok_(queue.holds_lock()) - ok_(queue.release()) - ok_(not queue.holds_lock()) - eq_(queue.get(1), b"one") - ok_(queue.consume()) - ok_(not queue.release()) - eq_(len(queue), 0) + assert queue.get(1) == b"one" + assert queue.holds_lock() + assert queue.release() + assert not queue.holds_lock() + assert queue.get(1) == b"one" + assert queue.consume() + assert not queue.release() + assert len(queue) == 0 def test_holds_lock(self): queue = self._makeOne() - ok_(not queue.holds_lock()) + assert not queue.holds_lock() queue.put(b"one") - queue.get(.1) - ok_(queue.holds_lock()) + queue.get(0.1) + assert queue.holds_lock() queue.consume() - ok_(not queue.holds_lock()) + assert not queue.holds_lock() def test_priority(self): queue = self._makeOne() @@ -156,14 +169,14 @@ class KazooLockingQueueTests(KazooTestCase): queue.put(b"two", priority=0) queue.put(b"three", priority=10) - eq_(queue.get(1), b"one") - ok_(queue.consume()) - eq_(queue.get(1), b"two") - ok_(queue.consume()) - eq_(queue.get(1), b"three") - ok_(queue.consume()) - eq_(queue.get(1), b"four") - ok_(queue.consume()) + assert queue.get(1) == b"one" + assert queue.consume() + assert queue.get(1) == b"two" + assert queue.consume() + assert queue.get(1) == b"three" + assert queue.consume() + assert queue.get(1) == b"four" + assert queue.consume() def test_concurrent_execution(self): queue = self._makeOne() @@ -176,17 +189,17 @@ class KazooLockingQueueTests(KazooTestCase): def get_concurrently(value, event): q = self.client.LockingQueue(queue.path) - value.append(q.get(.1)) + value.append(q.get(0.1)) event.set() self.client.handler.spawn(get_concurrently, value1, event1) self.client.handler.spawn(get_concurrently, value2, event2) self.client.handler.spawn(get_concurrently, value3, event3) queue.put(b"one") - event1.wait(.2) - event2.wait(.2) - event3.wait(.2) + event1.wait(0.2) + event2.wait(0.2) + event3.wait(0.2) result = value1 + value2 + value3 - eq_(result.count(b"one"), 1) - eq_(result.count(None), 2) + assert result.count(b"one") == 1 + assert result.count(None) == 2 diff --git a/kazoo/tests/test_retry.py b/kazoo/tests/test_retry.py index 3ce4a41..7a30667 100644 --- a/kazoo/tests/test_retry.py +++ b/kazoo/tests/test_retry.py @@ -1,15 +1,14 @@ import unittest -from nose.tools import eq_ - +import pytest class TestRetrySleeper(unittest.TestCase): - def _pass(self): pass def _fail(self, times=1): from kazoo.retry import ForceRetryError + scope = dict(times=0) def inner(): @@ -18,24 +17,28 @@ class TestRetrySleeper(unittest.TestCase): else: scope['times'] += 1 raise ForceRetryError('Failed!') + return inner def _makeOne(self, *args, **kwargs): from kazoo.retry import KazooRetry + return KazooRetry(*args, **kwargs) def test_reset(self): retry = self._makeOne(delay=0, max_tries=2) retry(self._fail()) - eq_(retry._attempts, 1) + assert retry._attempts == 1 retry.reset() - eq_(retry._attempts, 0) + assert retry._attempts == 0 def test_too_many_tries(self): from kazoo.retry import RetryFailedError + retry = self._makeOne(delay=0) - self.assertRaises(RetryFailedError, retry, self._fail(times=999)) - eq_(retry._attempts, 1) + with pytest.raises(RetryFailedError): + retry(self._fail(times=999)) + assert retry._attempts == 1 def test_maximum_delay(self): def sleep_func(_time): @@ -43,9 +46,9 @@ class TestRetrySleeper(unittest.TestCase): retry = self._makeOne(delay=10, max_tries=100, sleep_func=sleep_func) retry(self._fail(times=10)) - self.assertTrue(retry._cur_delay < 4000, retry._cur_delay) + assert retry._cur_delay < 4000 # gevent's sleep function is picky about the type - eq_(type(retry._cur_delay), float) + assert type(retry._cur_delay) == float def test_copy(self): def _sleep(t): @@ -53,27 +56,33 @@ class TestRetrySleeper(unittest.TestCase): retry = self._makeOne(sleep_func=_sleep) rcopy = retry.copy() - self.assertTrue(rcopy.sleep_func is _sleep) + assert rcopy.sleep_func is _sleep class TestKazooRetry(unittest.TestCase): - def _makeOne(self, **kw): from kazoo.retry import KazooRetry + return KazooRetry(**kw) def test_connection_closed(self): from kazoo.exceptions import ConnectionClosedError + retry = self._makeOne() def testit(): raise ConnectionClosedError() - self.assertRaises(ConnectionClosedError, retry, testit) + + with pytest.raises(ConnectionClosedError): + retry(testit) def test_session_expired(self): from kazoo.exceptions import SessionExpiredError + retry = self._makeOne(max_tries=1) def testit(): raise SessionExpiredError() - self.assertRaises(Exception, retry, testit) + + with pytest.raises(Exception): + retry(testit) diff --git a/kazoo/tests/test_sasl.py b/kazoo/tests/test_sasl.py index 635b7c4..efdf965 100644 --- a/kazoo/tests/test_sasl.py +++ b/kazoo/tests/test_sasl.py @@ -2,7 +2,7 @@ import os import subprocess import time -from nose import SkipTest +import pytest from kazoo.testing import KazooTestHarness from kazoo.exceptions import ( @@ -17,7 +17,7 @@ class TestLegacySASLDigestAuthentication(KazooTestHarness): try: import puresasl # NOQA except ImportError: - raise SkipTest("PureSASL not available.") + pytest.skip("PureSASL not available.") os.environ["ZOOKEEPER_JAAS_AUTH"] = "digest" self.setup_zookeeper() @@ -27,7 +27,7 @@ class TestLegacySASLDigestAuthentication(KazooTestHarness): else: version = self.client.server_version() if not version or version < (3, 4): - raise SkipTest("Must use Zookeeper 3.4 or above") + pytest.skip("Must use Zookeeper 3.4 or above") def tearDown(self): self.teardown_zookeeper() @@ -48,7 +48,8 @@ class TestLegacySASLDigestAuthentication(KazooTestHarness): client.create("/1", acl=(acl,)) # give ZK a chance to copy data to other node time.sleep(0.1) - self.assertRaises(NoAuthError, self.client.get, "/1") + with pytest.raises(NoAuthError): + self.client.get("/1") finally: client.delete("/1") client.stop() @@ -56,7 +57,8 @@ class TestLegacySASLDigestAuthentication(KazooTestHarness): def test_invalid_sasl_auth(self): client = self._get_client(auth_data=[("sasl", "baduser:badpassword")]) - self.assertRaises(AuthFailedError, client.start) + with pytest.raises(AuthFailedError): + client.start() class TestSASLDigestAuthentication(KazooTestHarness): @@ -64,7 +66,7 @@ class TestSASLDigestAuthentication(KazooTestHarness): try: import puresasl # NOQA except ImportError: - raise SkipTest("PureSASL not available.") + pytest.skip("PureSASL not available.") os.environ["ZOOKEEPER_JAAS_AUTH"] = "digest" self.setup_zookeeper() @@ -74,7 +76,7 @@ class TestSASLDigestAuthentication(KazooTestHarness): else: version = self.client.server_version() if not version or version < (3, 4): - raise SkipTest("Must use Zookeeper 3.4 or above") + pytest.skip("Must use Zookeeper 3.4 or above") def tearDown(self): self.teardown_zookeeper() @@ -99,7 +101,8 @@ class TestSASLDigestAuthentication(KazooTestHarness): client.create("/1", acl=(acl,)) # give ZK a chance to copy data to other node time.sleep(0.1) - self.assertRaises(NoAuthError, self.client.get, "/1") + with pytest.raises(NoAuthError): + self.client.get("/1") finally: client.delete("/1") client.stop() @@ -113,7 +116,8 @@ class TestSASLDigestAuthentication(KazooTestHarness): "password": "badpassword", } ) - self.assertRaises(AuthFailedError, client.start) + with pytest.raises(AuthFailedError): + client.start() class TestSASLGSSAPIAuthentication(KazooTestHarness): @@ -121,13 +125,13 @@ class TestSASLGSSAPIAuthentication(KazooTestHarness): try: import puresasl # NOQA except ImportError: - raise SkipTest("PureSASL not available.") + pytest.skip("PureSASL not available.") try: import kerberos # NOQA except ImportError: - raise SkipTest("Kerberos support not available.") + pytest.skip("Kerberos support not available.") if not os.environ.get("KRB5_TEST_ENV"): - raise SkipTest("Test Kerberos environ not setup.") + pytest.skip("Test Kerberos environ not setup.") os.environ["ZOOKEEPER_JAAS_AUTH"] = "gssapi" self.setup_zookeeper() @@ -137,7 +141,7 @@ class TestSASLGSSAPIAuthentication(KazooTestHarness): else: version = self.client.server_version() if not version or version < (3, 4): - raise SkipTest("Must use Zookeeper 3.4 or above") + pytest.skip("Must use Zookeeper 3.4 or above") def tearDown(self): self.teardown_zookeeper() @@ -163,7 +167,8 @@ class TestSASLGSSAPIAuthentication(KazooTestHarness): client.create("/1", acl=(acl,)) # give ZK a chance to copy data to other node time.sleep(0.1) - self.assertRaises(NoAuthError, self.client.get, "/1") + with pytest.raises(NoAuthError): + self.client.get("/1") finally: client.delete("/1") client.stop() @@ -183,4 +188,5 @@ class TestSASLGSSAPIAuthentication(KazooTestHarness): ) client = self._get_client(sasl_options={"mechanism": "GSSAPI"}) - self.assertRaises(AuthFailedError, client.start) + with pytest.raises(AuthFailedError): + client.start() diff --git a/kazoo/tests/test_security.py b/kazoo/tests/test_security.py index 4a7e670..ee740a9 100644 --- a/kazoo/tests/test_security.py +++ b/kazoo/tests/test_security.py @@ -1,40 +1,42 @@ import unittest -from nose.tools import eq_ from kazoo.security import Permissions class TestACL(unittest.TestCase): def _makeOne(self, *args, **kwargs): from kazoo.security import make_acl + return make_acl(*args, **kwargs) def test_read_acl(self): acl = self._makeOne("digest", ":", read=True) - eq_(acl.perms & Permissions.READ, Permissions.READ) + assert acl.perms & Permissions.READ == Permissions.READ def test_all_perms(self): acl = self._makeOne("digest", ":", read=True, write=True, create=True, delete=True, admin=True) for perm in [Permissions.READ, Permissions.CREATE, Permissions.WRITE, Permissions.DELETE, Permissions.ADMIN]: - eq_(acl.perms & perm, perm) + assert acl.perms & perm == perm def test_perm_listing(self): from kazoo.security import ACL + f = ACL(15, 'fred') - self.assert_('READ' in f.acl_list) - self.assert_('WRITE' in f.acl_list) - self.assert_('CREATE' in f.acl_list) - self.assert_('DELETE' in f.acl_list) + assert 'READ' in f.acl_list + assert 'WRITE' in f.acl_list + assert 'CREATE' in f.acl_list + assert 'DELETE' in f.acl_list f = ACL(16, 'fred') - self.assert_('ADMIN' in f.acl_list) + assert 'ADMIN' in f.acl_list f = ACL(31, 'george') - self.assert_('ALL' in f.acl_list) + assert 'ALL' in f.acl_list def test_perm_repr(self): from kazoo.security import ACL + f = ACL(16, 'fred') - self.assert_("ACL(perms=16, acl_list=['ADMIN']" in repr(f)) + assert "ACL(perms=16, acl_list=['ADMIN']" in repr(f) diff --git a/kazoo/tests/test_threading_handler.py b/kazoo/tests/test_threading_handler.py index a6b6f3a..4376957 100644 --- a/kazoo/tests/test_threading_handler.py +++ b/kazoo/tests/test_threading_handler.py @@ -2,18 +2,18 @@ import threading import unittest import mock -from nose.tools import assert_raises -from nose.tools import eq_ -from nose.tools import raises +import pytest class TestThreadingHandler(unittest.TestCase): def _makeOne(self, *args): from kazoo.handlers.threading import SequentialThreadingHandler + return SequentialThreadingHandler(*args) def _getAsync(self, *args): from kazoo.handlers.threading import AsyncResult + return AsyncResult def test_proper_threading(self): @@ -32,27 +32,27 @@ class TestThreadingHandler(unittest.TestCase): def test_exception_raising(self): h = self._makeOne() - @raises(h.timeout_exception) - def testit(): + with pytest.raises(h.timeout_exception): raise h.timeout_exception("This is a timeout") - testit() def test_double_start_stop(self): h = self._makeOne() h.start() - self.assertTrue(h._running) + assert h._running is True h.start() h.stop() h.stop() - self.assertFalse(h._running) + assert h._running is False def test_huge_file_descriptor(self): from kazoo.handlers.threading import _HAS_EPOLL + if not _HAS_EPOLL: self.skipTest('only run on systems with epoll()') import resource import socket from kazoo.handlers.utils import create_tcp_socket + try: resource.setrlimit(resource.RLIMIT_NOFILE, (4096, 4096)) except (ValueError, resource.error): @@ -66,7 +66,7 @@ class TestThreadingHandler(unittest.TestCase): h = self._makeOne() h.start() h.select(socks, [], []) - with self.assertRaises(ValueError): + with pytest.raises(ValueError): h._select(socks, [], []) h._epoll_select(socks, [], []) h.stop() @@ -75,21 +75,23 @@ class TestThreadingHandler(unittest.TestCase): class TestThreadingAsync(unittest.TestCase): def _makeOne(self, *args): from kazoo.handlers.threading import AsyncResult + return AsyncResult(*args) def _makeHandler(self): from kazoo.handlers.threading import SequentialThreadingHandler + return SequentialThreadingHandler() def test_ready(self): mock_handler = mock.Mock() async_result = self._makeOne(mock_handler) - eq_(async_result.ready(), False) + assert async_result.ready() is False async_result.set('val') - eq_(async_result.ready(), True) - eq_(async_result.successful(), True) - eq_(async_result.exception, None) + assert async_result.ready() is True + assert async_result.successful() is True + assert async_result.exception is None def test_callback_queued(self): mock_handler = mock.Mock() @@ -124,13 +126,14 @@ class TestThreadingAsync(unittest.TestCase): val = async_result.get() lst.append(val) cv.set() + th = threading.Thread(target=wait_for_val) th.start() bv.wait() async_result.set('fred') cv.wait() - eq_(lst, ['fred']) + assert lst == ['fred'] th.join() def test_get_with_nowait(self): @@ -138,15 +141,11 @@ class TestThreadingAsync(unittest.TestCase): async_result = self._makeOne(mock_handler) timeout = self._makeHandler().timeout_exception - @raises(timeout) - def test_it(): + with pytest.raises(timeout): async_result.get(block=False) - test_it() - @raises(timeout) - def test_nowait(): + with pytest.raises(timeout): async_result.get_nowait() - test_nowait() def test_get_with_exception(self): mock_handler = mock.Mock() @@ -165,13 +164,14 @@ class TestThreadingAsync(unittest.TestCase): else: lst.append(val) cv.set() + th = threading.Thread(target=wait_for_val) th.start() bv.wait() async_result.set_exception(ImportError) cv.wait() - eq_(lst, ['oops']) + assert lst == ['oops'] th.join() def test_wait(self): @@ -191,13 +191,14 @@ class TestThreadingAsync(unittest.TestCase): else: lst.append(val) cv.set() + th = threading.Thread(target=wait_for_val) th.start() bv.wait(10) async_result.set("fred") cv.wait(15) - eq_(lst, [True]) + assert lst == [True] th.join() def test_wait_race(self): @@ -217,6 +218,7 @@ class TestThreadingAsync(unittest.TestCase): # NB: should not sleep async_result.wait(20) cv.set() + th = threading.Thread(target=wait_for_val) th.daemon = True th.start() @@ -224,7 +226,7 @@ class TestThreadingAsync(unittest.TestCase): # if the wait() didn't sleep (correctly), cv will be set quickly # if it did sleep, the cv will not be set yet and this will timeout cv.wait(10) - eq_(cv.is_set(), True) + assert cv.is_set() is True th.join() def test_set_before_wait(self): @@ -239,10 +241,11 @@ class TestThreadingAsync(unittest.TestCase): val = async_result.get() lst.append(val) cv.set() + th = threading.Thread(target=wait_for_val) th.start() cv.wait() - eq_(lst, ['fred']) + assert lst == ['fred'] th.join() def test_set_exc_before_wait(self): @@ -261,10 +264,11 @@ class TestThreadingAsync(unittest.TestCase): else: lst.append(val) cv.set() + th = threading.Thread(target=wait_for_val) th.start() cv.wait() - eq_(lst, ['ooops']) + assert lst == ['ooops'] th.join() def test_linkage(self): @@ -285,11 +289,11 @@ class TestThreadingAsync(unittest.TestCase): th.start() async_result.rawlink(add_on) - async_result.set('fred') + async_result.set(b'fred') assert mock_handler.completion_queue.put.called async_result.unlink(add_on) cv.wait() - eq_(async_result.value, 'fred') + assert async_result.value == b'fred' th.join() def test_linkage_not_ready(self): @@ -329,11 +333,12 @@ class TestThreadingAsync(unittest.TestCase): @capture_exceptions(async_result) def exceptional_function(): - return 1/0 + return 1 / 0 exceptional_function() - assert_raises(ZeroDivisionError, async_result.get) + with pytest.raises(ZeroDivisionError): + async_result.get() def test_no_capture_exceptions(self): from kazoo.handlers.utils import capture_exceptions diff --git a/kazoo/tests/test_utils.py b/kazoo/tests/test_utils.py index 260d993..7e21a40 100644 --- a/kazoo/tests/test_utils.py +++ b/kazoo/tests/test_utils.py @@ -1,10 +1,11 @@ import unittest from mock import patch -from nose import SkipTest +import pytest try: from kazoo.handlers.eventlet import green_socket as socket + EVENTLET_HANDLER_AVAILABLE = True except ImportError: EVENTLET_HANDLER_AVAILABLE = False @@ -30,7 +31,7 @@ class TestCreateTCPConnection(unittest.TestCase): def test_timeout_arg_eventlet(self): if not EVENTLET_HANDLER_AVAILABLE: - raise SkipTest('eventlet handler not available.') + pytest.skip('eventlet handler not available.') from kazoo.handlers import utils from kazoo.handlers.utils import create_tcp_connection, time @@ -57,12 +58,13 @@ class TestCreateTCPConnection(unittest.TestCase): # Simulate a second passing between calls to check the current time. with patch.object(time, 'time', side_effect=range(10)): - with self.assertRaises(socket.error): + with pytest.raises(socket.error): create_tcp_connection(socket, ('127.0.0.1', 2181), timeout=0.5) def test_negative_timeout(self): from kazoo.handlers.utils import create_tcp_connection, socket - with self.assertRaises(socket.error): + + with pytest.raises(socket.error): create_tcp_connection(socket, ('127.0.0.1', 2181), timeout=-1) def test_zero_timeout(self): @@ -74,5 +76,5 @@ class TestCreateTCPConnection(unittest.TestCase): # Simulate no time passing between calls to check the current time. with patch.object(time, 'time', return_value=time.time()): - with self.assertRaises(socket.error): + with pytest.raises(socket.error): create_tcp_connection(socket, ('127.0.0.1', 2181), timeout=0) diff --git a/kazoo/tests/test_watchers.py b/kazoo/tests/test_watchers.py index 35f34b5..69d8fce 100644 --- a/kazoo/tests/test_watchers.py +++ b/kazoo/tests/test_watchers.py @@ -2,8 +2,7 @@ import time import threading import uuid -from nose.tools import eq_ -from nose.tools import raises +import pytest from kazoo.exceptions import KazooException from kazoo.protocol.states import EventType @@ -30,12 +29,12 @@ class KazooDataWatcherTests(KazooTestCase): update.set() update.wait(10) - eq_(data, [None]) + assert data == [None] update.clear() self.client.create(self.path, b'fred') update.wait(10) - eq_(data[0], b'fred') + assert data[0] == b'fred' update.clear() def test_data_watcher_once(self): @@ -54,15 +53,14 @@ class KazooDataWatcherTests(KazooTestCase): update.set() update.wait(10) - eq_(data, [None]) + assert data == [None] update.clear() - @raises(KazooException) - def test_it(): + with pytest.raises(KazooException): + @dwatcher def func(d, stat): data.pop() - test_it() def test_data_watcher_with_event(self): # Test that the data watcher gets passed the event, if it @@ -80,12 +78,12 @@ class KazooDataWatcherTests(KazooTestCase): update.set() update.wait(10) - eq_(data, [None]) + assert data == [None] update.clear() self.client.create(self.path, b'fred') update.wait(10) - eq_(data[0].type, EventType.CREATED) + assert data[0].type == EventType.CREATED update.clear() def test_func_style_data_watch(self): @@ -99,15 +97,16 @@ class KazooDataWatcherTests(KazooTestCase): data.pop() data.append(d) update.set() + self.client.DataWatch(path, changed) update.wait(10) - eq_(data, [None]) + assert data == [None] update.clear() self.client.create(path, b'fred') update.wait(10) - eq_(data[0], b'fred') + assert data[0] == b'fred' update.clear() def test_datawatch_across_session_expire(self): @@ -121,13 +120,13 @@ class KazooDataWatcherTests(KazooTestCase): update.set() update.wait(10) - eq_(data, [b""]) + assert data == [b""] update.clear() self.expire_session(threading.Event) self.client.retry(self.client.set, self.path, b'fred') update.wait(25) - eq_(data[0], b'fred') + assert data[0] == b'fred' def test_func_stops(self): update = threading.Event() @@ -146,21 +145,21 @@ class KazooDataWatcherTests(KazooTestCase): return False update.wait(10) - eq_(data, [None]) + assert data == [None] update.clear() fail_through.append(True) self.client.create(self.path, b'fred') update.wait(10) - eq_(data[0], b'fred') + assert data[0] == b'fred' update.clear() self.client.set(self.path, b'asdfasdf') update.wait(0.2) - eq_(data[0], b'fred') + assert data[0] == b'fred' d, stat = self.client.get(self.path) - eq_(d, b'asdfasdf') + assert d == b'asdfasdf' def test_no_such_node(self): args = [] @@ -169,7 +168,7 @@ class KazooDataWatcherTests(KazooTestCase): def changed(d, stat): args.extend([d, stat]) - eq_(args, [None, None]) + assert args == [None, None] def test_no_such_node_for_children_watch(self): args = [] @@ -182,27 +181,27 @@ class KazooDataWatcherTests(KazooTestCase): # watch a node which does not exist children_watch = self.client.ChildrenWatch(path, changed) - eq_(update.is_set(), False) - eq_(children_watch._stopped, True) - eq_(args, []) + assert update.is_set() is False + assert children_watch._stopped is True + assert args == [] # watch a node which exists self.client.create(path, b'') children_watch = self.client.ChildrenWatch(path, changed) update.wait(3) - eq_(args, [[]]) + assert args == [[]] update.clear() # watch changes self.client.create(path + '/fred', b'') update.wait(3) - eq_(args, [[], ['fred']]) + assert args == [[], ['fred']] update.clear() # delete children self.client.delete(path + '/fred') update.wait(3) - eq_(args, [[], ['fred'], []]) + assert args == [[], ['fred'], []] update.clear() # delete watching @@ -216,30 +215,18 @@ class KazooDataWatcherTests(KazooTestCase): children_watch._run_lock.release() time.sleep(retry / 10.0) - eq_(update.is_set(), False) - eq_(children_watch._stopped, True) - - def test_bad_watch_func2(self): - counter = 0 - - @self.client.DataWatch(self.path) - def changed(d, stat): - if counter > 0: - raise Exception("oops") - - raises(Exception)(changed) - - counter += 1 - self.client.set(self.path, b'asdfasdf') + assert update.is_set() is False + assert children_watch._stopped is True def test_watcher_evaluating_to_false(self): class WeirdWatcher(list): def __call__(self, *args): self.called = True + watcher = WeirdWatcher() self.client.DataWatch(self.path, watcher) self.client.set(self.path, b'mwahaha') - self.assertTrue(watcher.called) + assert watcher.called is True def test_watcher_repeat_delete(self): a = [] @@ -252,24 +239,24 @@ class KazooDataWatcherTests(KazooTestCase): a.append(val) ev.set() - eq_(a, [None]) + assert a == [None] ev.wait(10) ev.clear() self.client.create(self.path, b'blah') ev.wait(10) - eq_(ev.is_set(), True) + assert ev.is_set() is True ev.clear() - eq_(a, [None, b'blah']) + assert a == [None, b'blah'] self.client.delete(self.path) ev.wait(10) - eq_(ev.is_set(), True) + assert ev.is_set() is True ev.clear() - eq_(a, [None, b'blah', None]) + assert a == [None, b'blah', None] self.client.create(self.path, b'blah') ev.wait(10) - eq_(ev.is_set(), True) + assert ev.is_set() is True ev.clear() - eq_(a, [None, b'blah', None, b'blah']) + assert a == [None, b'blah', None, b'blah'] def test_watcher_with_closing(self): a = [] @@ -281,14 +268,15 @@ class KazooDataWatcherTests(KazooTestCase): def changed(val, stat): a.append(val) ev.set() - eq_(a, [None]) + + assert a == [None] b = False try: self.client.stop() except: b = True - eq_(b, False) + assert b is False class KazooChildrenWatcherTests(KazooTestCase): @@ -309,17 +297,17 @@ class KazooChildrenWatcherTests(KazooTestCase): update.set() update.wait(10) - eq_(all_children, []) + assert all_children == [] update.clear() self.client.create(self.path + '/' + 'smith') update.wait(10) - eq_(all_children, ['smith']) + assert all_children == ['smith'] update.clear() self.client.create(self.path + '/' + 'george') update.wait(10) - eq_(sorted(all_children), ['george', 'smith']) + assert sorted(all_children) == ['george', 'smith'] def test_child_watcher_once(self): update = threading.Event() @@ -335,15 +323,14 @@ class KazooChildrenWatcherTests(KazooTestCase): update.set() update.wait(10) - eq_(all_children, []) + assert all_children == [] update.clear() - @raises(KazooException) - def test_it(): + with pytest.raises(KazooException): + @cwatch def changed_again(children): update.set() - test_it() def test_child_watcher_with_event(self): update = threading.Event() @@ -356,12 +343,12 @@ class KazooChildrenWatcherTests(KazooTestCase): update.set() update.wait(10) - eq_(events, [None]) + assert events == [None] update.clear() self.client.create(self.path + '/' + 'smith') update.wait(10) - eq_(events[0].type, EventType.CHILD) + assert events[0].type == EventType.CHILD update.clear() def test_func_style_child_watcher(self): @@ -377,17 +364,17 @@ class KazooChildrenWatcherTests(KazooTestCase): self.client.ChildrenWatch(self.path, changed) update.wait(10) - eq_(all_children, []) + assert all_children == [] update.clear() self.client.create(self.path + '/' + 'smith') update.wait(10) - eq_(all_children, ['smith']) + assert all_children == ['smith'] update.clear() self.client.create(self.path + '/' + 'george') update.wait(10) - eq_(sorted(all_children), ['george', 'smith']) + assert sorted(all_children) == ['george', 'smith'] def test_func_stops(self): update = threading.Event() @@ -405,18 +392,18 @@ class KazooChildrenWatcherTests(KazooTestCase): return False update.wait(10) - eq_(all_children, []) + assert all_children == [] update.clear() fail_through.append(True) self.client.create(self.path + '/' + 'smith') update.wait(10) - eq_(all_children, ['smith']) + assert all_children == ['smith'] update.clear() self.client.create(self.path + '/' + 'george') update.wait(0.5) - eq_(all_children, ['smith']) + assert all_children == ['smith'] def test_child_watcher_remove_session_watcher(self): update = threading.Event() @@ -436,21 +423,21 @@ class KazooChildrenWatcherTests(KazooTestCase): session_watcher = children_watch._session_watcher update.wait(10) - eq_(session_watcher in self.client.state_listeners, True) - eq_(all_children, []) + assert session_watcher in self.client.state_listeners + assert all_children == [] update.clear() fail_through.append(True) self.client.create(self.path + '/' + 'smith') update.wait(10) - eq_(session_watcher not in self.client.state_listeners, True) - eq_(all_children, ['smith']) + assert session_watcher not in self.client.state_listeners + assert all_children == ['smith'] update.clear() self.client.create(self.path + '/' + 'george') update.wait(10) - eq_(session_watcher not in self.client.state_listeners, True) - eq_(all_children, ['smith']) + assert session_watcher not in self.client.state_listeners + assert all_children == ['smith'] def test_child_watch_session_loss(self): update = threading.Event() @@ -464,19 +451,19 @@ class KazooChildrenWatcherTests(KazooTestCase): update.set() update.wait(10) - eq_(all_children, []) + assert all_children == [] update.clear() self.client.create(self.path + '/' + 'smith') update.wait(10) - eq_(all_children, ['smith']) + assert all_children == ['smith'] update.clear() self.expire_session(threading.Event) self.client.retry(self.client.create, self.path + '/' + 'george') update.wait(20) - eq_(sorted(all_children), ['george', 'smith']) + assert sorted(all_children) == ['george', 'smith'] def test_child_stop_on_session_loss(self): update = threading.Event() @@ -490,35 +477,23 @@ class KazooChildrenWatcherTests(KazooTestCase): update.set() update.wait(10) - eq_(all_children, []) + assert all_children == [] update.clear() self.client.create(self.path + '/' + 'smith') update.wait(10) - eq_(all_children, ['smith']) + assert all_children == ['smith'] update.clear() self.expire_session(threading.Event) self.client.retry(self.client.create, self.path + '/' + 'george') update.wait(4) - eq_(update.is_set(), False) - eq_(all_children, ['smith']) + assert update.is_set() is False + assert all_children == ['smith'] children = self.client.get_children(self.path) - eq_(sorted(children), ['george', 'smith']) - - def test_bad_children_watch_func(self): - counter = 0 - - @self.client.ChildrenWatch(self.path) - def changed(children): - if counter > 0: - raise Exception("oops") - - raises(Exception)(changed) - counter += 1 - self.client.create(self.path + '/' + 'smith') + assert sorted(children) == ['george', 'smith'] class KazooPatientChildrenWatcherTests(KazooTestCase): @@ -528,6 +503,7 @@ class KazooPatientChildrenWatcherTests(KazooTestCase): def _makeOne(self, *args, **kwargs): from kazoo.recipe.watchers import PatientChildrenWatch + return PatientChildrenWatch(*args, **kwargs) def test_watch(self): @@ -535,37 +511,36 @@ class KazooPatientChildrenWatcherTests(KazooTestCase): watcher = self._makeOne(self.client, self.path, 0.1) result = watcher.start() children, asy = result.get() - eq_(len(children), 0) - eq_(asy.ready(), False) + assert len(children) == 0 + assert asy.ready() is False self.client.create(self.path + '/' + 'fred') asy.get(timeout=1) - eq_(asy.ready(), True) + assert asy.ready() is True def test_exception(self): from kazoo.exceptions import NoNodeError + watcher = self._makeOne(self.client, self.path, 0.1) result = watcher.start() - @raises(NoNodeError) - def testit(): + with pytest.raises(NoNodeError): result.get() - testit() def test_watch_iterations(self): self.client.ensure_path(self.path) watcher = self._makeOne(self.client, self.path, 0.5) result = watcher.start() - eq_(result.ready(), False) + assert result.ready() is False time.sleep(0.08) self.client.create(self.path + '/' + uuid.uuid4().hex) - eq_(result.ready(), False) + assert result.ready() is False time.sleep(0.08) - eq_(result.ready(), False) + assert result.ready() is False self.client.create(self.path + '/' + uuid.uuid4().hex) time.sleep(0.08) - eq_(result.ready(), False) + assert result.ready() is False children, asy = result.get() - eq_(len(children), 2) + assert len(children) == 2 diff --git a/requirements_sasl.txt b/requirements_sasl.txt index 3fb3416..8e04041 100644 --- a/requirements_sasl.txt +++ b/requirements_sasl.txt @@ -1 +1 @@ -pure_sasl==0.5.1 +pure_sasl>=0.5.1 diff --git a/requirements_sphinx.txt b/requirements_sphinx.txt index 36a0a69..6600509 100644 --- a/requirements_sphinx.txt +++ b/requirements_sphinx.txt @@ -1,4 +1,4 @@ -Jinja2==2.7.3 -Pygments==1.6 -Sphinx==1.2.2 -docutils==0.12 +Jinja2>=2.7.3 +Pygments>=1.6 +Sphinx>=1.2.2 +docutils>=0.12 diff --git a/requirements_test.txt b/requirements_test.txt index f385468..06f6978 100644 --- a/requirements_test.txt +++ b/requirements_test.txt @@ -1,5 +1,5 @@ -coverage==3.7.1 -mock==1.0.1 -nose==1.3.3 -flake8==2.3.0 -objgraph==3.4.0 +flake8 +mock +objgraph +pytest +pytest-cov diff --git a/run_failure.py b/run_failure.py index b49c13e..7bc1dac 100644 --- a/run_failure.py +++ b/run_failure.py @@ -3,24 +3,26 @@ import sys def test(arg): - return os.system('bin/nosetests -s -d -v %s' % arg) + return os.system("bin/pytest -v %s" % arg) def main(args): if not args: - print("Run as bin/python run_failure.py , for example: \n" - "bin/python run_failure.py " - "kazoo.tests.test_watchers:KazooChildrenWatcherTests") + print( + "Run as bin/python run_failure.py , for example: \n" + "bin/python run_failure.py " + "kazoo.tests.test_watchers:KazooChildrenWatcherTests" + ) return arg = args[0] i = 0 while 1: i += 1 - print('Run number: %s' % i) + print("Run number: %s" % i) ret = test(arg) if ret != 0: break -if __name__ == '__main__': +if __name__ == "__main__": main(sys.argv[1:]) diff --git a/setup.cfg b/setup.cfg index 967016b..d2c3491 100644 --- a/setup.cfg +++ b/setup.cfg @@ -11,9 +11,5 @@ tag_build = dev [metadata] license_file = LICENSE -[nosetests] -cover-package = kazoo -nocapture = 1 -cover-erase = 1 -where = kazoo -cover-inclusive = 1 +[tool:pytest] +addopts = -ra -v diff --git a/setup.py b/setup.py index e47bc31..15a7a13 100644 --- a/setup.py +++ b/setup.py @@ -14,20 +14,19 @@ with open(os.path.join(here, 'kazoo', 'version.py')) as f: version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', f.read(), re.MULTILINE).group(1) -PYTHON3 = sys.version_info > (3, ) PYPY = getattr(sys, 'pypy_version_info', False) and True or False install_requires = ['six'] tests_require = install_requires + [ - 'coverage', 'mock', - 'nose', + 'pytest', + 'pytest-cov', 'flake8', 'objgraph', ] -if not (PYTHON3 or PYPY): +if not PYPY: tests_require += [ 'gevent>=1.2', 'eventlet>=0.17.1', diff --git a/tox.ini b/tox.ini index d4c35fe..3b0e925 100644 --- a/tox.ini +++ b/tox.ini @@ -12,7 +12,7 @@ envlist = py36, py36-{sasl,docs}, py37, - py37-{sasl,docs}, + py37-{gevent,eventlet,sasl,docs}, pypy [testenv:pep8] @@ -28,6 +28,7 @@ setenv = ZOOKEEPER_SUFFIX={env:ZOOKEEPER_SUFFIX:} ZOOKEEPER_LIB={env:ZOOKEEPER_LIB:} deps = + -c{toxinidir}/constraints.txt -r{toxinidir}/requirements.txt -r{toxinidir}/requirements_test.txt docs: -r{toxinidir}/requirements_sphinx.txt @@ -38,7 +39,7 @@ deps = commands = sasl: {toxinidir}/init_krb5.sh {envtmpdir}/kerberos \ /{toxinidir}/ensure-zookeeper-env.sh \ - nosetests {posargs: -d -v --with-coverage kazoo.tests} + pytest {posargs: -ra -v --cov=kazoo kazoo/tests} [flake8] builtins = _ -- cgit v1.2.1