tor-commits
Threads by month
- ----- 2026 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2025 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2024 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2023 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2022 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2021 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2020 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2019 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2018 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2017 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2016 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2015 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2014 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2013 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2012 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2011 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- 1 participants
- 216258 discussions
commit 1db0e6b84e870a5f228f3a770daca542bdef5d4e
Author: Illia Volochii <illia.volochii(a)gmail.com>
Date: Sun Apr 26 22:31:12 2020 +0300
Fix unit tests
---
test/unit/connection/authentication.py | 36 +++--
test/unit/connection/connect.py | 19 +--
test/unit/control/controller.py | 254 +++++++++++++++++++--------------
test/unit/response/control_message.py | 10 +-
4 files changed, 188 insertions(+), 131 deletions(-)
diff --git a/test/unit/connection/authentication.py b/test/unit/connection/authentication.py
index f6241e0e..596fa50c 100644
--- a/test/unit/connection/authentication.py
+++ b/test/unit/connection/authentication.py
@@ -14,41 +14,52 @@ import unittest
import stem.connection
import test
-from unittest.mock import Mock, patch
+from unittest.mock import patch
from stem.response import ControlMessage
from stem.util import log
+from test.unit.util.asynchronous import (
+ async_test,
+ coro_func_raising_exc,
+ coro_func_returning_value,
+)
class TestAuthenticate(unittest.TestCase):
@patch('stem.connection.get_protocolinfo')
- @patch('stem.connection.authenticate_none', Mock())
- def test_with_get_protocolinfo(self, get_protocolinfo_mock):
+ @patch('stem.connection.authenticate_none')
+ @async_test
+ async def test_with_get_protocolinfo(self, authenticate_none_mock, get_protocolinfo_mock):
"""
Tests the authenticate() function when it needs to make a get_protocolinfo.
"""
# tests where get_protocolinfo succeeds
+ authenticate_none_mock.side_effect = coro_func_returning_value(None)
+
protocolinfo_message = ControlMessage.from_str('250-PROTOCOLINFO 1\r\n250 OK\r\n', 'PROTOCOLINFO')
protocolinfo_message.auth_methods = (stem.connection.AuthMethod.NONE, )
- get_protocolinfo_mock.return_value = protocolinfo_message
+ get_protocolinfo_mock.side_effect = coro_func_returning_value(protocolinfo_message)
- stem.connection.authenticate(None)
+ await stem.connection.authenticate(None)
# tests where get_protocolinfo raises an exception
get_protocolinfo_mock.side_effect = stem.ProtocolError
- self.assertRaises(stem.connection.IncorrectSocketType, stem.connection.authenticate, None)
+ with self.assertRaises(stem.connection.IncorrectSocketType):
+ await stem.connection.authenticate(None)
get_protocolinfo_mock.side_effect = stem.SocketError
- self.assertRaises(stem.connection.AuthenticationFailure, stem.connection.authenticate, None)
+ with self.assertRaises(stem.connection.AuthenticationFailure):
+ await stem.connection.authenticate(None)
@patch('stem.connection.authenticate_none')
@patch('stem.connection.authenticate_password')
@patch('stem.connection.authenticate_cookie')
@patch('stem.connection.authenticate_safecookie')
- def test_all_use_cases(self, authenticate_safecookie_mock, authenticate_cookie_mock, authenticate_password_mock, authenticate_none_mock):
+ @async_test
+ async def test_all_use_cases(self, authenticate_safecookie_mock, authenticate_cookie_mock, authenticate_password_mock, authenticate_none_mock):
"""
Does basic validation that all valid use cases for the PROTOCOLINFO input
and dependent functions result in either success or a AuthenticationFailed
@@ -133,15 +144,16 @@ class TestAuthenticate(unittest.TestCase):
auth_mock, raised_exc = authenticate_safecookie_mock, auth_cookie_exc
if raised_exc:
- auth_mock.side_effect = raised_exc
+ auth_mock.side_effect = coro_func_raising_exc(raised_exc)
else:
- auth_mock.side_effect = None
+ auth_mock.side_effect = coro_func_returning_value(None)
expect_success = True
if expect_success:
- stem.connection.authenticate(None, 'blah', None, protocolinfo)
+ await stem.connection.authenticate(None, 'blah', None, protocolinfo)
else:
- self.assertRaises(stem.connection.AuthenticationFailure, stem.connection.authenticate, None, 'blah', None, protocolinfo)
+ with self.assertRaises(stem.connection.AuthenticationFailure):
+ await stem.connection.authenticate(None, 'blah', None, protocolinfo)
# revert logging back to normal
stem_logger.setLevel(log.logging_level(log.TRACE))
diff --git a/test/unit/connection/connect.py b/test/unit/connection/connect.py
index 175a1ebd..d2a22f18 100644
--- a/test/unit/connection/connect.py
+++ b/test/unit/connection/connect.py
@@ -11,6 +11,8 @@ import stem.socket
from unittest.mock import Mock, patch
+from test.unit.util.asynchronous import coro_func_raising_exc, coro_func_returning_value
+
class TestConnect(unittest.TestCase):
@patch('sys.stdout', new_callable = io.StringIO)
@@ -85,6 +87,7 @@ class TestConnect(unittest.TestCase):
@patch('stem.connection.authenticate')
def test_auth_success(self, authenticate_mock):
+ authenticate_mock.side_effect = coro_func_returning_value(None)
control_socket = Mock()
stem.connection._connect_auth(control_socket, None, False, None, None)
@@ -99,7 +102,7 @@ class TestConnect(unittest.TestCase):
def test_auth_success_with_password_prompt(self, authenticate_mock, getpass_mock):
control_socket = Mock()
- def authenticate_mock_func(controller, password, *args):
+ async def authenticate_mock_func(controller, password, *args):
if password is None:
raise stem.connection.MissingPassword('no password')
elif password == 'my_password':
@@ -117,25 +120,25 @@ class TestConnect(unittest.TestCase):
@patch('sys.stdout', new_callable = io.StringIO)
@patch('stem.connection.authenticate')
def test_auth_failure(self, authenticate_mock, stdout_mock):
- control_socket = stem.socket.ControlPort(connect = False)
+ control_socket = stem.socket.ControlPort()
- authenticate_mock.side_effect = stem.connection.IncorrectSocketType('unable to connect to socket')
+ authenticate_mock.side_effect = coro_func_raising_exc(stem.connection.IncorrectSocketType('unable to connect to socket'))
self._assert_authenticate_fails_with(control_socket, stdout_mock, 'Please check in your torrc that 9051 is the ControlPort.')
- control_socket = stem.socket.ControlSocketFile(connect = False)
+ control_socket = stem.socket.ControlSocketFile()
self._assert_authenticate_fails_with(control_socket, stdout_mock, 'Are you sure the interface you specified belongs to')
- authenticate_mock.side_effect = stem.connection.UnrecognizedAuthMethods('unable to connect', ['telepathy'])
+ authenticate_mock.side_effect = coro_func_raising_exc(stem.connection.UnrecognizedAuthMethods('unable to connect', ['telepathy']))
self._assert_authenticate_fails_with(control_socket, stdout_mock, 'Tor is using a type of authentication we do not recognize...\n\n telepathy')
- authenticate_mock.side_effect = stem.connection.IncorrectPassword('password rejected')
+ authenticate_mock.side_effect = coro_func_raising_exc(stem.connection.IncorrectPassword('password rejected'))
self._assert_authenticate_fails_with(control_socket, stdout_mock, 'Incorrect password')
- authenticate_mock.side_effect = stem.connection.UnreadableCookieFile('permission denied', '/tmp/my_cookie', False)
+ authenticate_mock.side_effect = coro_func_raising_exc(stem.connection.UnreadableCookieFile('permission denied', '/tmp/my_cookie', False))
self._assert_authenticate_fails_with(control_socket, stdout_mock, "We were unable to read tor's authentication cookie...\n\n Path: /tmp/my_cookie\n Issue: permission denied")
- authenticate_mock.side_effect = stem.connection.OpenAuthRejected('crazy failure')
+ authenticate_mock.side_effect = coro_func_raising_exc(stem.connection.OpenAuthRejected('crazy failure'))
self._assert_authenticate_fails_with(control_socket, stdout_mock, 'Unable to authenticate: crazy failure')
def _assert_authenticate_fails_with(self, control_socket, stdout_mock, msg):
diff --git a/test/unit/control/controller.py b/test/unit/control/controller.py
index c0a07e2a..d09b5ca8 100644
--- a/test/unit/control/controller.py
+++ b/test/unit/control/controller.py
@@ -3,6 +3,7 @@ Unit tests for the stem.control module. The module's primarily exercised via
integ tests, but a few bits lend themselves to unit testing.
"""
+import asyncio
import datetime
import io
import unittest
@@ -20,6 +21,11 @@ from stem import ControllerError, DescriptorUnavailable, InvalidArguments, Inval
from stem.control import MALFORMED_EVENTS, _parse_circ_path, Listener, Controller, EventType
from stem.response import ControlMessage
from stem.exit_policy import ExitPolicy
+from test.unit.util.asynchronous import (
+ async_test,
+ coro_func_raising_exc,
+ coro_func_returning_value,
+)
NS_DESC = 'r %s %s u5lTXJKGsLKufRLnSyVqT7TdGYw 2012-12-30 22:02:49 77.223.43.54 9001 0\ns Fast Named Running Stable Valid\nw Bandwidth=75'
TEST_TIMESTAMP = 12345
@@ -36,8 +42,9 @@ class TestControl(unittest.TestCase):
# When initially constructing a controller we need to suppress msg, so our
# constructor's SETEVENTS requests pass.
- with patch('stem.control.BaseController.msg', Mock()):
+ with patch('stem.control.BaseController.msg', Mock(side_effect = coro_func_returning_value(None))):
self.controller = Controller(socket)
+ self.async_controller = self.controller._async_controller
self.circ_listener = Mock()
self.controller.add_event_listener(self.circ_listener, EventType.CIRC)
@@ -59,18 +66,24 @@ class TestControl(unittest.TestCase):
for event in stem.control.EventType:
self.assertTrue(stem.control.event_description(event) is not None)
- @patch('stem.control.Controller.msg')
+ @patch('stem.control.AsyncController.msg')
def test_get_info(self, msg_mock):
- msg_mock.return_value = ControlMessage.from_str('250-hello=hi right back!\r\n250 OK\r\n', 'GETINFO')
+ message = ControlMessage.from_str('250-hello=hi right back!\r\n250 OK\r\n', 'GETINFO')
+ msg_mock.side_effect = coro_func_returning_value(message)
self.assertEqual('hi right back!', self.controller.get_info('hello'))
- @patch('stem.control.Controller.msg')
- def test_get_info_address_caching(self, msg_mock):
- msg_mock.return_value = ControlMessage.from_str('551 Address unknown\r\n')
+ @patch('stem.control.AsyncController.msg')
+ @async_test
+ async def test_get_info_address_caching(self, msg_mock):
+ def set_message(*args):
+ message = ControlMessage.from_str(*args)
+ msg_mock.side_effect = coro_func_returning_value(message)
- self.assertEqual(None, self.controller._last_address_exc)
+ set_message('551 Address unknown\r\n')
+
+ self.assertEqual(None, self.async_controller._last_address_exc)
self.assertRaisesWith(stem.OperationFailed, 'Address unknown', self.controller.get_info, 'address')
- self.assertEqual('Address unknown', str(self.controller._last_address_exc))
+ self.assertEqual('Address unknown', str(self.async_controller._last_address_exc))
self.assertEqual(1, msg_mock.call_count)
# now that we have a cached failure we should provide that back
@@ -80,27 +93,28 @@ class TestControl(unittest.TestCase):
# invalidates the cache, transitioning from no address to having one
- msg_mock.return_value = ControlMessage.from_str('250-address=17.2.89.80\r\n250 OK\r\n', 'GETINFO')
+ set_message('250-address=17.2.89.80\r\n250 OK\r\n', 'GETINFO')
self.assertRaisesWith(stem.OperationFailed, 'Address unknown', self.controller.get_info, 'address')
- self.controller._handle_event(ControlMessage.from_str('650 STATUS_SERVER NOTICE EXTERNAL_ADDRESS ADDRESS=17.2.89.80 METHOD=DIRSERV\r\n'))
+ await self.async_controller._handle_event(ControlMessage.from_str('650 STATUS_SERVER NOTICE EXTERNAL_ADDRESS ADDRESS=17.2.89.80 METHOD=DIRSERV\r\n'))
self.assertEqual('17.2.89.80', self.controller.get_info('address'))
# invalidates the cache, transitioning from one address to another
- msg_mock.return_value = ControlMessage.from_str('250-address=80.89.2.17\r\n250 OK\r\n', 'GETINFO')
+ set_message('250-address=80.89.2.17\r\n250 OK\r\n', 'GETINFO')
self.assertEqual('17.2.89.80', self.controller.get_info('address'))
- self.controller._handle_event(ControlMessage.from_str('650 STATUS_SERVER NOTICE EXTERNAL_ADDRESS ADDRESS=80.89.2.17 METHOD=DIRSERV\r\n'))
+ await self.async_controller._handle_event(ControlMessage.from_str('650 STATUS_SERVER NOTICE EXTERNAL_ADDRESS ADDRESS=80.89.2.17 METHOD=DIRSERV\r\n'))
self.assertEqual('80.89.2.17', self.controller.get_info('address'))
- @patch('stem.control.Controller.msg')
- @patch('stem.control.Controller.get_conf')
+ @patch('stem.control.AsyncController.msg')
+ @patch('stem.control.AsyncController.get_conf')
def test_get_info_without_fingerprint(self, get_conf_mock, msg_mock):
- msg_mock.return_value = ControlMessage.from_str('551 Not running in server mode\r\n')
+ message = ControlMessage.from_str('551 Not running in server mode\r\n')
+ msg_mock.side_effect = coro_func_returning_value(message)
get_conf_mock.return_value = None
- self.assertEqual(None, self.controller._last_fingerprint_exc)
+ self.assertEqual(None, self.async_controller._last_fingerprint_exc)
self.assertRaisesWith(stem.OperationFailed, 'Not running in server mode', self.controller.get_info, 'fingerprint')
- self.assertEqual('Not running in server mode', str(self.controller._last_fingerprint_exc))
+ self.assertEqual('Not running in server mode', str(self.async_controller._last_fingerprint_exc))
self.assertEqual(1, msg_mock.call_count)
# now that we have a cached failure we should provide that back
@@ -114,7 +128,7 @@ class TestControl(unittest.TestCase):
self.assertRaisesWith(stem.OperationFailed, 'Not running in server mode', self.controller.get_info, 'fingerprint')
self.assertEqual(2, msg_mock.call_count)
- @patch('stem.control.Controller.get_info')
+ @patch('stem.control.AsyncController.get_info')
def test_get_version(self, get_info_mock):
"""
Exercises the get_version() method.
@@ -124,7 +138,7 @@ class TestControl(unittest.TestCase):
# Use one version for first check.
version_2_1 = '0.2.1.32'
version_2_1_object = stem.version.Version(version_2_1)
- get_info_mock.return_value = version_2_1
+ get_info_mock.side_effect = coro_func_returning_value(version_2_1)
# Return a version with a cold cache.
self.assertEqual(version_2_1_object, self.controller.get_version())
@@ -132,23 +146,23 @@ class TestControl(unittest.TestCase):
# Use a different version for second check.
version_2_2 = '0.2.2.39'
version_2_2_object = stem.version.Version(version_2_2)
- get_info_mock.return_value = version_2_2
+ get_info_mock.side_effect = coro_func_returning_value(version_2_2)
# Return a version with a hot cache, so it will be the old version.
self.assertEqual(version_2_1_object, self.controller.get_version())
# Turn off caching.
- self.controller._is_caching_enabled = False
+ self.async_controller._is_caching_enabled = False
# Return a version without caching, so it will be the new version.
self.assertEqual(version_2_2_object, self.controller.get_version())
# Spec says the getinfo response may optionally be prefixed by 'Tor '. In
# practice it doesn't but we should accept that.
- get_info_mock.return_value = 'Tor 0.2.1.32'
+ get_info_mock.side_effect = coro_func_returning_value('Tor 0.2.1.32')
self.assertEqual(version_2_1_object, self.controller.get_version())
# Raise an exception in the get_info() call.
- get_info_mock.side_effect = InvalidArguments
+ get_info_mock.side_effect = coro_func_raising_exc(InvalidArguments)
# Get a default value when the call fails.
self.assertEqual(
@@ -161,22 +175,24 @@ class TestControl(unittest.TestCase):
# Give a bad version. The stem.version.Version ValueError should bubble up.
version_A_42 = '0.A.42.spam'
- get_info_mock.return_value = version_A_42
- get_info_mock.side_effect = None
+ get_info_mock.side_effect = coro_func_returning_value(version_A_42)
self.assertRaises(ValueError, self.controller.get_version)
finally:
# Turn caching back on before we leave.
self.controller._is_caching_enabled = True
- @patch('stem.control.Controller.get_info')
+ @patch('stem.control.AsyncController.get_info')
def test_get_exit_policy(self, get_info_mock):
"""
Exercises the get_exit_policy() method.
"""
- get_info_mock.side_effect = lambda param, default = None: {
- 'exit-policy/full': 'reject *:25,reject *:119,reject *:135-139,reject *:445,reject *:563,reject *:1214,reject *:4661-4666,reject *:6346-6429,reject *:6699,reject *:6881-6999,accept *:*',
- }[param]
+ async def get_info_mock_side_effect(param, default = None):
+ return {
+ 'exit-policy/full': 'reject *:25,reject *:119,reject *:135-139,reject *:445,reject *:563,reject *:1214,reject *:4661-4666,reject *:6346-6429,reject *:6699,reject *:6881-6999,accept *:*',
+ }[param]
+
+ get_info_mock.side_effect = get_info_mock_side_effect
expected = ExitPolicy(
'reject *:25',
@@ -194,8 +210,8 @@ class TestControl(unittest.TestCase):
self.assertEqual(str(expected), str(self.controller.get_exit_policy()))
- @patch('stem.control.Controller.get_info')
- @patch('stem.control.Controller.get_conf')
+ @patch('stem.control.AsyncController.get_info')
+ @patch('stem.control.AsyncController.get_conf')
def test_get_ports(self, get_conf_mock, get_info_mock):
"""
Exercises the get_ports() and get_listeners() methods.
@@ -204,12 +220,15 @@ class TestControl(unittest.TestCase):
# Exercise as an old version of tor that doesn't support the 'GETINFO
# net/listeners/*' options.
- get_info_mock.side_effect = InvalidArguments
+ get_info_mock.side_effect = coro_func_raising_exc(InvalidArguments)
+
+ async def get_conf_mock_side_effect(param, **kwargs):
+ return {
+ 'ControlPort': '9050',
+ 'ControlListenAddress': ['127.0.0.1'],
+ }[param]
- get_conf_mock.side_effect = lambda param, *args, **kwargs: {
- 'ControlPort': '9050',
- 'ControlListenAddress': ['127.0.0.1'],
- }[param]
+ get_conf_mock.side_effect = get_conf_mock_side_effect
self.assertEqual([('127.0.0.1', 9050)], self.controller.get_listeners(Listener.CONTROL))
self.assertEqual([9050], self.controller.get_ports(Listener.CONTROL))
@@ -217,10 +236,13 @@ class TestControl(unittest.TestCase):
# non-local addresss
- get_conf_mock.side_effect = lambda param, *args, **kwargs: {
- 'ControlPort': '9050',
- 'ControlListenAddress': ['27.4.4.1'],
- }[param]
+ async def get_conf_mock_side_effect(param, **kwargs):
+ return {
+ 'ControlPort': '9050',
+ 'ControlListenAddress': ['27.4.4.1'],
+ }[param]
+
+ get_conf_mock.side_effect = get_conf_mock_side_effect
self.assertEqual([('27.4.4.1', 9050)], self.controller.get_listeners(Listener.CONTROL))
self.assertEqual([], self.controller.get_ports(Listener.CONTROL))
@@ -228,8 +250,8 @@ class TestControl(unittest.TestCase):
# exercise via the GETINFO option
- get_info_mock.side_effect = None
- get_info_mock.return_value = '"127.0.0.1:1112" "127.0.0.1:1114"'
+ listeners = '"127.0.0.1:1112" "127.0.0.1:1114"'
+ get_info_mock.side_effect = coro_func_returning_value(listeners)
self.assertEqual(
[('127.0.0.1', 1112), ('127.0.0.1', 1114)],
@@ -241,15 +263,16 @@ class TestControl(unittest.TestCase):
# with all localhost addresses, including a couple that aren't
- get_info_mock.side_effect = None
- get_info_mock.return_value = '"27.4.4.1:1113" "127.0.0.5:1114" "0.0.0.0:1115" "[::]:1116" "[::1]:1117" "[10::]:1118"'
+ listeners = '"27.4.4.1:1113" "127.0.0.5:1114" "0.0.0.0:1115" "[::]:1116" "[::1]:1117" "[10::]:1118"'
+ get_info_mock.side_effect = coro_func_returning_value(listeners)
self.assertEqual([1114, 1115, 1116, 1117], self.controller.get_ports(Listener.OR))
self.controller.clear_cache()
# IPv6 address
- get_info_mock.return_value = '"0.0.0.0:9001" "[fe80:0000:0000:0000:0202:b3ff:fe1e:8329]:9001"'
+ listeners = '"0.0.0.0:9001" "[fe80:0000:0000:0000:0202:b3ff:fe1e:8329]:9001"'
+ get_info_mock.side_effect = coro_func_returning_value(listeners)
self.assertEqual(
[('0.0.0.0', 9001), ('fe80:0000:0000:0000:0202:b3ff:fe1e:8329', 9001)],
@@ -259,25 +282,28 @@ class TestControl(unittest.TestCase):
# unix socket file
self.controller.clear_cache()
- get_info_mock.return_value = '"unix:/tmp/tor/socket"'
+ get_info_mock.side_effect = coro_func_returning_value('"unix:/tmp/tor/socket"')
self.assertEqual([], self.controller.get_listeners(Listener.CONTROL))
self.assertEqual([], self.controller.get_ports(Listener.CONTROL))
- @patch('stem.control.Controller.get_info')
+ @patch('stem.control.AsyncController.get_info')
@patch('time.time', Mock(return_value = 1410723598.276578))
def test_get_accounting_stats(self, get_info_mock):
"""
Exercises the get_accounting_stats() method.
"""
- get_info_mock.side_effect = lambda param, **kwargs: {
- 'accounting/enabled': '1',
- 'accounting/hibernating': 'awake',
- 'accounting/interval-end': '2014-09-14 19:41:00',
- 'accounting/bytes': '4837 2050',
- 'accounting/bytes-left': '102944 7440',
- }[param]
+ async def get_info_mock_side_effect(param, **kwargs):
+ return {
+ 'accounting/enabled': '1',
+ 'accounting/hibernating': 'awake',
+ 'accounting/interval-end': '2014-09-14 19:41:00',
+ 'accounting/bytes': '4837 2050',
+ 'accounting/bytes-left': '102944 7440',
+ }[param]
+
+ get_info_mock.side_effect = get_info_mock_side_effect
expected = stem.control.AccountingStats(
1410723598.276578,
@@ -290,7 +316,7 @@ class TestControl(unittest.TestCase):
self.assertEqual(expected, self.controller.get_accounting_stats())
- get_info_mock.side_effect = ControllerError('nope, too bad')
+ get_info_mock.side_effect = coro_func_raising_exc(ControllerError('nope, too bad'))
self.assertRaises(ControllerError, self.controller.get_accounting_stats)
self.assertEqual('my default', self.controller.get_accounting_stats('my default'))
@@ -303,7 +329,7 @@ class TestControl(unittest.TestCase):
# use the handy mocked protocolinfo response
protocolinfo_msg = ControlMessage.from_str('250-PROTOCOLINFO 1\r\n250 OK\r\n', 'PROTOCOLINFO')
- get_protocolinfo_mock.return_value = protocolinfo_msg
+ get_protocolinfo_mock.side_effect = coro_func_returning_value(protocolinfo_msg)
# compare the str representation of these object, because the class
# does not have, nor need, a direct comparison operator
@@ -315,7 +341,7 @@ class TestControl(unittest.TestCase):
# raise an exception in the stem.connection.get_protocolinfo() call
- get_protocolinfo_mock.side_effect = ProtocolError
+ get_protocolinfo_mock.side_effect = coro_func_raising_exc(ProtocolError)
# get a default value when the call fails
@@ -338,7 +364,7 @@ class TestControl(unittest.TestCase):
self.assertEqual(123, self.controller.get_user(123))
@patch('stem.socket.ControlSocket.is_localhost', Mock(return_value = True))
- @patch('stem.control.Controller.get_info', Mock(return_value = 'atagar'))
+ @patch('stem.control.AsyncController.get_info', Mock(side_effect = coro_func_returning_value('atagar')))
def test_get_user_by_getinfo(self):
"""
Exercise the get_user() resolution via its getinfo option.
@@ -366,7 +392,7 @@ class TestControl(unittest.TestCase):
self.assertEqual(123, self.controller.get_pid(123))
@patch('stem.socket.ControlSocket.is_localhost', Mock(return_value = True))
- @patch('stem.control.Controller.get_info', Mock(return_value = '321'))
+ @patch('stem.control.AsyncController.get_info', Mock(side_effect = coro_func_returning_value('321')))
def test_get_pid_by_getinfo(self):
"""
Exercise the get_pid() resolution via its getinfo option.
@@ -375,14 +401,14 @@ class TestControl(unittest.TestCase):
self.assertEqual(321, self.controller.get_pid())
@patch('stem.socket.ControlSocket.is_localhost', Mock(return_value = True))
- @patch('stem.control.Controller.get_conf')
+ @patch('stem.control.AsyncController.get_conf')
@patch('stem.control.open', create = True)
def test_get_pid_by_pid_file(self, open_mock, get_conf_mock):
"""
Exercise the get_pid() resolution via a PidFile.
"""
- get_conf_mock.return_value = '/tmp/pid_file'
+ get_conf_mock.side_effect = coro_func_returning_value('/tmp/pid_file')
open_mock.return_value = io.BytesIO(b'432')
self.assertEqual(432, self.controller.get_pid())
@@ -397,25 +423,25 @@ class TestControl(unittest.TestCase):
self.assertEqual(432, self.controller.get_pid())
- @patch('stem.control.Controller.get_version', Mock(return_value = stem.version.Version('0.5.0.14')))
+ @patch('stem.control.AsyncController.get_version', Mock(side_effect = coro_func_returning_value(stem.version.Version('0.5.0.14'))))
@patch('stem.socket.ControlSocket.is_localhost', Mock(return_value = False))
- @patch('stem.control.Controller.get_info')
+ @patch('stem.control.AsyncController.get_info')
@patch('time.time', Mock(return_value = 1000.0))
def test_get_uptime_by_getinfo(self, getinfo_mock):
"""
Exercise the get_uptime() resolution via a GETINFO query.
"""
- getinfo_mock.return_value = '321'
+ getinfo_mock.side_effect = coro_func_returning_value('321')
self.assertEqual(321.0, self.controller.get_uptime())
self.controller.clear_cache()
- getinfo_mock.return_value = 'abc'
+ getinfo_mock.side_effect = coro_func_returning_value('abc')
self.assertRaisesWith(ValueError, "'GETINFO uptime' did not provide a valid numeric response: abc", self.controller.get_uptime)
@patch('stem.socket.ControlSocket.is_localhost', Mock(return_value = True))
- @patch('stem.control.Controller.get_version', Mock(return_value = stem.version.Version('0.1.0.14')))
- @patch('stem.control.Controller.get_pid', Mock(return_value = '12'))
+ @patch('stem.control.AsyncController.get_version', Mock(side_effect = coro_func_returning_value(stem.version.Version('0.1.0.14'))))
+ @patch('stem.control.AsyncController.get_pid', Mock(side_effect = coro_func_returning_value('12')))
@patch('stem.util.system.start_time', Mock(return_value = 5000.0))
@patch('time.time', Mock(return_value = 5200.0))
def test_get_uptime_by_process(self):
@@ -425,7 +451,7 @@ class TestControl(unittest.TestCase):
self.assertEqual(200.0, self.controller.get_uptime())
- @patch('stem.control.Controller.get_info')
+ @patch('stem.control.AsyncController.get_info')
def test_get_network_status_for_ourselves(self, get_info_mock):
"""
Exercises the get_network_status() method for getting our own relay.
@@ -433,7 +459,7 @@ class TestControl(unittest.TestCase):
# when there's an issue getting our fingerprint
- get_info_mock.side_effect = ControllerError('nope, too bad')
+ get_info_mock.side_effect = coro_func_raising_exc(ControllerError('nope, too bad'))
exc_msg = 'Unable to determine our own fingerprint: nope, too bad'
self.assertRaisesWith(ControllerError, exc_msg, self.controller.get_network_status)
@@ -443,25 +469,29 @@ class TestControl(unittest.TestCase):
desc = NS_DESC % ('moria1', '/96bKo4soysolMgKn5Hex2nyFSY')
- get_info_mock.side_effect = lambda param, **kwargs: {
- 'fingerprint': '9695DFC35FFEB861329B9F1AB04C46397020CE31',
- 'ns/id/9695DFC35FFEB861329B9F1AB04C46397020CE31': desc,
- }[param]
+ async def get_info_mock_side_effect(param, **kwargs):
+ return {
+ 'fingerprint': '9695DFC35FFEB861329B9F1AB04C46397020CE31',
+ 'ns/id/9695DFC35FFEB861329B9F1AB04C46397020CE31': desc,
+ }[param]
+
+ get_info_mock.side_effect = get_info_mock_side_effect
self.assertEqual(stem.descriptor.router_status_entry.RouterStatusEntryV3(desc), self.controller.get_network_status())
- @patch('stem.control.Controller.get_info')
+ @patch('stem.control.AsyncController.get_info')
def test_get_network_status_when_unavailable(self, get_info_mock):
"""
Exercises the get_network_status() method.
"""
- get_info_mock.side_effect = InvalidArguments(None, 'GETINFO request contained unrecognized keywords: ns/id/5AC9C5AA75BA1F18D8459B326B4B8111A856D290')
+ exc = InvalidArguments(None, 'GETINFO request contained unrecognized keywords: ns/id/5AC9C5AA75BA1F18D8459B326B4B8111A856D290')
+ get_info_mock.side_effect = coro_func_raising_exc(exc)
exc_msg = "Tor was unable to provide the descriptor for '5AC9C5AA75BA1F18D8459B326B4B8111A856D290'"
self.assertRaisesWith(DescriptorUnavailable, exc_msg, self.controller.get_network_status, '5AC9C5AA75BA1F18D8459B326B4B8111A856D290')
- @patch('stem.control.Controller.get_info')
+ @patch('stem.control.AsyncController.get_info')
def test_get_network_status(self, get_info_mock):
"""
Exercises the get_network_status() method.
@@ -476,7 +506,7 @@ class TestControl(unittest.TestCase):
# always return the same router status entry
- get_info_mock.return_value = desc
+ get_info_mock.side_effect = coro_func_returning_value(desc)
# pretend to get the router status entry with its name
@@ -494,7 +524,7 @@ class TestControl(unittest.TestCase):
# raise an exception in the get_info() call
- get_info_mock.side_effect = InvalidArguments
+ get_info_mock.side_effect = coro_func_raising_exc(InvalidArguments)
# get a default value when the call fails
@@ -507,22 +537,28 @@ class TestControl(unittest.TestCase):
self.assertRaises(InvalidArguments, self.controller.get_network_status, nickname)
- @patch('stem.control.Controller.is_authenticated', Mock(return_value = True))
- @patch('stem.control.Controller._attach_listeners', Mock(return_value = ([], [])))
- @patch('stem.control.Controller.get_version')
- def test_add_event_listener(self, get_version_mock):
+ @patch('stem.control.AsyncController.is_authenticated', Mock(return_value = True))
+ @patch('stem.control.AsyncController._attach_listeners')
+ @patch('stem.control.AsyncController.get_version')
+ def test_add_event_listener(self, get_version_mock, attach_listeners_mock):
"""
Exercises the add_event_listener and remove_event_listener methods.
"""
+ attach_listeners_mock.side_effect = coro_func_returning_value(([], []))
+
+ def set_version(version_str):
+ version = stem.version.Version(version_str)
+ get_version_mock.side_effect = coro_func_returning_value(version)
+
# set up for failure to create any events
- get_version_mock.return_value = stem.version.Version('0.1.0.14')
+ set_version('0.1.0.14')
self.assertRaises(InvalidRequest, self.controller.add_event_listener, Mock(), EventType.BW)
# set up to only fail newer events
- get_version_mock.return_value = stem.version.Version('0.2.0.35')
+ set_version('0.2.0.35')
# EventType.BW is one of the earliest events
@@ -551,7 +587,7 @@ class TestControl(unittest.TestCase):
event thread.
"""
- self.circ_listener.side_effect = ValueError('boom')
+ self.circ_listener.side_effect = coro_func_raising_exc(ValueError('boom'))
self._emit_event(CIRC_EVENT)
self.circ_listener.assert_called_once_with(CIRC_EVENT)
@@ -582,10 +618,10 @@ class TestControl(unittest.TestCase):
self._emit_event(BW_EVENT)
self.bw_listener.assert_called_once_with(BW_EVENT)
- @patch('stem.control.Controller.get_version', Mock(return_value = stem.version.Version('0.5.0.14')))
- @patch('stem.control.Controller.msg', Mock(return_value = ControlMessage.from_str('250 OK\r\n')))
- @patch('stem.control.Controller.add_event_listener', Mock())
- @patch('stem.control.Controller.remove_event_listener', Mock())
+ @patch('stem.control.AsyncController.get_version', Mock(side_effect = coro_func_returning_value(stem.version.Version('0.5.0.14'))))
+ @patch('stem.control.AsyncController.msg', Mock(side_effect = coro_func_returning_value(ControlMessage.from_str('250 OK\r\n'))))
+ @patch('stem.control.AsyncController.add_event_listener', Mock(side_effect = coro_func_returning_value(None)))
+ @patch('stem.control.AsyncController.remove_event_listener', Mock(side_effect = coro_func_returning_value(None)))
def test_timeout(self):
"""
Methods that have an 'await' argument also have an optional timeout. Check
@@ -607,8 +643,9 @@ class TestControl(unittest.TestCase):
)
response = ''.join(['%s\r\n' % ' '.join(entry) for entry in valid_streams])
+ get_info_mock = Mock(side_effect = coro_func_returning_value(response))
- with patch('stem.control.Controller.get_info', Mock(return_value = response)):
+ with patch('stem.control.AsyncController.get_info', get_info_mock):
streams = self.controller.get_streams()
self.assertEqual(len(valid_streams), len(streams))
@@ -627,8 +664,9 @@ class TestControl(unittest.TestCase):
# instance, it's already open).
response = stem.response.ControlMessage.from_str('555 Connection is not managed by controller.\r\n')
+ msg_mock = Mock(side_effect = coro_func_returning_value(response))
- with patch('stem.control.Controller.msg', Mock(return_value = response)):
+ with patch('stem.control.AsyncController.msg', msg_mock):
self.assertRaises(UnsatisfiableRequest, self.controller.attach_stream, 'stream_id', 'circ_id')
def test_parse_circ_path(self):
@@ -671,7 +709,7 @@ class TestControl(unittest.TestCase):
for test_input in malformed_inputs:
self.assertRaises(ProtocolError, _parse_circ_path, test_input)
- @patch('stem.control.Controller.get_conf')
+ @patch('stem.control.AsyncController.get_conf')
def test_get_effective_rate(self, get_conf_mock):
"""
Exercise the get_effective_rate() method.
@@ -679,18 +717,21 @@ class TestControl(unittest.TestCase):
# check default if nothing was set
- get_conf_mock.side_effect = lambda param, *args, **kwargs: {
- 'BandwidthRate': '1073741824',
- 'BandwidthBurst': '1073741824',
- 'RelayBandwidthRate': '0',
- 'RelayBandwidthBurst': '0',
- 'MaxAdvertisedBandwidth': '1073741824',
- }[param]
+ async def get_conf_mock_side_effect(param, **kwargs):
+ return {
+ 'BandwidthRate': '1073741824',
+ 'BandwidthBurst': '1073741824',
+ 'RelayBandwidthRate': '0',
+ 'RelayBandwidthBurst': '0',
+ 'MaxAdvertisedBandwidth': '1073741824',
+ }[param]
+
+ get_conf_mock.side_effect = get_conf_mock_side_effect
self.assertEqual(1073741824, self.controller.get_effective_rate())
self.assertEqual(1073741824, self.controller.get_effective_rate(burst = True))
- get_conf_mock.side_effect = ControllerError('nope, too bad')
+ get_conf_mock.side_effect = coro_func_raising_exc(ControllerError('nope, too bad'))
self.assertRaises(ControllerError, self.controller.get_effective_rate)
self.assertEqual('my_default', self.controller.get_effective_rate('my_default'))
@@ -705,18 +746,19 @@ class TestControl(unittest.TestCase):
# with its work is to join on the thread.
with patch('time.time', Mock(return_value = TEST_TIMESTAMP)):
- with patch('stem.control.Controller.is_alive') as is_alive_mock:
+ with patch('stem.control.AsyncController.is_alive') as is_alive_mock:
is_alive_mock.return_value = True
- self.controller._create_loop_tasks()
+ loop = self.controller._asyncio_loop
+ asyncio.run_coroutine_threadsafe(self.async_controller._event_loop(), loop)
try:
# Converting an event back into an uncast ControlMessage, then feeding it
# into our controller's event queue.
uncast_event = ControlMessage.from_str(event.raw_content())
- self.controller._event_queue.put(uncast_event)
- self.controller._event_notice.set()
- self.controller._event_queue.join() # block until the event is consumed
+ event_queue = self.async_controller._event_queue
+ asyncio.run_coroutine_threadsafe(event_queue.put(uncast_event), loop).result()
+ asyncio.run_coroutine_threadsafe(event_queue.join(), loop).result() # block until the event is consumed
finally:
is_alive_mock.return_value = False
- self.controller._close()
+ asyncio.run_coroutine_threadsafe(self.async_controller._close(), loop).result()
diff --git a/test/unit/response/control_message.py b/test/unit/response/control_message.py
index abf5debf..414dcf63 100644
--- a/test/unit/response/control_message.py
+++ b/test/unit/response/control_message.py
@@ -126,7 +126,7 @@ class TestControlMessage(unittest.TestCase):
# replace the CRLF for the line
infonames_lines[index] = line.rstrip('\r\n') + '\n'
test_socket_file = io.BytesIO(stem.util.str_tools._to_bytes(''.join(infonames_lines)))
- self.assertRaises(stem.ProtocolError, stem.socket.recv_message, test_socket_file)
+ self.assertRaises(stem.ProtocolError, stem.socket.recv_message_from_bytes_io, test_socket_file)
# puts the CRLF back
infonames_lines[index] = infonames_lines[index].rstrip('\n') + '\r\n'
@@ -151,8 +151,8 @@ class TestControlMessage(unittest.TestCase):
# - this is part of the message prefix
# - this is disrupting the line ending
- self.assertRaises(stem.ProtocolError, stem.socket.recv_message, io.BytesIO(stem.util.str_tools._to_bytes(removal_test_input)))
- self.assertRaises(stem.ProtocolError, stem.socket.recv_message, io.BytesIO(stem.util.str_tools._to_bytes(replacement_test_input)))
+ self.assertRaises(stem.ProtocolError, stem.socket.recv_message_from_bytes_io, io.BytesIO(stem.util.str_tools._to_bytes(removal_test_input)))
+ self.assertRaises(stem.ProtocolError, stem.socket.recv_message_from_bytes_io, io.BytesIO(stem.util.str_tools._to_bytes(replacement_test_input)))
else:
# otherwise the data will be malformed, but this goes undetected
self._assert_message_parses(removal_test_input)
@@ -166,7 +166,7 @@ class TestControlMessage(unittest.TestCase):
control_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
control_socket_file = control_socket.makefile()
- self.assertRaises(stem.SocketClosed, stem.socket.recv_message, control_socket_file)
+ self.assertRaises(stem.SocketClosed, stem.socket.recv_message_from_bytes_io, control_socket_file)
def test_equality(self):
msg = stem.response.ControlMessage.from_str(EVENT_BW)
@@ -200,7 +200,7 @@ class TestControlMessage(unittest.TestCase):
stem.response.ControlMessage for the given input
"""
- message = stem.socket.recv_message(io.BytesIO(stem.util.str_tools._to_bytes(controller_reply)))
+ message = stem.socket.recv_message_from_bytes_io(io.BytesIO(stem.util.str_tools._to_bytes(controller_reply)))
# checks that the raw_content equals the input value
self.assertEqual(controller_reply, message.raw_content())
1
0
[stem/master] Refactor defining a thread for the asynchronous controller
by atagar@torproject.org 16 Jul '20
by atagar@torproject.org 16 Jul '20
16 Jul '20
commit 67f2bc72489e48d7ebe07945b37b79941d046d1f
Author: Illia Volochii <illia.volochii(a)gmail.com>
Date: Mon Apr 27 18:50:10 2020 +0300
Refactor defining a thread for the asynchronous controller
---
stem/control.py | 32 ++++++++++++++++++++------------
1 file changed, 20 insertions(+), 12 deletions(-)
diff --git a/stem/control.py b/stem/control.py
index d3e074b7..20173a7a 100644
--- a/stem/control.py
+++ b/stem/control.py
@@ -3905,6 +3905,21 @@ class AsyncController(_ControllerClassMethodMixin, BaseController):
return (set_events, failed_events)
+class _AsyncControllerThread(threading.Thread):
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, *kwargs)
+ self.loop = asyncio.new_event_loop()
+ self.setDaemon(True)
+
+ def run(self):
+ self.loop.run_forever()
+
+ def join(self, timeout = None):
+ self.loop.call_soon_threadsafe(self.loop.stop)
+ super().join(timeout)
+ self.loop.close()
+
+
class Controller(_ControllerClassMethodMixin, _BaseControllerSocketMixin):
@classmethod
def from_port(cls: Type, address: str = '127.0.0.1', port: Union[int, str] = 'default') -> 'stem.control.Controller':
@@ -3919,14 +3934,9 @@ class Controller(_ControllerClassMethodMixin, _BaseControllerSocketMixin):
return instance
def __init__(self, control_socket: 'stem.socket.ControlSocket', is_authenticated: bool = False) -> None:
- self._asyncio_loop = asyncio.new_event_loop()
-
- self._asyncio_thread = threading.Thread(
- target=self._asyncio_loop.run_forever,
- name='async_controller',
- )
- self._asyncio_thread.setDaemon(True)
- self._asyncio_thread.start()
+ self._async_controller_thread = _AsyncControllerThread()
+ self._async_controller_thread.start()
+ self._asyncio_loop = self._async_controller_thread.loop
self._async_controller = self._init_async_controller(control_socket, is_authenticated)
self._socket = self._async_controller._socket
@@ -3968,10 +3978,8 @@ class Controller(_ControllerClassMethodMixin, _BaseControllerSocketMixin):
def close(self) -> None:
self._execute_async_method('close')
- self._asyncio_loop.call_soon_threadsafe(self._asyncio_loop.stop)
- if self._asyncio_thread.is_alive():
- self._asyncio_thread.join()
- self._asyncio_loop.close()
+ if self._async_controller_thread.is_alive():
+ self._async_controller_thread.join()
def get_latest_heartbeat(self) -> float:
return self._async_controller.get_latest_heartbeat()
1
0
commit 28c9dde029f0a8ad0b69e209fac73a32735e1496
Author: Illia Volochii <illia.volochii(a)gmail.com>
Date: Mon Apr 27 19:58:06 2020 +0300
Fix tests
---
test/unit/connection/connect.py | 31 ++++++++++++++++++++++++-------
1 file changed, 24 insertions(+), 7 deletions(-)
diff --git a/test/unit/connection/connect.py b/test/unit/connection/connect.py
index aa91736b..8ba2770c 100644
--- a/test/unit/connection/connect.py
+++ b/test/unit/connection/connect.py
@@ -1,7 +1,7 @@
"""
Unit tests for the stem.connection.connect function.
"""
-
+import contextlib
import io
import unittest
@@ -47,8 +47,11 @@ class TestConnect(unittest.TestCase):
@patch('os.path.exists', Mock(return_value = False))
@patch('stem.connection._connect_auth', Mock())
def test_getting_a_control_port(self, port_mock):
+ port_connect_mock = port_mock.return_value.connect
+ port_connect_mock.side_effect = coro_func_returning_value(None)
stem.connection.connect()
port_mock.assert_called_once_with('127.0.0.1', 9051)
+ port_connect_mock.assert_called_once()
port_mock.reset_mock()
stem.connection.connect(control_port = ('255.0.0.10', 80), control_socket = None)
@@ -58,8 +61,11 @@ class TestConnect(unittest.TestCase):
@patch('os.path.exists', Mock(return_value = True))
@patch('stem.connection._connect_auth', Mock())
def test_getting_a_control_socket(self, socket_mock):
+ socket_connect_mock = socket_mock.return_value.connect
+ socket_connect_mock.side_effect = coro_func_returning_value(None)
stem.connection.connect()
socket_mock.assert_called_once_with('/var/run/tor/control')
+ socket_connect_mock.assert_called_once()
socket_mock.reset_mock()
stem.connection.connect(control_port = None, control_socket = '/tmp/my_socket')
@@ -90,11 +96,12 @@ class TestConnect(unittest.TestCase):
authenticate_mock.side_effect = coro_func_returning_value(None)
control_socket = Mock()
- stem.connection._connect_auth(control_socket, None, False, None, None)
- authenticate_mock.assert_called_with(control_socket, None, None)
- authenticate_mock.reset_mock()
+ with self._get_thread() as thread:
+ stem.connection._connect_auth(control_socket, None, False, None, None, thread)
+ authenticate_mock.assert_called_with(control_socket, None, None)
+ authenticate_mock.reset_mock()
- stem.connection._connect_auth(control_socket, 's3krit!!!', False, '/my/chroot', None)
+ stem.connection._connect_auth(control_socket, 's3krit!!!', False, '/my/chroot', None, thread)
authenticate_mock.assert_called_with(control_socket, 's3krit!!!', '/my/chroot')
@patch('getpass.getpass')
@@ -113,7 +120,8 @@ class TestConnect(unittest.TestCase):
authenticate_mock.side_effect = authenticate_mock_func
getpass_mock.return_value = 'my_password'
- stem.connection._connect_auth(control_socket, None, True, None, None)
+ with self._get_thread() as thread:
+ stem.connection._connect_auth(control_socket, None, True, None, None, thread)
authenticate_mock.assert_any_call(control_socket, None, None)
authenticate_mock.assert_any_call(control_socket, 'my_password', None)
@@ -142,7 +150,8 @@ class TestConnect(unittest.TestCase):
self._assert_authenticate_fails_with(control_socket, stdout_mock, 'Unable to authenticate: crazy failure')
def _assert_authenticate_fails_with(self, control_socket, stdout_mock, msg):
- result = stem.connection._connect_auth(control_socket, None, False, None, None)
+ with self._get_thread() as thread:
+ result = stem.connection._connect_auth(control_socket, None, False, None, None, thread)
if result is not None:
self.fail() # _connect_auth() was successful
@@ -152,3 +161,11 @@ class TestConnect(unittest.TestCase):
if msg not in stdout_output:
self.fail("Expected...\n\n%s\n\n... which couldn't be found in...\n\n%s" % (msg, stdout_output))
+
+ @contextlib.contextmanager
+ def _get_thread(self):
+ thread = stem.control._AsyncControllerThread()
+ thread.start()
+ yield thread
+ if thread.is_alive():
+ thread.join()
1
0
[stem/master] Make it possible to use a function to connect to the async controller
by atagar@torproject.org 16 Jul '20
by atagar@torproject.org 16 Jul '20
16 Jul '20
commit 459612e63181218d79d2a42ab5b0eebd0cb206bf
Author: Illia Volochii <illia.volochii(a)gmail.com>
Date: Tue Apr 28 23:54:52 2020 +0300
Make it possible to use a function to connect to the async controller
---
stem/connection.py | 76 ++++++++++++++++++++++++-----------------
stem/control.py | 11 ++++--
test/unit/connection/connect.py | 48 ++++++++++++--------------
3 files changed, 74 insertions(+), 61 deletions(-)
diff --git a/stem/connection.py b/stem/connection.py
index 12330ca3..3d240070 100644
--- a/stem/connection.py
+++ b/stem/connection.py
@@ -133,6 +133,7 @@ import getpass
import hashlib
import hmac
import os
+import threading
import stem.control
import stem.response
@@ -253,6 +254,31 @@ def connect(control_port: Tuple[str, Union[str, int]] = ('127.0.0.1', 'default')
# TODO: change this function's API so we can provide a concrete type
+ if controller is None or not issubclass(controller, stem.control.Controller):
+ raise ValueError('Controller should be a stem.control.BaseController subclass.')
+
+ async_controller_thread = stem.control._AsyncControllerThread()
+ async_controller_thread.start()
+
+ connect_coroutine = _connect_async(control_port, control_socket, password, password_prompt, chroot_path, controller)
+ try:
+ connection = asyncio.run_coroutine_threadsafe(connect_coroutine, async_controller_thread.loop).result()
+ if connection is None and async_controller_thread.is_alive():
+ async_controller_thread.join()
+ return connection
+ except:
+ if async_controller_thread.is_alive():
+ async_controller_thread.join()
+ raise
+
+
+async def connect_async(control_port = ('127.0.0.1', 'default'), control_socket = '/var/run/tor/control', password = None, password_prompt = False, chroot_path = None, controller = stem.control.AsyncController):
+ if controller and not issubclass(controller, stem.control.BaseController):
+ raise ValueError('The provided controller should be a stem.control.BaseController subclass.')
+ return await _connect_async(control_port, control_socket, password, password_prompt, chroot_path, controller)
+
+
+async def _connect_async(control_port, control_socket, password, password_prompt, chroot_path, controller):
if control_port is None and control_socket is None:
raise ValueError('Neither a control port nor control socket were provided. Nothing to connect to.')
elif control_port:
@@ -266,17 +292,11 @@ def connect(control_port: Tuple[str, Union[str, int]] = ('127.0.0.1', 'default')
control_connection = None # type: Optional[stem.socket.ControlSocket]
error_msg = ''
- async_controller_thread = stem.control._AsyncControllerThread()
- async_controller_thread.start()
-
- def connect_socket(socket):
- asyncio.run_coroutine_threadsafe(socket.connect(), async_controller_thread.loop).result()
-
if control_socket:
if os.path.exists(control_socket):
try:
control_connection = stem.socket.ControlSocketFile(control_socket)
- connect_socket(control_connection)
+ await control_connection.connect()
except stem.SocketError as exc:
error_msg = CONNECT_MESSAGES['unable_to_use_socket'].format(path = control_socket, error = exc)
else:
@@ -290,7 +310,7 @@ def connect(control_port: Tuple[str, Union[str, int]] = ('127.0.0.1', 'default')
control_connection = _connection_for_default_port(address)
else:
control_connection = stem.socket.ControlPort(address, int(port))
- connect_socket(control_connection)
+ await control_connection.connect()
except stem.SocketError as exc:
error_msg = CONNECT_MESSAGES['unable_to_use_port'].format(address = address, port = port, error = exc)
@@ -304,14 +324,12 @@ def connect(control_port: Tuple[str, Union[str, int]] = ('127.0.0.1', 'default')
error_msg = CONNECT_MESSAGES['no_control_port'] if is_tor_running else CONNECT_MESSAGES['tor_isnt_running']
print(error_msg)
- if async_controller_thread.is_alive():
- async_controller_thread.join()
return None
- return _connect_auth(control_connection, password, password_prompt, chroot_path, controller, async_controller_thread)
+ return await _connect_auth(control_connection, password, password_prompt, chroot_path, controller)
-def _connect_auth(control_socket: stem.socket.ControlSocket, password: str, password_prompt: bool, chroot_path: str, controller: Optional[Type[stem.control.BaseController]], async_controller_thread: 'threading.Thread') -> Any:
+async def _connect_auth(control_socket: stem.socket.ControlSocket, password: str, password_prompt: bool, chroot_path: str, controller: Optional[Type[stem.control.BaseController]]) -> Any:
"""
Helper for the connect_* functions that authenticates the socket and
constructs the controller.
@@ -327,61 +345,55 @@ def _connect_auth(control_socket: stem.socket.ControlSocket, password: str, pass
:returns: authenticated control connection, the type based on the controller argument
"""
- def run_coroutine(coroutine):
- asyncio.run_coroutine_threadsafe(coroutine, async_controller_thread.loop).result()
-
- def close_control_socket():
- run_coroutine(control_socket.close())
- if async_controller_thread.is_alive():
- async_controller_thread.join()
-
try:
- run_coroutine(authenticate(control_socket, password, chroot_path))
+ await authenticate(control_socket, password, chroot_path)
if controller is None:
return control_socket
- else:
- return controller(control_socket, is_authenticated = True, started_async_controller_thread = async_controller_thread)
+ elif issubclass(controller, stem.control.BaseController):
+ return controller(control_socket, is_authenticated = True)
+ elif issubclass(controller, stem.control.Controller):
+ return controller(control_socket, is_authenticated = True, started_async_controller_thread = threading.current_thread())
except IncorrectSocketType:
if isinstance(control_socket, stem.socket.ControlPort):
print(CONNECT_MESSAGES['wrong_port_type'].format(port = control_socket.port))
else:
print(CONNECT_MESSAGES['wrong_socket_type'])
- close_control_socket()
+ await control_socket.close()
return None
except UnrecognizedAuthMethods as exc:
print(CONNECT_MESSAGES['uncrcognized_auth_type'].format(auth_methods = ', '.join(exc.unknown_auth_methods)))
- close_control_socket()
+ await control_socket.close()
return None
except IncorrectPassword:
print(CONNECT_MESSAGES['incorrect_password'])
- close_control_socket()
+ await control_socket.close()
return None
except MissingPassword:
if password is not None:
- close_control_socket()
+ await control_socket.close()
raise ValueError(CONNECT_MESSAGES['missing_password_bug'])
if password_prompt:
try:
password = getpass.getpass(CONNECT_MESSAGES['password_prompt'] + ' ')
except KeyboardInterrupt:
- close_control_socket()
+ await control_socket.close()
return None
- return _connect_auth(control_socket, password, password_prompt, chroot_path, controller, async_controller_thread)
+ return await _connect_auth(control_socket, password, password_prompt, chroot_path, controller)
else:
print(CONNECT_MESSAGES['needs_password'])
- close_control_socket()
+ await control_socket.close()
return None
except UnreadableCookieFile as exc:
print(CONNECT_MESSAGES['unreadable_cookie_file'].format(path = exc.cookie_path, issue = str(exc)))
- close_control_socket()
+ await control_socket.close()
return None
except AuthenticationFailure as exc:
print(CONNECT_MESSAGES['general_auth_failure'].format(error = exc))
- close_control_socket()
+ await control_socket.close()
return None
diff --git a/stem/control.py b/stem/control.py
index 21a89a5a..b2d2d9d7 100644
--- a/stem/control.py
+++ b/stem/control.py
@@ -3946,10 +3946,15 @@ class Controller(_ControllerClassMethodMixin, _BaseControllerSocketMixin):
self._socket = self._async_controller._socket
def _init_async_controller(self, control_socket: 'stem.socket.ControlSocket', is_authenticated: bool) -> 'stem.control.AsyncController':
- async def init_async_controller():
- return AsyncController(control_socket, is_authenticated)
+ # The asynchronous controller should be initialized in the thread where its
+ # methods will be executed.
+ if self._async_controller_thread != threading.current_thread():
+ async def init_async_controller() -> 'stem.control.AsyncController':
+ return AsyncController(control_socket, is_authenticated)
- return asyncio.run_coroutine_threadsafe(init_async_controller(), self._asyncio_loop).result()
+ return asyncio.run_coroutine_threadsafe(init_async_controller(), self._asyncio_loop).result()
+
+ return AsyncController(control_socket, is_authenticated)
def _execute_async_method(self, method_name: str, *args: Any, **kwargs: Any) -> Any:
return asyncio.run_coroutine_threadsafe(
diff --git a/test/unit/connection/connect.py b/test/unit/connection/connect.py
index 8ba2770c..2112f678 100644
--- a/test/unit/connection/connect.py
+++ b/test/unit/connection/connect.py
@@ -1,7 +1,7 @@
"""
Unit tests for the stem.connection.connect function.
"""
-import contextlib
+
import io
import unittest
@@ -11,7 +11,11 @@ import stem.socket
from unittest.mock import Mock, patch
-from test.unit.async_util import coro_func_raising_exc, coro_func_returning_value
+from test.unit.async_util import (
+ async_test,
+ coro_func_raising_exc,
+ coro_func_returning_value,
+)
class TestConnect(unittest.TestCase):
@@ -20,7 +24,7 @@ class TestConnect(unittest.TestCase):
@patch('os.path.exists', Mock(return_value = True))
@patch('stem.socket.ControlSocketFile', Mock(side_effect = stem.SocketError('failed')))
@patch('stem.socket.ControlPort', Mock(side_effect = stem.SocketError('failed')))
- @patch('stem.connection._connect_auth', Mock())
+ @patch('stem.connection._connect_auth', Mock(side_effect = coro_func_returning_value(None)))
def test_failue_with_the_default_endpoint(self, is_running_mock, stdout_mock):
is_running_mock.return_value = False
self._assert_connect_fails_with({}, stdout_mock, "Unable to connect to tor. Are you sure it's running?")
@@ -33,7 +37,7 @@ class TestConnect(unittest.TestCase):
@patch('stem.util.system.is_running', Mock(return_value = True))
@patch('stem.socket.ControlSocketFile', Mock(side_effect = stem.SocketError('failed')))
@patch('stem.socket.ControlPort', Mock(side_effect = stem.SocketError('failed')))
- @patch('stem.connection._connect_auth', Mock())
+ @patch('stem.connection._connect_auth', Mock(side_effect = coro_func_returning_value(None)))
def test_failure_with_a_custom_endpoint(self, path_exists_mock, stdout_mock):
path_exists_mock.return_value = True
self._assert_connect_fails_with({'control_port': ('127.0.0.1', 80), 'control_socket': None}, stdout_mock, "Unable to connect to 127.0.0.1:80: failed")
@@ -45,7 +49,7 @@ class TestConnect(unittest.TestCase):
@patch('stem.socket.ControlPort')
@patch('os.path.exists', Mock(return_value = False))
- @patch('stem.connection._connect_auth', Mock())
+ @patch('stem.connection._connect_auth', Mock(side_effect = coro_func_returning_value(None)))
def test_getting_a_control_port(self, port_mock):
port_connect_mock = port_mock.return_value.connect
port_connect_mock.side_effect = coro_func_returning_value(None)
@@ -59,7 +63,7 @@ class TestConnect(unittest.TestCase):
@patch('stem.socket.ControlSocketFile')
@patch('os.path.exists', Mock(return_value = True))
- @patch('stem.connection._connect_auth', Mock())
+ @patch('stem.connection._connect_auth', Mock(side_effect = coro_func_returning_value(None)))
def test_getting_a_control_socket(self, socket_mock):
socket_connect_mock = socket_mock.return_value.connect
socket_connect_mock.side_effect = coro_func_returning_value(None)
@@ -92,21 +96,22 @@ class TestConnect(unittest.TestCase):
self.assertEqual(msg, stdout_output.strip().lstrip('\x00'))
@patch('stem.connection.authenticate')
- def test_auth_success(self, authenticate_mock):
+ @async_test
+ async def test_auth_success(self, authenticate_mock):
authenticate_mock.side_effect = coro_func_returning_value(None)
control_socket = Mock()
- with self._get_thread() as thread:
- stem.connection._connect_auth(control_socket, None, False, None, None, thread)
- authenticate_mock.assert_called_with(control_socket, None, None)
- authenticate_mock.reset_mock()
+ await stem.connection._connect_auth(control_socket, None, False, None, None)
+ authenticate_mock.assert_called_with(control_socket, None, None)
+ authenticate_mock.reset_mock()
- stem.connection._connect_auth(control_socket, 's3krit!!!', False, '/my/chroot', None, thread)
+ await stem.connection._connect_auth(control_socket, 's3krit!!!', False, '/my/chroot', None)
authenticate_mock.assert_called_with(control_socket, 's3krit!!!', '/my/chroot')
@patch('getpass.getpass')
@patch('stem.connection.authenticate')
- def test_auth_success_with_password_prompt(self, authenticate_mock, getpass_mock):
+ @async_test
+ async def test_auth_success_with_password_prompt(self, authenticate_mock, getpass_mock):
control_socket = Mock()
async def authenticate_mock_func(controller, password, *args):
@@ -120,8 +125,7 @@ class TestConnect(unittest.TestCase):
authenticate_mock.side_effect = authenticate_mock_func
getpass_mock.return_value = 'my_password'
- with self._get_thread() as thread:
- stem.connection._connect_auth(control_socket, None, True, None, None, thread)
+ await stem.connection._connect_auth(control_socket, None, True, None, None)
authenticate_mock.assert_any_call(control_socket, None, None)
authenticate_mock.assert_any_call(control_socket, 'my_password', None)
@@ -149,9 +153,9 @@ class TestConnect(unittest.TestCase):
authenticate_mock.side_effect = coro_func_raising_exc(stem.connection.OpenAuthRejected('crazy failure'))
self._assert_authenticate_fails_with(control_socket, stdout_mock, 'Unable to authenticate: crazy failure')
- def _assert_authenticate_fails_with(self, control_socket, stdout_mock, msg):
- with self._get_thread() as thread:
- result = stem.connection._connect_auth(control_socket, None, False, None, None, thread)
+ @async_test
+ async def _assert_authenticate_fails_with(self, control_socket, stdout_mock, msg):
+ result = await stem.connection._connect_auth(control_socket, None, False, None, None)
if result is not None:
self.fail() # _connect_auth() was successful
@@ -161,11 +165,3 @@ class TestConnect(unittest.TestCase):
if msg not in stdout_output:
self.fail("Expected...\n\n%s\n\n... which couldn't be found in...\n\n%s" % (msg, stdout_output))
-
- @contextlib.contextmanager
- def _get_thread(self):
- thread = stem.control._AsyncControllerThread()
- thread.start()
- yield thread
- if thread.is_alive():
- thread.join()
1
0
[stem/master] Stop canceling asynchronous tasks for reader and event loops
by atagar@torproject.org 16 Jul '20
by atagar@torproject.org 16 Jul '20
16 Jul '20
commit 163b3b383bc88cc373f9b97f8f458995f09bf498
Author: Illia Volochii <illia.volochii(a)gmail.com>
Date: Thu Apr 30 19:29:37 2020 +0300
Stop canceling asynchronous tasks for reader and event loops
They finish automatically when detect that their controller is not alive.
---
stem/control.py | 6 +-----
1 file changed, 1 insertion(+), 5 deletions(-)
diff --git a/stem/control.py b/stem/control.py
index 98631428..ff0f3bc1 100644
--- a/stem/control.py
+++ b/stem/control.py
@@ -641,7 +641,6 @@ class BaseController(_BaseControllerSocketMixin):
self._socket = control_socket
self._asyncio_loop = asyncio.get_event_loop()
- self._asyncio_loop_tasks = []
self._msg_lock = _MsgLock()
@@ -785,9 +784,6 @@ class BaseController(_BaseControllerSocketMixin):
await self._socket.close()
- for task in self._asyncio_loop_tasks:
- task.cancel()
-
# Join on any outstanding state change listeners. Closing is a state change
# of its own, so if we have any listeners it's quite likely there's some
# work in progress.
@@ -951,7 +947,7 @@ class BaseController(_BaseControllerSocketMixin):
"""
for coroutine in (self._reader_loop(), self._event_loop()):
- self._asyncio_loop_tasks.append(self._asyncio_loop.create_task(coroutine))
+ self._asyncio_loop.create_task(coroutine)
async def _reader_loop(self) -> None:
"""
1
0
commit 94f65d97f85fb577a69f42cea35079e4245835fd
Author: Illia Volochii <illia.volochii(a)gmail.com>
Date: Mon Apr 27 19:55:52 2020 +0300
Remove an unused import
---
stem/connection.py | 1 -
1 file changed, 1 deletion(-)
diff --git a/stem/connection.py b/stem/connection.py
index 6b985725..5da92709 100644
--- a/stem/connection.py
+++ b/stem/connection.py
@@ -133,7 +133,6 @@ import getpass
import hashlib
import hmac
import os
-import threading
import stem.control
import stem.response
1
0
[stem/master] Stop joining the thread for the asynchronous controller while closing
by atagar@torproject.org 16 Jul '20
by atagar@torproject.org 16 Jul '20
16 Jul '20
commit fe14b7164a10868c7bec12a7d25810bbbc6813b9
Author: Illia Volochii <illia.volochii(a)gmail.com>
Date: Thu Apr 30 19:25:38 2020 +0300
Stop joining the thread for the asynchronous controller while closing
If it is joined, it will not be possible to reconnect.
---
stem/control.py | 6 ++++--
1 file changed, 4 insertions(+), 2 deletions(-)
diff --git a/stem/control.py b/stem/control.py
index b2d2d9d7..a87e88ca 100644
--- a/stem/control.py
+++ b/stem/control.py
@@ -3987,8 +3987,6 @@ class Controller(_ControllerClassMethodMixin, _BaseControllerSocketMixin):
def close(self) -> None:
self._execute_async_method('close')
- if self._async_controller_thread.is_alive():
- self._async_controller_thread.join()
def get_latest_heartbeat(self) -> float:
return self._async_controller.get_latest_heartbeat()
@@ -4170,6 +4168,10 @@ class Controller(_ControllerClassMethodMixin, _BaseControllerSocketMixin):
def drop_guards(self) -> None:
self._execute_async_method('drop_guards')
+ def __del__(self) -> None:
+ if self._asyncio_loop.is_running():
+ self._asyncio_loop.call_soon_threadsafe(self._asyncio_loop.stop)
+
def __enter__(self) -> 'stem.control.Controller':
return self
1
0
commit 05d67e3a819f82d2545c6e9039d39a8512c13686
Author: Illia Volochii <illia.volochii(a)gmail.com>
Date: Mon Apr 27 19:57:13 2020 +0300
Fix a problem with a missing argument
---
stem/connection.py | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/stem/connection.py b/stem/connection.py
index 5da92709..12330ca3 100644
--- a/stem/connection.py
+++ b/stem/connection.py
@@ -370,7 +370,7 @@ def _connect_auth(control_socket: stem.socket.ControlSocket, password: str, pass
close_control_socket()
return None
- return _connect_auth(control_socket, password, password_prompt, chroot_path, controller)
+ return _connect_auth(control_socket, password, password_prompt, chroot_path, controller, async_controller_thread)
else:
print(CONNECT_MESSAGES['needs_password'])
close_control_socket()
1
0
commit 2b4d3666ef9d3a9faf6742bd5ccfdef88cfbe4fd
Author: Illia Volochii <illia.volochii(a)gmail.com>
Date: Thu Apr 30 19:30:00 2020 +0300
Optimize `_MsgLock` a little bit
---
stem/control.py | 2 ++
1 file changed, 2 insertions(+)
diff --git a/stem/control.py b/stem/control.py
index ff0f3bc1..6de671b6 100644
--- a/stem/control.py
+++ b/stem/control.py
@@ -554,6 +554,8 @@ def event_description(event: str) -> str:
class _MsgLock:
+ __slots__ = ('_r_lock', '_async_lock')
+
def __init__(self):
self._r_lock = threading.RLock()
self._async_lock = asyncio.Lock()
1
0
commit 00e719e07c9a9993607b96d0151aa1baf943d91e
Author: Illia Volochii <illia.volochii(a)gmail.com>
Date: Thu Apr 30 19:43:53 2020 +0300
Fix most of the integration tests
---
test/{unit => }/async_util.py | 0
test/integ/connection/authentication.py | 143 +++++++++--------
test/integ/connection/connect.py | 17 ++-
test/integ/control/base_controller.py | 130 ++++++++--------
test/integ/control/controller.py | 261 +++++++++++++++++++-------------
test/integ/manual.py | 6 +-
test/integ/process.py | 27 ++--
test/integ/response/protocolinfo.py | 44 +++---
test/integ/socket/control_message.py | 84 +++++-----
test/integ/socket/control_socket.py | 84 +++++-----
test/integ/util/connection.py | 6 +-
test/integ/util/proc.py | 6 +-
test/integ/version.py | 12 +-
test/runner.py | 64 +++++---
test/unit/connection/authentication.py | 2 +-
test/unit/connection/connect.py | 2 +-
test/unit/control/controller.py | 2 +-
17 files changed, 516 insertions(+), 374 deletions(-)
diff --git a/test/unit/async_util.py b/test/async_util.py
similarity index 100%
rename from test/unit/async_util.py
rename to test/async_util.py
diff --git a/test/integ/connection/authentication.py b/test/integ/connection/authentication.py
index d07c20b2..b992ac9a 100644
--- a/test/integ/connection/authentication.py
+++ b/test/integ/connection/authentication.py
@@ -12,6 +12,7 @@ import stem.version
import test
import test.require
import test.runner
+from test.async_util import async_test
# Responses given by tor for various authentication failures. These may change
# in the future and if they do then this test should be updated.
@@ -98,31 +99,34 @@ def _get_auth_failure_message(auth_type):
class TestAuthenticate(unittest.TestCase):
@test.require.controller
- def test_authenticate_general_socket(self):
+ @async_test
+ async def test_authenticate_general_socket(self):
"""
Tests that the authenticate function can authenticate to our socket.
"""
runner = test.runner.get_runner()
- with runner.get_tor_socket(False) as control_socket:
- stem.connection.authenticate(control_socket, test.runner.CONTROL_PASSWORD, runner.get_chroot())
- test.runner.exercise_controller(self, control_socket)
+ async with await runner.get_tor_socket(False) as control_socket:
+ await stem.connection.authenticate(control_socket, test.runner.CONTROL_PASSWORD, runner.get_chroot())
+ await test.runner.exercise_controller(self, control_socket)
@test.require.controller
- def test_authenticate_general_controller(self):
+ @async_test
+ async def test_authenticate_general_controller(self):
"""
Tests that the authenticate function can authenticate via a Controller.
"""
runner = test.runner.get_runner()
- with runner.get_tor_controller(False) as controller:
- stem.connection.authenticate(controller, test.runner.CONTROL_PASSWORD, runner.get_chroot())
- test.runner.exercise_controller(self, controller)
+ with await runner.get_tor_controller(False) as controller:
+ await stem.connection.authenticate(controller, test.runner.CONTROL_PASSWORD, runner.get_chroot())
+ await test.runner.exercise_controller(self, controller)
@test.require.controller
- def test_authenticate_general_example(self):
+ @async_test
+ async def test_authenticate_general_example(self):
"""
Tests the authenticate function with something like its pydoc example.
"""
@@ -139,8 +143,8 @@ class TestAuthenticate(unittest.TestCase):
try:
# this authenticate call should work for everything but password-only auth
- stem.connection.authenticate(control_socket, chroot_path = runner.get_chroot())
- test.runner.exercise_controller(self, control_socket)
+ await stem.connection.authenticate(control_socket, chroot_path = runner.get_chroot())
+ await test.runner.exercise_controller(self, control_socket)
except stem.connection.IncorrectSocketType:
self.fail()
except stem.connection.MissingPassword:
@@ -148,17 +152,18 @@ class TestAuthenticate(unittest.TestCase):
controller_password = test.runner.CONTROL_PASSWORD
try:
- stem.connection.authenticate_password(control_socket, controller_password)
- test.runner.exercise_controller(self, control_socket)
+ await stem.connection.authenticate_password(control_socket, controller_password)
+ await test.runner.exercise_controller(self, control_socket)
except stem.connection.PasswordAuthFailed:
self.fail()
except stem.connection.AuthenticationFailure:
self.fail()
finally:
- control_socket.close()
+ await control_socket.close()
@test.require.controller
- def test_authenticate_general_password(self):
+ @async_test
+ async def test_authenticate_general_password(self):
"""
Tests the authenticate function's password argument.
"""
@@ -172,28 +177,31 @@ class TestAuthenticate(unittest.TestCase):
is_password_only = test.runner.Torrc.PASSWORD in tor_options and test.runner.Torrc.COOKIE not in tor_options
# tests without a password
- with runner.get_tor_socket(False) as control_socket:
+ async with await runner.get_tor_socket(False) as control_socket:
if is_password_only:
- self.assertRaises(stem.connection.MissingPassword, stem.connection.authenticate, control_socket)
+ with self.assertRaises(stem.connection.MissingPassword):
+ await stem.connection.authenticate(control_socket)
else:
- stem.connection.authenticate(control_socket, chroot_path = runner.get_chroot())
- test.runner.exercise_controller(self, control_socket)
+ await stem.connection.authenticate(control_socket, chroot_path = runner.get_chroot())
+ await test.runner.exercise_controller(self, control_socket)
# tests with the incorrect password
- with runner.get_tor_socket(False) as control_socket:
+ async with await runner.get_tor_socket(False) as control_socket:
if is_password_only:
- self.assertRaises(stem.connection.IncorrectPassword, stem.connection.authenticate, control_socket, 'blarg')
+ with self.assertRaises(stem.connection.IncorrectPassword):
+ await stem.connection.authenticate(control_socket, 'blarg')
else:
- stem.connection.authenticate(control_socket, 'blarg', runner.get_chroot())
- test.runner.exercise_controller(self, control_socket)
+ await stem.connection.authenticate(control_socket, 'blarg', runner.get_chroot())
+ await test.runner.exercise_controller(self, control_socket)
# tests with the right password
- with runner.get_tor_socket(False) as control_socket:
- stem.connection.authenticate(control_socket, test.runner.CONTROL_PASSWORD, runner.get_chroot())
- test.runner.exercise_controller(self, control_socket)
+ async with await runner.get_tor_socket(False) as control_socket:
+ await stem.connection.authenticate(control_socket, test.runner.CONTROL_PASSWORD, runner.get_chroot())
+ await test.runner.exercise_controller(self, control_socket)
@test.require.controller
- def test_authenticate_general_cookie(self):
+ @async_test
+ async def test_authenticate_general_cookie(self):
"""
Tests the authenticate function with only cookie authentication methods.
This manipulates our PROTOCOLINFO response to test each method
@@ -205,7 +213,7 @@ class TestAuthenticate(unittest.TestCase):
is_cookie_only = test.runner.Torrc.COOKIE in tor_options and test.runner.Torrc.PASSWORD not in tor_options
# test both cookie authentication mechanisms
- with runner.get_tor_socket(False) as control_socket:
+ async with await runner.get_tor_socket(False) as control_socket:
if is_cookie_only:
for method in (stem.connection.AuthMethod.COOKIE, stem.connection.AuthMethod.SAFECOOKIE):
protocolinfo_response = stem.connection.get_protocolinfo(control_socket)
@@ -215,10 +223,11 @@ class TestAuthenticate(unittest.TestCase):
# both independently
protocolinfo_response.auth_methods = (method, )
- stem.connection.authenticate(control_socket, chroot_path = runner.get_chroot(), protocolinfo_response = protocolinfo_response)
+ await stem.connection.authenticate(control_socket, chroot_path = runner.get_chroot(), protocolinfo_response = protocolinfo_response)
@test.require.controller
- def test_authenticate_none(self):
+ @async_test
+ async def test_authenticate_none(self):
"""
Tests the authenticate_none function.
"""
@@ -226,12 +235,14 @@ class TestAuthenticate(unittest.TestCase):
auth_type = stem.connection.AuthMethod.NONE
if _can_authenticate(auth_type):
- self._check_auth(auth_type)
+ await self._check_auth(auth_type)
else:
- self.assertRaises(stem.connection.OpenAuthRejected, self._check_auth, auth_type)
+ with self.assertRaises(stem.connection.OpenAuthRejected):
+ await self._check_auth(auth_type)
@test.require.controller
- def test_authenticate_password(self):
+ @async_test
+ async def test_authenticate_password(self):
"""
Tests the authenticate_password function.
"""
@@ -240,26 +251,29 @@ class TestAuthenticate(unittest.TestCase):
auth_value = test.runner.CONTROL_PASSWORD
if _can_authenticate(auth_type):
- self._check_auth(auth_type, auth_value)
+ await self._check_auth(auth_type, auth_value)
else:
- self.assertRaises(stem.connection.PasswordAuthRejected, self._check_auth, auth_type, auth_value)
+ with self.assertRaises(stem.connection.PasswordAuthRejected):
+ await self._check_auth(auth_type, auth_value)
# Check with an empty, invalid, and quoted password. These should work if
# we have no authentication, and fail otherwise.
for auth_value in ('', 'blarg', 'this has a " in it'):
if _can_authenticate(stem.connection.AuthMethod.NONE):
- self._check_auth(auth_type, auth_value)
+ await self._check_auth(auth_type, auth_value)
else:
if _can_authenticate(stem.connection.AuthMethod.PASSWORD):
exc_type = stem.connection.IncorrectPassword
else:
exc_type = stem.connection.PasswordAuthRejected
- self.assertRaises(exc_type, self._check_auth, auth_type, auth_value)
+ with self.assertRaises(exc_type):
+ await self._check_auth(auth_type, auth_value)
@test.require.controller
- def test_wrong_password_with_controller(self):
+ @async_test
+ async def test_wrong_password_with_controller(self):
"""
We ran into a race condition where providing the wrong password to the
Controller caused inconsistent responses. Checking for that...
@@ -273,11 +287,13 @@ class TestAuthenticate(unittest.TestCase):
self.skipTest('(requires only password auth)')
for i in range(10):
- with runner.get_tor_controller(False) as controller:
- self.assertRaises(stem.connection.IncorrectPassword, controller.authenticate, 'wrong_password')
+ with await runner.get_tor_controller(False) as controller:
+ with self.assertRaises(stem.connection.IncorrectPassword):
+ await controller.authenticate('wrong_password')
@test.require.controller
- def test_authenticate_cookie(self):
+ @async_test
+ async def test_authenticate_cookie(self):
"""
Tests the authenticate_cookie function.
"""
@@ -292,14 +308,17 @@ class TestAuthenticate(unittest.TestCase):
# auth but the function will short circuit with failure due to the
# missing file.
- self.assertRaises(stem.connection.UnreadableCookieFile, self._check_auth, auth_type, auth_value, False)
+ with self.assertRaises(stem.connection.UnreadableCookieFile):
+ await self._check_auth(auth_type, auth_value, False)
elif _can_authenticate(auth_type):
- self._check_auth(auth_type, auth_value)
+ await self._check_auth(auth_type, auth_value)
else:
- self.assertRaises(stem.connection.CookieAuthRejected, self._check_auth, auth_type, auth_value, False)
+ with self.assertRaises(stem.connection.CookieAuthRejected):
+ await self._check_auth(auth_type, auth_value, False)
@test.require.controller
- def test_authenticate_cookie_invalid(self):
+ @async_test
+ async def test_authenticate_cookie_invalid(self):
"""
Tests the authenticate_cookie function with a properly sized but incorrect
value.
@@ -316,10 +335,11 @@ class TestAuthenticate(unittest.TestCase):
if _can_authenticate(stem.connection.AuthMethod.NONE):
# authentication will work anyway unless this is safecookie
if auth_type == stem.connection.AuthMethod.COOKIE:
- self._check_auth(auth_type, auth_value)
+ await self._check_auth(auth_type, auth_value)
elif auth_type == stem.connection.AuthMethod.SAFECOOKIE:
exc_type = stem.connection.CookieAuthRejected
- self.assertRaises(exc_type, self._check_auth, auth_type, auth_value)
+ with self.assertRaises(exc_type):
+ await self._check_auth(auth_type, auth_value)
else:
if auth_type == stem.connection.AuthMethod.SAFECOOKIE:
if _can_authenticate(auth_type):
@@ -331,12 +351,14 @@ class TestAuthenticate(unittest.TestCase):
else:
exc_type = stem.connection.CookieAuthRejected
- self.assertRaises(exc_type, self._check_auth, auth_type, auth_value, False)
+ with self.assertRaises(exc_type):
+ await self._check_auth(auth_type, auth_value, False)
os.remove(auth_value)
@test.require.controller
- def test_authenticate_cookie_missing(self):
+ @async_test
+ async def test_authenticate_cookie_missing(self):
"""
Tests the authenticate_cookie function with a path that really, really
shouldn't exist.
@@ -344,10 +366,12 @@ class TestAuthenticate(unittest.TestCase):
for auth_type in (stem.connection.AuthMethod.COOKIE, stem.connection.AuthMethod.SAFECOOKIE):
auth_value = "/if/this/exists/then/they're/asking/for/a/failure"
- self.assertRaises(stem.connection.UnreadableCookieFile, self._check_auth, auth_type, auth_value, False)
+ with self.assertRaises(stem.connection.UnreadableCookieFile):
+ await self._check_auth(auth_type, auth_value, False)
@test.require.controller
- def test_authenticate_cookie_wrong_size(self):
+ @async_test
+ async def test_authenticate_cookie_wrong_size(self):
"""
Tests the authenticate_cookie function with our torrc as an auth cookie.
This is to confirm that we won't read arbitrary files to the control
@@ -361,9 +385,10 @@ class TestAuthenticate(unittest.TestCase):
# Weird coincidence? Fail so we can pick another file to check against.
self.fail('Our torrc is 32 bytes, preventing the test_authenticate_cookie_wrong_size test from running.')
else:
- self.assertRaises(stem.connection.IncorrectCookieSize, self._check_auth, auth_type, auth_value, False)
+ with self.assertRaises(stem.connection.IncorrectCookieSize):
+ await self._check_auth(auth_type, auth_value, False)
- def _check_auth(self, auth_type, auth_arg = None, check_message = True):
+ async def _check_auth(self, auth_type, auth_arg = None, check_message = True):
"""
Attempts to use the given type of authentication against tor's control
socket. If it succeeds then we check that the socket can then be used. If
@@ -377,19 +402,19 @@ class TestAuthenticate(unittest.TestCase):
:raises: :class:`stem.connection.AuthenticationFailure` if the authentication fails
"""
- with test.runner.get_runner().get_tor_socket(False) as control_socket:
+ async with await test.runner.get_runner().get_tor_socket(False) as control_socket:
# run the authentication, re-raising if there's a problem
try:
if auth_type == stem.connection.AuthMethod.NONE:
- stem.connection.authenticate_none(control_socket)
+ await stem.connection.authenticate_none(control_socket)
elif auth_type == stem.connection.AuthMethod.PASSWORD:
- stem.connection.authenticate_password(control_socket, auth_arg)
+ await stem.connection.authenticate_password(control_socket, auth_arg)
elif auth_type == stem.connection.AuthMethod.COOKIE:
- stem.connection.authenticate_cookie(control_socket, auth_arg)
+ await stem.connection.authenticate_cookie(control_socket, auth_arg)
elif auth_type == stem.connection.AuthMethod.SAFECOOKIE:
- stem.connection.authenticate_safecookie(control_socket, auth_arg)
+ await stem.connection.authenticate_safecookie(control_socket, auth_arg)
- test.runner.exercise_controller(self, control_socket)
+ await test.runner.exercise_controller(self, control_socket)
except stem.connection.AuthenticationFailure as exc:
# authentication functions should re-attach on failure
self.assertTrue(control_socket.is_alive())
diff --git a/test/integ/connection/connect.py b/test/integ/connection/connect.py
index a271843f..b1d2a672 100644
--- a/test/integ/connection/connect.py
+++ b/test/integ/connection/connect.py
@@ -8,6 +8,7 @@ import unittest
import stem.connection
import test.require
import test.runner
+from test.async_util import async_test
from unittest.mock import patch
@@ -15,37 +16,37 @@ from unittest.mock import patch
class TestConnect(unittest.TestCase):
@test.require.controller
@patch('sys.stdout', new_callable = io.StringIO)
- def test_connect(self, stdout_mock):
+ @async_test
+ async def test_connect(self, stdout_mock):
"""
Basic sanity checks for the connect function.
"""
runner = test.runner.get_runner()
- control_socket = stem.connection.connect(
+ control_socket = await stem.connection.connect_async(
control_port = ('127.0.0.1', test.runner.CONTROL_PORT),
control_socket = test.runner.CONTROL_SOCKET_PATH,
password = test.runner.CONTROL_PASSWORD,
chroot_path = runner.get_chroot(),
controller = None)
- test.runner.exercise_controller(self, control_socket)
+ await test.runner.exercise_controller(self, control_socket)
self.assertEqual('', stdout_mock.getvalue())
@test.require.controller
@patch('sys.stdout', new_callable = io.StringIO)
- def test_connect_to_socks_port(self, stdout_mock):
+ @async_test
+ async def test_connect_to_socks_port(self, stdout_mock):
"""
Common user gotcha is connecting to the SocksPort or ORPort rather than the
ControlPort. Testing that connecting to the SocksPort errors in a
reasonable way.
"""
- runner = test.runner.get_runner()
-
- control_socket = stem.connection.connect(
+ control_socket = await stem.connection.connect_async(
control_port = ('127.0.0.1', test.runner.SOCKS_PORT),
- chroot_path = runner.get_chroot(),
+ control_socket = None,
controller = None)
self.assertEqual(None, control_socket)
diff --git a/test/integ/control/base_controller.py b/test/integ/control/base_controller.py
index 323b57c7..ff51e2f1 100644
--- a/test/integ/control/base_controller.py
+++ b/test/integ/control/base_controller.py
@@ -2,10 +2,11 @@
Integration tests for the stem.control.BaseController class.
"""
+import asyncio
import os
import hashlib
+import random
import re
-import threading
import time
import unittest
@@ -14,6 +15,7 @@ import stem.socket
import stem.util.system
import test.require
import test.runner
+from test.async_util import async_test
class StateObserver(object):
@@ -39,7 +41,8 @@ class StateObserver(object):
class TestBaseController(unittest.TestCase):
@test.require.controller
- def test_connect_repeatedly(self):
+ @async_test
+ async def test_connect_repeatedly(self):
"""
Connects and closes the socket repeatedly. This is a simple attempt to
trigger concurrency issues.
@@ -48,47 +51,51 @@ class TestBaseController(unittest.TestCase):
if stem.util.system.is_mac():
self.skipTest('(ticket #6235)')
- with test.runner.get_runner().get_tor_socket() as control_socket:
+ async with await test.runner.get_runner().get_tor_socket() as control_socket:
controller = stem.control.BaseController(control_socket)
for _ in range(50):
- controller.connect()
- controller.close()
+ await controller.connect()
+ await controller.close()
@test.require.controller
- def test_msg(self):
+ @async_test
+ async def test_msg(self):
"""
Tests a basic query with the msg() method.
"""
- with test.runner.get_runner().get_tor_socket() as control_socket:
+ async with await test.runner.get_runner().get_tor_socket() as control_socket:
controller = stem.control.BaseController(control_socket)
- test.runner.exercise_controller(self, controller)
+ await test.runner.exercise_controller(self, controller)
@test.require.controller
- def test_msg_invalid(self):
+ @async_test
+ async def test_msg_invalid(self):
"""
Tests the msg() method against an invalid controller command.
"""
- with test.runner.get_runner().get_tor_socket() as control_socket:
+ async with await test.runner.get_runner().get_tor_socket() as control_socket:
controller = stem.control.BaseController(control_socket)
- response = controller.msg('invalid')
+ response = await controller.msg('invalid')
self.assertEqual('Unrecognized command "invalid"', str(response))
@test.require.controller
- def test_msg_invalid_getinfo(self):
+ @async_test
+ async def test_msg_invalid_getinfo(self):
"""
Tests the msg() method against a non-existant GETINFO option.
"""
- with test.runner.get_runner().get_tor_socket() as control_socket:
+ async with await test.runner.get_runner().get_tor_socket() as control_socket:
controller = stem.control.BaseController(control_socket)
- response = controller.msg('GETINFO blarg')
+ response = await controller.msg('GETINFO blarg')
self.assertEqual('Unrecognized key "blarg"', str(response))
@test.require.controller
- def test_msg_repeatedly(self):
+ @async_test
+ async def test_msg_repeatedly(self):
"""
Connects, sends a burst of messages, and closes the socket repeatedly. This
is a simple attempt to trigger concurrency issues.
@@ -97,35 +104,31 @@ class TestBaseController(unittest.TestCase):
if stem.util.system.is_mac():
self.skipTest('(ticket #6235)')
- with test.runner.get_runner().get_tor_socket() as control_socket:
+ async with await test.runner.get_runner().get_tor_socket() as control_socket:
controller = stem.control.BaseController(control_socket)
- def run_getinfo():
+ async def connect_and_close():
+ await controller.connect()
+ await controller.close()
+
+ async def run_getinfo():
for _ in range(50):
try:
- controller.msg('GETINFO version')
- controller.msg('GETINFO blarg')
- controller.msg('blarg')
+ await controller.msg('GETINFO version')
+ await controller.msg('GETINFO blarg')
+ await controller.msg('blarg')
except stem.ControllerError:
pass
- message_threads = []
-
- for _ in range(5):
- msg_thread = threading.Thread(target = run_getinfo)
- message_threads.append(msg_thread)
- msg_thread.setDaemon(True)
- msg_thread.start()
-
- for index in range(50):
- controller.connect()
- controller.close()
+ coroutines = [connect_and_close()] * 50
+ coroutines.extend(run_getinfo() for _ in range(5))
+ random.shuffle(coroutines)
- for msg_thread in message_threads:
- msg_thread.join()
+ await asyncio.gather(*coroutines)
@test.require.controller
- def test_asynchronous_event_handling(self):
+ @async_test
+ async def test_asynchronous_event_handling(self):
"""
Check that we can both receive asynchronous events while hammering our
socket with queries, and checks that when a controller is closed the
@@ -140,37 +143,27 @@ class TestBaseController(unittest.TestCase):
def __init__(self, control_socket):
stem.control.BaseController.__init__(self, control_socket)
self.received_events = []
- self.receive_notice = threading.Event()
+ self.receive_notice = asyncio.Event()
- def _handle_event(self, event_message):
- self.receive_notice.wait()
+ async def _handle_event(self, event_message):
+ await self.receive_notice.wait()
self.received_events.append(event_message)
- with test.runner.get_runner().get_tor_socket() as control_socket:
+ async with await test.runner.get_runner().get_tor_socket() as control_socket:
controller = ControlledListener(control_socket)
- controller.msg('SETEVENTS CONF_CHANGED')
+ await controller.msg('SETEVENTS CONF_CHANGED')
for i in range(10):
fingerprint = hashlib.sha1(os.urandom(20)).hexdigest().upper()
- controller.msg('SETCONF NodeFamily=%s' % fingerprint)
- test.runner.exercise_controller(self, controller)
-
- controller.msg('SETEVENTS')
- controller.msg('RESETCONF NodeFamily')
-
- # Concurrently shut down the controller. We need to do this in another
- # thread because it'll block on the event handling, which in turn is
- # currently blocking on the reveive_notice.
-
- close_thread = threading.Thread(target = controller.close, name = 'Closing controller')
- close_thread.setDaemon(True)
- close_thread.start()
+ await controller.msg('SETCONF NodeFamily=%s' % fingerprint)
+ await test.runner.exercise_controller(self, controller)
- # Finally start handling the BW events that we've received. We should
- # have at least a couple of them.
+ await controller.msg('SETEVENTS')
+ await controller.msg('RESETCONF NodeFamily')
+ await controller.close()
controller.receive_notice.set()
- close_thread.join()
+ await asyncio.sleep(0)
self.assertTrue(len(controller.received_events) >= 2)
@@ -180,19 +173,21 @@ class TestBaseController(unittest.TestCase):
self.assertEqual(('650', '-'), conf_changed_event.content()[0][:2])
@test.require.controller
- def test_get_latest_heartbeat(self):
+ @async_test
+ async def test_get_latest_heartbeat(self):
"""
Basic check for get_latest_heartbeat().
"""
# makes a getinfo query, then checks that the heartbeat is close to now
- with test.runner.get_runner().get_tor_socket() as control_socket:
+ async with await test.runner.get_runner().get_tor_socket() as control_socket:
controller = stem.control.BaseController(control_socket)
- controller.msg('GETINFO version')
+ await controller.msg('GETINFO version')
self.assertTrue((time.time() - controller.get_latest_heartbeat()) < 5)
@test.require.controller
- def test_status_notifications(self):
+ @async_test
+ async def test_status_notifications(self):
"""
Checks basic functionality of the add_status_listener() and
remove_status_listener() methods.
@@ -200,18 +195,18 @@ class TestBaseController(unittest.TestCase):
state_observer = StateObserver()
- with test.runner.get_runner().get_tor_socket(False) as control_socket:
+ async with await test.runner.get_runner().get_tor_socket(False) as control_socket:
controller = stem.control.BaseController(control_socket)
controller.add_status_listener(state_observer.listener, False)
- controller.close()
+ await controller.close()
self.assertEqual(controller, state_observer.controller)
self.assertEqual(stem.control.State.CLOSED, state_observer.state)
self.assertTrue(state_observer.timestamp <= time.time())
self.assertTrue(state_observer.timestamp > time.time() - 1.0)
state_observer.reset()
- controller.connect()
+ await controller.connect()
self.assertEqual(controller, state_observer.controller)
self.assertEqual(stem.control.State.INIT, state_observer.state)
self.assertTrue(state_observer.timestamp <= time.time())
@@ -219,8 +214,9 @@ class TestBaseController(unittest.TestCase):
state_observer.reset()
# cause the socket to shut down without calling close()
- controller.msg('Blarg!')
- self.assertRaises(stem.SocketClosed, controller.msg, 'blarg')
+ await controller.msg('Blarg!')
+ with self.assertRaises(stem.SocketClosed):
+ await controller.msg('blarg')
self.assertEqual(controller, state_observer.controller)
self.assertEqual(stem.control.State.CLOSED, state_observer.state)
self.assertTrue(state_observer.timestamp <= time.time())
@@ -229,7 +225,7 @@ class TestBaseController(unittest.TestCase):
# remove listener and make sure we don't get further notices
controller.remove_status_listener(state_observer.listener)
- controller.connect()
+ await controller.connect()
self.assertEqual(None, state_observer.controller)
self.assertEqual(None, state_observer.state)
self.assertEqual(None, state_observer.timestamp)
@@ -239,8 +235,8 @@ class TestBaseController(unittest.TestCase):
# get the notice asynchronously
controller.add_status_listener(state_observer.listener, True)
- controller.close()
- time.sleep(0.001) # not much work going on so this doesn't need to be much
+ await controller.close()
+ await asyncio.sleep(0.001) # not much work going on so this doesn't need to be much
self.assertEqual(controller, state_observer.controller)
self.assertEqual(stem.control.State.CLOSED, state_observer.state)
self.assertTrue(state_observer.timestamp <= time.time())
diff --git a/test/integ/control/controller.py b/test/integ/control/controller.py
index 732ae50a..ab1e76c3 100644
--- a/test/integ/control/controller.py
+++ b/test/integ/control/controller.py
@@ -2,6 +2,7 @@
Integration tests for the stem.control.Controller class.
"""
+import asyncio
import os
import shutil
import socket
@@ -22,6 +23,7 @@ import test
import test.network
import test.require
import test.runner
+from test.async_util import async_test
from stem import Flag, Signal
from stem.control import EventType, Listener, State
@@ -36,13 +38,14 @@ TEST_ROUTER_STATUS_ENTRY = None
class TestController(unittest.TestCase):
@test.require.only_run_once
@test.require.controller
- def test_missing_capabilities(self):
+ @async_test
+ async def test_missing_capabilities(self):
"""
Check to see if tor supports any events, signals, or features that we
don't.
"""
- with test.runner.get_runner().get_tor_controller() as controller:
+ with await test.runner.get_runner().get_tor_controller() as controller:
for event in controller.get_info('events/names').split():
if event not in EventType:
test.register_new_capability('Event', event)
@@ -80,12 +83,13 @@ class TestController(unittest.TestCase):
self.assertRaises(stem.SocketError, stem.control.Controller.from_socket_file, test.runner.CONTROL_SOCKET_PATH)
@test.require.controller
- def test_reset_notification(self):
+ @async_test
+ async def test_reset_notification(self):
"""
Checks that a notificiation listener is... well, notified of SIGHUPs.
"""
- with test.runner.get_runner().get_tor_controller() as controller:
+ with await test.runner.get_runner().get_tor_controller() as controller:
received_events = []
def status_listener(my_controller, state, timestamp):
@@ -101,7 +105,7 @@ class TestController(unittest.TestCase):
if (time.time() - before) > 2:
self.fail("We've waited a couple seconds for SIGHUP to generate an event, but it didn't come")
- time.sleep(0.001)
+ await asyncio.sleep(0.001)
after = time.time()
@@ -109,14 +113,15 @@ class TestController(unittest.TestCase):
state_controller, state_type, state_timestamp = received_events[0]
- self.assertEqual(controller, state_controller)
+ self.assertEqual(controller._async_controller, state_controller)
self.assertEqual(State.RESET, state_type)
self.assertTrue(state_timestamp > before and state_timestamp < after)
controller.reset_conf('__OwningControllerProcess')
@test.require.controller
- def test_event_handling(self):
+ @async_test
+ async def test_event_handling(self):
"""
Add a couple listeners for various events and make sure that they receive
them. Then remove the listeners.
@@ -135,7 +140,7 @@ class TestController(unittest.TestCase):
runner = test.runner.get_runner()
- with runner.get_tor_controller() as controller:
+ with await runner.get_tor_controller() as controller:
controller.add_event_listener(listener1, EventType.CONF_CHANGED)
controller.add_event_listener(listener2, EventType.CONF_CHANGED, EventType.DEBUG)
@@ -174,7 +179,8 @@ class TestController(unittest.TestCase):
controller.reset_conf('NodeFamily')
@test.require.controller
- def test_reattaching_listeners(self):
+ @async_test
+ async def test_reattaching_listeners(self):
"""
Checks that event listeners are re-attached when a controller disconnects
then reconnects to tor.
@@ -189,7 +195,7 @@ class TestController(unittest.TestCase):
runner = test.runner.get_runner()
- with runner.get_tor_controller() as controller:
+ with await runner.get_tor_controller() as controller:
controller.add_event_listener(listener, EventType.CONF_CHANGED)
# trigger an event
@@ -215,14 +221,15 @@ class TestController(unittest.TestCase):
controller.reset_conf('NodeFamily')
@test.require.controller
- def test_getinfo(self):
+ @async_test
+ async def test_getinfo(self):
"""
Exercises GETINFO with valid and invalid queries.
"""
runner = test.runner.get_runner()
- with runner.get_tor_controller() as controller:
+ with await runner.get_tor_controller() as controller:
# successful single query
torrc_path = runner.get_torrc_path()
@@ -253,12 +260,13 @@ class TestController(unittest.TestCase):
self.assertEqual({}, controller.get_info([], {}))
@test.require.controller
- def test_getinfo_freshrelaydescs(self):
+ @async_test
+ async def test_getinfo_freshrelaydescs(self):
"""
Exercises 'GETINFO status/fresh-relay-descs'.
"""
- with test.runner.get_runner().get_tor_controller() as controller:
+ with await test.runner.get_runner().get_tor_controller() as controller:
response = controller.get_info('status/fresh-relay-descs')
div = response.find('\nextra-info ')
nickname = controller.get_conf('Nickname')
@@ -276,12 +284,13 @@ class TestController(unittest.TestCase):
@test.require.controller
@test.require.online
- def test_getinfo_dir_status(self):
+ @async_test
+ async def test_getinfo_dir_status(self):
"""
Exercise 'GETINFO dir/status-vote/*'.
"""
- with test.runner.get_runner().get_tor_controller() as controller:
+ with await test.runner.get_runner().get_tor_controller() as controller:
consensus = controller.get_info('dir/status-vote/current/consensus')
self.assertTrue('moria1' in consensus, 'moria1 not found in the consensus')
@@ -290,47 +299,51 @@ class TestController(unittest.TestCase):
self.assertTrue('moria1' in microdescs, 'moria1 not found in the microdescriptor consensus')
@test.require.controller
- def test_get_version(self):
+ @async_test
+ async def test_get_version(self):
"""
Test that the convenient method get_version() works.
"""
- with test.runner.get_runner().get_tor_controller() as controller:
+ with await test.runner.get_runner().get_tor_controller() as controller:
version = controller.get_version()
self.assertTrue(isinstance(version, stem.version.Version))
self.assertEqual(version, test.tor_version())
@test.require.controller
- def test_get_exit_policy(self):
+ @async_test
+ async def test_get_exit_policy(self):
"""
Sanity test for get_exit_policy(). Our 'ExitRelay 0' torrc entry causes us
to have a simple reject-all policy.
"""
- with test.runner.get_runner().get_tor_controller() as controller:
+ with await test.runner.get_runner().get_tor_controller() as controller:
self.assertEqual(ExitPolicy('reject *:*'), controller.get_exit_policy())
@test.require.controller
- def test_authenticate(self):
+ @async_test
+ async def test_authenticate(self):
"""
Test that the convenient method authenticate() works.
"""
runner = test.runner.get_runner()
- with runner.get_tor_controller(False) as controller:
+ with await runner.get_tor_controller(False) as controller:
controller.authenticate(test.runner.CONTROL_PASSWORD)
- test.runner.exercise_controller(self, controller)
+ await test.runner.exercise_controller(self, controller)
@test.require.controller
- def test_protocolinfo(self):
+ @async_test
+ async def test_protocolinfo(self):
"""
Test that the convenient method protocolinfo() works.
"""
runner = test.runner.get_runner()
- with runner.get_tor_controller(False) as controller:
+ with await runner.get_tor_controller(False) as controller:
protocolinfo = controller.get_protocolinfo()
self.assertTrue(isinstance(protocolinfo, stem.response.protocolinfo.ProtocolInfoResponse))
@@ -351,14 +364,15 @@ class TestController(unittest.TestCase):
self.assertEqual(tuple(auth_methods), protocolinfo.auth_methods)
@test.require.controller
- def test_getconf(self):
+ @async_test
+ async def test_getconf(self):
"""
Exercises GETCONF with valid and invalid queries.
"""
runner = test.runner.get_runner()
- with runner.get_tor_controller() as controller:
+ with await runner.get_tor_controller() as controller:
control_socket = controller.get_socket()
if isinstance(control_socket, stem.socket.ControlPort):
@@ -414,15 +428,16 @@ class TestController(unittest.TestCase):
self.assertEqual({}, controller.get_conf_map([], 'la-di-dah'))
@test.require.controller
- def test_is_set(self):
+ @async_test
+ async def test_is_set(self):
"""
Exercises our is_set() method.
"""
runner = test.runner.get_runner()
- with runner.get_tor_controller() as controller:
- custom_options = controller._get_custom_options()
+ with await runner.get_tor_controller() as controller:
+ custom_options = controller._execute_async_method('_get_custom_options')
self.assertTrue('ControlPort' in custom_options or 'ControlSocket' in custom_options)
self.assertEqual('1', custom_options['DownloadExtraInfo'])
self.assertEqual('1112', custom_options['SocksPort'])
@@ -441,7 +456,8 @@ class TestController(unittest.TestCase):
self.assertFalse(controller.is_set('ConnLimit'))
@test.require.controller
- def test_hidden_services_conf(self):
+ @async_test
+ async def test_hidden_services_conf(self):
"""
Exercises the hidden service family of methods (get_hidden_service_conf,
set_hidden_service_conf, create_hidden_service, and remove_hidden_service).
@@ -455,7 +471,7 @@ class TestController(unittest.TestCase):
service3_path = os.path.join(test_dir, 'test_hidden_service3')
service4_path = os.path.join(test_dir, 'test_hidden_service4')
- with runner.get_tor_controller() as controller:
+ with await runner.get_tor_controller() as controller:
try:
# initially we shouldn't be running any hidden services
@@ -549,32 +565,35 @@ class TestController(unittest.TestCase):
pass
@test.require.controller
- def test_without_ephemeral_hidden_services(self):
+ @async_test
+ async def test_without_ephemeral_hidden_services(self):
"""
Exercises ephemeral hidden service methods when none are present.
"""
- with test.runner.get_runner().get_tor_controller() as controller:
+ with await test.runner.get_runner().get_tor_controller() as controller:
self.assertEqual([], controller.list_ephemeral_hidden_services())
self.assertEqual([], controller.list_ephemeral_hidden_services(detached = True))
self.assertEqual(False, controller.remove_ephemeral_hidden_service('gfzprpioee3hoppz'))
@test.require.controller
- def test_with_invalid_ephemeral_hidden_service_port(self):
- with test.runner.get_runner().get_tor_controller() as controller:
+ @async_test
+ async def test_with_invalid_ephemeral_hidden_service_port(self):
+ with await test.runner.get_runner().get_tor_controller() as controller:
for ports in (4567890, [4567, 4567890], {4567: '-:4567'}):
exc_msg = "ADD_ONION response didn't have an OK status: Invalid VIRTPORT/TARGET"
self.assertRaisesWith(stem.ProtocolError, exc_msg, controller.create_ephemeral_hidden_service, ports)
@test.require.controller
- def test_ephemeral_hidden_services_v2(self):
+ @async_test
+ async def test_ephemeral_hidden_services_v2(self):
"""
Exercises creating v2 ephemeral hidden services.
"""
runner = test.runner.get_runner()
- with runner.get_tor_controller() as controller:
+ with await runner.get_tor_controller() as controller:
response = controller.create_ephemeral_hidden_service(4567, key_content = 'RSA1024')
self.assertEqual([response.service_id], controller.list_ephemeral_hidden_services())
self.assertTrue(response.private_key is not None)
@@ -606,19 +625,20 @@ class TestController(unittest.TestCase):
# other controllers shouldn't be able to see these hidden services
- with runner.get_tor_controller() as second_controller:
+ with await runner.get_tor_controller() as second_controller:
self.assertEqual(2, len(controller.list_ephemeral_hidden_services()))
self.assertEqual(0, len(second_controller.list_ephemeral_hidden_services()))
@test.require.controller
- def test_ephemeral_hidden_services_v3(self):
+ @async_test
+ async def test_ephemeral_hidden_services_v3(self):
"""
Exercises creating v3 ephemeral hidden services.
"""
runner = test.runner.get_runner()
- with runner.get_tor_controller() as controller:
+ with await runner.get_tor_controller() as controller:
response = controller.create_ephemeral_hidden_service(4567, key_content = 'ED25519-V3')
self.assertEqual([response.service_id], controller.list_ephemeral_hidden_services())
self.assertTrue(response.private_key is not None)
@@ -650,19 +670,20 @@ class TestController(unittest.TestCase):
# other controllers shouldn't be able to see these hidden services
- with runner.get_tor_controller() as second_controller:
+ with await runner.get_tor_controller() as second_controller:
self.assertEqual(2, len(controller.list_ephemeral_hidden_services()))
self.assertEqual(0, len(second_controller.list_ephemeral_hidden_services()))
@test.require.controller
- def test_with_ephemeral_hidden_services_basic_auth(self):
+ @async_test
+ async def test_with_ephemeral_hidden_services_basic_auth(self):
"""
Exercises creating ephemeral hidden services that uses basic authentication.
"""
runner = test.runner.get_runner()
- with runner.get_tor_controller() as controller:
+ with await runner.get_tor_controller() as controller:
response = controller.create_ephemeral_hidden_service(4567, key_content = 'RSA1024', basic_auth = {'alice': 'nKwfvVPmTNr2k2pG0pzV4g', 'bob': None})
self.assertEqual([response.service_id], controller.list_ephemeral_hidden_services())
self.assertTrue(response.private_key is not None)
@@ -674,7 +695,8 @@ class TestController(unittest.TestCase):
self.assertEqual([], controller.list_ephemeral_hidden_services())
@test.require.controller
- def test_with_ephemeral_hidden_services_basic_auth_no_credentials(self):
+ @async_test
+ async def test_with_ephemeral_hidden_services_basic_auth_no_credentials(self):
"""
Exercises creating ephemeral hidden services when attempting to use basic
auth but not including any credentials.
@@ -682,12 +704,13 @@ class TestController(unittest.TestCase):
runner = test.runner.get_runner()
- with runner.get_tor_controller() as controller:
+ with await runner.get_tor_controller() as controller:
exc_msg = "ADD_ONION response didn't have an OK status: No auth clients specified"
self.assertRaisesWith(stem.ProtocolError, exc_msg, controller.create_ephemeral_hidden_service, 4567, basic_auth = {})
@test.require.controller
- def test_with_detached_ephemeral_hidden_services(self):
+ @async_test
+ async def test_with_detached_ephemeral_hidden_services(self):
"""
Exercises creating detached ephemeral hidden services and methods when
they're present.
@@ -695,7 +718,7 @@ class TestController(unittest.TestCase):
runner = test.runner.get_runner()
- with runner.get_tor_controller() as controller:
+ with await runner.get_tor_controller() as controller:
response = controller.create_ephemeral_hidden_service(4567, detached = True)
self.assertEqual([], controller.list_ephemeral_hidden_services())
self.assertEqual([response.service_id], controller.list_ephemeral_hidden_services(detached = True))
@@ -709,7 +732,7 @@ class TestController(unittest.TestCase):
# other controllers should be able to see this service, and drop it
- with runner.get_tor_controller() as second_controller:
+ with await runner.get_tor_controller() as second_controller:
self.assertEqual([response.service_id], second_controller.list_ephemeral_hidden_services(detached = True))
self.assertEqual(True, second_controller.remove_ephemeral_hidden_service(response.service_id))
self.assertEqual([], controller.list_ephemeral_hidden_services(detached = True))
@@ -722,7 +745,8 @@ class TestController(unittest.TestCase):
controller.remove_ephemeral_hidden_service(response.service_id)
@test.require.controller
- def test_rejecting_unanonymous_hidden_services_creation(self):
+ @async_test
+ async def test_rejecting_unanonymous_hidden_services_creation(self):
"""
Attempt to create a non-anonymous hidden service despite not setting
HiddenServiceSingleHopMode and HiddenServiceNonAnonymousMode.
@@ -730,11 +754,12 @@ class TestController(unittest.TestCase):
runner = test.runner.get_runner()
- with runner.get_tor_controller() as controller:
+ with await runner.get_tor_controller() as controller:
self.assertEqual('Tor is in anonymous hidden service mode', str(controller.msg('ADD_ONION NEW:BEST Flags=NonAnonymous Port=4567')))
@test.require.controller
- def test_set_conf(self):
+ @async_test
+ async def test_set_conf(self):
"""
Exercises set_conf(), reset_conf(), and set_options() methods with valid
and invalid requests.
@@ -744,7 +769,7 @@ class TestController(unittest.TestCase):
with tempfile.TemporaryDirectory() as tmpdir:
- with runner.get_tor_controller() as controller:
+ with await runner.get_tor_controller() as controller:
try:
# successfully set a single option
connlimit = int(controller.get_conf('ConnLimit'))
@@ -807,13 +832,14 @@ class TestController(unittest.TestCase):
), reset = True)
@test.require.controller
- def test_set_conf_for_usebridges(self):
+ @async_test
+ async def test_set_conf_for_usebridges(self):
"""
Ensure we can set UseBridges=1 and also set a Bridge. This is a tor
regression check (:trac:`31945`).
"""
- with test.runner.get_runner().get_tor_controller() as controller:
+ with await test.runner.get_runner().get_tor_controller() as controller:
orport = controller.get_conf('ORPort')
try:
@@ -830,24 +856,26 @@ class TestController(unittest.TestCase):
), reset = True)
@test.require.controller
- def test_set_conf_when_immutable(self):
+ @async_test
+ async def test_set_conf_when_immutable(self):
"""
Issue a SETCONF for tor options that cannot be changed while running.
"""
- with test.runner.get_runner().get_tor_controller() as controller:
+ with await test.runner.get_runner().get_tor_controller() as controller:
self.assertRaisesWith(stem.InvalidArguments, "DisableAllSwap cannot be changed while tor's running", controller.set_conf, 'DisableAllSwap', '1')
self.assertRaisesWith(stem.InvalidArguments, "DisableAllSwap, User cannot be changed while tor's running", controller.set_options, {'User': 'atagar', 'DisableAllSwap': '1'})
@test.require.controller
- def test_loadconf(self):
+ @async_test
+ async def test_loadconf(self):
"""
Exercises Controller.load_conf with valid and invalid requests.
"""
runner = test.runner.get_runner()
- with runner.get_tor_controller() as controller:
+ with await runner.get_tor_controller() as controller:
oldconf = runner.get_torrc_contents()
try:
@@ -877,12 +905,13 @@ class TestController(unittest.TestCase):
controller.reset_conf('__OwningControllerProcess')
@test.require.controller
- def test_saveconf(self):
+ @async_test
+ async def test_saveconf(self):
runner = test.runner.get_runner()
# only testing for success, since we need to run out of disk space to test
# for failure
- with runner.get_tor_controller() as controller:
+ with await runner.get_tor_controller() as controller:
oldconf = runner.get_torrc_contents()
try:
@@ -897,14 +926,15 @@ class TestController(unittest.TestCase):
controller.reset_conf('__OwningControllerProcess')
@test.require.controller
- def test_get_ports(self):
+ @async_test
+ async def test_get_ports(self):
"""
Test Controller.get_ports against a running tor instance.
"""
runner = test.runner.get_runner()
- with runner.get_tor_controller() as controller:
+ with await runner.get_tor_controller() as controller:
self.assertEqual([test.runner.ORPORT], controller.get_ports(Listener.OR))
self.assertEqual([], controller.get_ports(Listener.DIR))
self.assertEqual([test.runner.SOCKS_PORT], controller.get_ports(Listener.SOCKS))
@@ -918,14 +948,15 @@ class TestController(unittest.TestCase):
self.assertEqual([], controller.get_ports(Listener.CONTROL))
@test.require.controller
- def test_get_listeners(self):
+ @async_test
+ async def test_get_listeners(self):
"""
Test Controller.get_listeners against a running tor instance.
"""
runner = test.runner.get_runner()
- with runner.get_tor_controller() as controller:
+ with await runner.get_tor_controller() as controller:
self.assertEqual([('0.0.0.0', test.runner.ORPORT)], controller.get_listeners(Listener.OR))
self.assertEqual([], controller.get_listeners(Listener.DIR))
self.assertEqual([('127.0.0.1', test.runner.SOCKS_PORT)], controller.get_listeners(Listener.SOCKS))
@@ -941,14 +972,15 @@ class TestController(unittest.TestCase):
@test.require.controller
@test.require.online
@test.require.version(stem.version.Version('0.1.2.2-alpha'))
- def test_enable_feature(self):
+ @async_test
+ async def test_enable_feature(self):
"""
Test Controller.enable_feature with valid and invalid inputs.
"""
runner = test.runner.get_runner()
- with runner.get_tor_controller() as controller:
+ with await runner.get_tor_controller() as controller:
self.assertTrue(controller.is_feature_enabled('VERBOSE_NAMES'))
self.assertRaises(stem.InvalidArguments, controller.enable_feature, ['NOT', 'A', 'FEATURE'])
@@ -960,12 +992,13 @@ class TestController(unittest.TestCase):
self.fail()
@test.require.controller
- def test_signal(self):
+ @async_test
+ async def test_signal(self):
"""
Test controller.signal with valid and invalid signals.
"""
- with test.runner.get_runner().get_tor_controller() as controller:
+ with await test.runner.get_runner().get_tor_controller() as controller:
# valid signal
controller.signal('CLEARDNSCACHE')
@@ -973,12 +1006,13 @@ class TestController(unittest.TestCase):
self.assertRaises(stem.InvalidArguments, controller.signal, 'FOOBAR')
@test.require.controller
- def test_newnym_availability(self):
+ @async_test
+ async def test_newnym_availability(self):
"""
Test the is_newnym_available and get_newnym_wait methods.
"""
- with test.runner.get_runner().get_tor_controller() as controller:
+ with await test.runner.get_runner().get_tor_controller() as controller:
self.assertEqual(True, controller.is_newnym_available())
self.assertEqual(0.0, controller.get_newnym_wait())
@@ -989,8 +1023,9 @@ class TestController(unittest.TestCase):
@test.require.controller
@test.require.online
- def test_extendcircuit(self):
- with test.runner.get_runner().get_tor_controller() as controller:
+ @async_test
+ async def test_extendcircuit(self):
+ with await test.runner.get_runner().get_tor_controller() as controller:
circuit_id = controller.extend_circuit('0')
# check if our circuit was created
@@ -1004,14 +1039,15 @@ class TestController(unittest.TestCase):
@test.require.controller
@test.require.online
- def test_repurpose_circuit(self):
+ @async_test
+ async def test_repurpose_circuit(self):
"""
Tests Controller.repurpose_circuit with valid and invalid input.
"""
runner = test.runner.get_runner()
- with runner.get_tor_controller() as controller:
+ with await runner.get_tor_controller() as controller:
circ_id = controller.new_circuit()
controller.repurpose_circuit(circ_id, 'CONTROLLER')
circuit = controller.get_circuit(circ_id)
@@ -1026,14 +1062,15 @@ class TestController(unittest.TestCase):
@test.require.controller
@test.require.online
- def test_close_circuit(self):
+ @async_test
+ async def test_close_circuit(self):
"""
Tests Controller.close_circuit with valid and invalid input.
"""
runner = test.runner.get_runner()
- with runner.get_tor_controller() as controller:
+ with await runner.get_tor_controller() as controller:
circuit_id = controller.new_circuit()
controller.close_circuit(circuit_id)
circuit_output = controller.get_info('circuit-status')
@@ -1052,7 +1089,8 @@ class TestController(unittest.TestCase):
@test.require.controller
@test.require.online
- def test_get_streams(self):
+ @async_test
+ async def test_get_streams(self):
"""
Tests Controller.get_streams().
"""
@@ -1061,7 +1099,7 @@ class TestController(unittest.TestCase):
port = 443
runner = test.runner.get_runner()
- with runner.get_tor_controller() as controller:
+ with await runner.get_tor_controller() as controller:
# we only need one proxy port, so take the first
socks_listener = controller.get_listeners(Listener.SOCKS)[0]
@@ -1077,14 +1115,15 @@ class TestController(unittest.TestCase):
@test.require.controller
@test.require.online
- def test_close_stream(self):
+ @async_test
+ async def test_close_stream(self):
"""
Tests Controller.close_stream with valid and invalid input.
"""
runner = test.runner.get_runner()
- with runner.get_tor_controller() as controller:
+ with await runner.get_tor_controller() as controller:
# use the first socks listener
socks_listener = controller.get_listeners(Listener.SOCKS)[0]
@@ -1116,11 +1155,12 @@ class TestController(unittest.TestCase):
@test.require.controller
@test.require.online
- def test_mapaddress(self):
+ @async_test
+ async def test_mapaddress(self):
self.skipTest('(https://trac.torproject.org/projects/tor/ticket/25611)')
runner = test.runner.get_runner()
- with runner.get_tor_controller() as controller:
+ with await runner.get_tor_controller() as controller:
controller.map_address({'1.2.1.2': 'ifconfig.me'})
s = None
@@ -1154,10 +1194,11 @@ class TestController(unittest.TestCase):
self.assertTrue(stem.util.connection.is_valid_ipv4_address(stem.util.str_tools._to_unicode(ip_addr)), "'%s' isn't an address" % ip_addr)
@test.require.controller
- def test_mapaddress_offline(self):
+ @async_test
+ async def test_mapaddress_offline(self):
runner = test.runner.get_runner()
- with runner.get_tor_controller() as controller:
+ with await runner.get_tor_controller() as controller:
# try mapping one element, ensuring results are as expected
map1 = {'1.2.1.2': 'ifconfig.me'}
@@ -1233,12 +1274,13 @@ class TestController(unittest.TestCase):
@test.require.controller
@test.require.online
- def test_get_microdescriptor(self):
+ @async_test
+ async def test_get_microdescriptor(self):
"""
Basic checks for get_microdescriptor().
"""
- with test.runner.get_runner().get_tor_controller() as controller:
+ with await test.runner.get_runner().get_tor_controller() as controller:
# we should balk at invalid content
self.assertRaises(ValueError, controller.get_microdescriptor, '')
self.assertRaises(ValueError, controller.get_microdescriptor, 5)
@@ -1257,7 +1299,8 @@ class TestController(unittest.TestCase):
@test.require.controller
@test.require.online
- def test_get_microdescriptors(self):
+ @async_test
+ async def test_get_microdescriptors(self):
"""
Fetches a few descriptors via the get_microdescriptors() method.
"""
@@ -1267,7 +1310,7 @@ class TestController(unittest.TestCase):
if not os.path.exists(runner.get_test_dir('cached-microdescs')):
self.skipTest('(no cached microdescriptors)')
- with runner.get_tor_controller() as controller:
+ with await runner.get_tor_controller() as controller:
count = 0
for desc in controller.get_microdescriptors():
@@ -1279,14 +1322,15 @@ class TestController(unittest.TestCase):
@test.require.controller
@test.require.online
- def test_get_server_descriptor(self):
+ @async_test
+ async def test_get_server_descriptor(self):
"""
Basic checks for get_server_descriptor().
"""
runner = test.runner.get_runner()
- with runner.get_tor_controller() as controller:
+ with await runner.get_tor_controller() as controller:
# we should balk at invalid content
self.assertRaises(ValueError, controller.get_server_descriptor, '')
self.assertRaises(ValueError, controller.get_server_descriptor, 5)
@@ -1305,14 +1349,15 @@ class TestController(unittest.TestCase):
@test.require.controller
@test.require.online
- def test_get_server_descriptors(self):
+ @async_test
+ async def test_get_server_descriptors(self):
"""
Fetches a few descriptors via the get_server_descriptors() method.
"""
runner = test.runner.get_runner()
- with runner.get_tor_controller() as controller:
+ with await runner.get_tor_controller() as controller:
count = 0
for desc in controller.get_server_descriptors():
@@ -1330,12 +1375,13 @@ class TestController(unittest.TestCase):
@test.require.controller
@test.require.online
- def test_get_network_status(self):
+ @async_test
+ async def test_get_network_status(self):
"""
Basic checks for get_network_status().
"""
- with test.runner.get_runner().get_tor_controller() as controller:
+ with await test.runner.get_runner().get_tor_controller() as controller:
# we should balk at invalid content
self.assertRaises(ValueError, controller.get_network_status, '')
self.assertRaises(ValueError, controller.get_network_status, 5)
@@ -1354,14 +1400,15 @@ class TestController(unittest.TestCase):
@test.require.controller
@test.require.online
- def test_get_network_statuses(self):
+ @async_test
+ async def test_get_network_statuses(self):
"""
Fetches a few descriptors via the get_network_statuses() method.
"""
runner = test.runner.get_runner()
- with runner.get_tor_controller() as controller:
+ with await runner.get_tor_controller() as controller:
count = 0
for desc in controller.get_network_statuses():
@@ -1377,14 +1424,15 @@ class TestController(unittest.TestCase):
@test.require.controller
@test.require.online
- def test_get_hidden_service_descriptor(self):
+ @async_test
+ async def test_get_hidden_service_descriptor(self):
"""
Fetches a few descriptors via the get_hidden_service_descriptor() method.
"""
runner = test.runner.get_runner()
- with runner.get_tor_controller() as controller:
+ with await runner.get_tor_controller() as controller:
# fetch the descriptor for DuckDuckGo
desc = controller.get_hidden_service_descriptor('3g2upl4pq6kufc4m.onion')
@@ -1402,7 +1450,8 @@ class TestController(unittest.TestCase):
@test.require.controller
@test.require.online
- def test_attachstream(self):
+ @async_test
+ async def test_attachstream(self):
host = socket.gethostbyname('www.torproject.org')
port = 80
@@ -1412,7 +1461,7 @@ class TestController(unittest.TestCase):
if stream.status == 'NEW' and circuit_id:
controller.attach_stream(stream.id, circuit_id)
- with test.runner.get_runner().get_tor_controller() as controller:
+ with await test.runner.get_runner().get_tor_controller() as controller:
# try 10 times to build a circuit we can connect through
for i in range(10):
controller.add_event_listener(handle_streamcreated, stem.control.EventType.STREAM)
@@ -1442,24 +1491,26 @@ class TestController(unittest.TestCase):
@test.require.controller
@test.require.online
- def test_get_circuits(self):
+ @async_test
+ async def test_get_circuits(self):
"""
Fetches circuits via the get_circuits() method.
"""
- with test.runner.get_runner().get_tor_controller() as controller:
+ with await test.runner.get_runner().get_tor_controller() as controller:
new_circ = controller.new_circuit()
circuits = controller.get_circuits()
self.assertTrue(new_circ in [circ.id for circ in circuits])
@test.require.controller
- def test_transition_to_relay(self):
+ @async_test
+ async def test_transition_to_relay(self):
"""
Transitions Tor to turn into a relay, then back to a client. This helps to
catch transition issues such as the one cited in :trac:`14901`.
"""
- with test.runner.get_runner().get_tor_controller() as controller:
+ with await test.runner.get_runner().get_tor_controller() as controller:
try:
controller.reset_conf('OrPort', 'DisableNetwork')
self.assertEqual(None, controller.get_conf('OrPort'))
diff --git a/test/integ/manual.py b/test/integ/manual.py
index 3e721ac6..df0c0105 100644
--- a/test/integ/manual.py
+++ b/test/integ/manual.py
@@ -14,6 +14,7 @@ import test
import test.runner
from stem.manual import Category
+from test.async_util import async_test
EXPECTED_CATEGORIES = set([
'NAME',
@@ -216,14 +217,15 @@ class TestManual(unittest.TestCase):
self.assertEqual(['tor - The second-generation onion router'], categories['NAME'])
self.assertEqual(['tor [OPTION value]...'], categories['SYNOPSIS'])
- def test_has_all_tor_config_options(self):
+ @async_test
+ async def test_has_all_tor_config_options(self):
"""
Check that all the configuration options tor supports are in the man page.
"""
self.requires_downloaded_manual()
- with test.runner.get_runner().get_tor_controller() as controller:
+ with await test.runner.get_runner().get_tor_controller() as controller:
config_options_in_tor = set([line.split()[0] for line in controller.get_info('config/names').splitlines() if line.split()[1] != 'Virtual'])
# options starting with an underscore are hidden by convention
diff --git a/test/integ/process.py b/test/integ/process.py
index 12cc493a..a2363fea 100644
--- a/test/integ/process.py
+++ b/test/integ/process.py
@@ -27,6 +27,7 @@ from contextlib import contextmanager
from unittest.mock import patch, Mock
from stem.util.test_tools import asynchronous, assert_equal, assert_in, skip
+from test.async_util import async_test
BASIC_RELAY_TORRC = """\
SocksPort 9089
@@ -97,9 +98,9 @@ class TestProcess(unittest.TestCase):
global TOR_CMD
TOR_CMD = args.tor_cmd
- for func, async_test in stem.util.test_tools.ASYNC_TESTS.items():
+ for func, asynchronous_test in stem.util.test_tools.ASYNC_TESTS.items():
if func.startswith('test.integ.process.'):
- async_test.run(TOR_CMD)
+ asynchronous_test.run(TOR_CMD)
@asynchronous
def test_version_argument(tor_cmd):
@@ -407,7 +408,8 @@ class TestProcess(unittest.TestCase):
raise AssertionError('Launching tor with the default timeout should be successful')
@asynchronous
- def test_launch_tor_with_config_via_file(tor_cmd):
+ @async_test
+ async def test_launch_tor_with_config_via_file(tor_cmd):
"""
Exercises launch_tor_with_config when we write a torrc to disk.
"""
@@ -432,23 +434,24 @@ class TestProcess(unittest.TestCase):
)
control_socket = stem.socket.ControlPort(port = int(control_port))
- stem.connection.authenticate(control_socket)
+ await stem.connection.authenticate(control_socket)
# exercises the socket
- control_socket.send('GETCONF ControlPort')
- getconf_response = control_socket.recv()
+ await control_socket.send('GETCONF ControlPort')
+ getconf_response = await control_socket.recv()
assert_equal('ControlPort=%s' % control_port, str(getconf_response))
finally:
if control_socket:
- control_socket.close()
+ await control_socket.close()
if tor_process:
tor_process.kill()
tor_process.wait()
@asynchronous
- def test_launch_tor_with_config_via_stdin(tor_cmd):
+ @async_test
+ async def test_launch_tor_with_config_via_stdin(tor_cmd):
"""
Exercises launch_tor_with_config when we provide our torrc via stdin.
"""
@@ -469,16 +472,16 @@ class TestProcess(unittest.TestCase):
)
control_socket = stem.socket.ControlPort(port = int(control_port))
- stem.connection.authenticate(control_socket)
+ await stem.connection.authenticate(control_socket)
# exercises the socket
- control_socket.send('GETCONF ControlPort')
- getconf_response = control_socket.recv()
+ await control_socket.send('GETCONF ControlPort')
+ getconf_response = await control_socket.recv()
assert_equal('ControlPort=%s' % control_port, str(getconf_response))
finally:
if control_socket:
- control_socket.close()
+ await control_socket.close()
if tor_process:
tor_process.kill()
diff --git a/test/integ/response/protocolinfo.py b/test/integ/response/protocolinfo.py
index 3a9ee0be..f824be5d 100644
--- a/test/integ/response/protocolinfo.py
+++ b/test/integ/response/protocolinfo.py
@@ -16,20 +16,23 @@ import test.runner
from unittest.mock import Mock, patch
+from test.async_util import async_test
+
class TestProtocolInfo(unittest.TestCase):
@test.require.controller
- def test_parsing(self):
+ @async_test
+ async def test_parsing(self):
"""
Makes a PROTOCOLINFO query and processes the response for our control
connection.
"""
- control_socket = test.runner.get_runner().get_tor_socket(False)
- control_socket.send('PROTOCOLINFO 1')
- protocolinfo_response = control_socket.recv()
+ control_socket = await test.runner.get_runner().get_tor_socket(False)
+ await control_socket.send('PROTOCOLINFO 1')
+ protocolinfo_response = await control_socket.recv()
stem.response.convert('PROTOCOLINFO', protocolinfo_response)
- control_socket.close()
+ await control_socket.close()
# according to the control spec the following _could_ differ or be
# undefined but if that actually happens then it's gonna make people sad
@@ -43,7 +46,8 @@ class TestProtocolInfo(unittest.TestCase):
@test.require.controller
@patch('stem.util.proc.is_available', Mock(return_value = False))
@patch('stem.util.system.is_available', Mock(return_value = True))
- def test_get_protocolinfo_path_expansion(self):
+ @async_test
+ async def test_get_protocolinfo_path_expansion(self):
"""
If we're running with the 'RELATIVE' target then test_parsing() will
exercise cookie path expansion when we're able to query the pid by our
@@ -71,47 +75,51 @@ class TestProtocolInfo(unittest.TestCase):
control_socket = stem.socket.ControlSocketFile(test.runner.CONTROL_SOCKET_PATH)
+ await control_socket.connect()
+
call_replacement = test.integ.util.system.filter_system_call(lookup_prefixes)
with patch('stem.util.system.call') as call_mock:
call_mock.side_effect = call_replacement
- protocolinfo_response = stem.connection.get_protocolinfo(control_socket)
+ protocolinfo_response = await stem.connection.get_protocolinfo(control_socket)
self.assert_matches_test_config(protocolinfo_response)
# we should have a usable socket at this point
self.assertTrue(control_socket.is_alive())
- control_socket.close()
+ await control_socket.close()
@test.require.controller
- def test_multiple_protocolinfo_calls(self):
+ @async_test
+ async def test_multiple_protocolinfo_calls(self):
"""
Tests making repeated PROTOCOLINFO queries. This use case is interesting
because tor will shut down the socket and stem should transparently
re-establish it.
"""
- with test.runner.get_runner().get_tor_socket(False) as control_socket:
+ async with await test.runner.get_runner().get_tor_socket(False) as control_socket:
for _ in range(5):
- protocolinfo_response = stem.connection.get_protocolinfo(control_socket)
+ protocolinfo_response = await stem.connection.get_protocolinfo(control_socket)
self.assert_matches_test_config(protocolinfo_response)
@test.require.controller
- def test_pre_disconnected_query(self):
+ @async_test
+ async def test_pre_disconnected_query(self):
"""
Tests making a PROTOCOLINFO query when previous use of the socket had
already disconnected it.
"""
- with test.runner.get_runner().get_tor_socket(False) as control_socket:
+ async with await test.runner.get_runner().get_tor_socket(False) as control_socket:
# makes a couple protocolinfo queries outside of get_protocolinfo first
- control_socket.send('PROTOCOLINFO 1')
- control_socket.recv()
+ await control_socket.send('PROTOCOLINFO 1')
+ await control_socket.recv()
- control_socket.send('PROTOCOLINFO 1')
- control_socket.recv()
+ await control_socket.send('PROTOCOLINFO 1')
+ await control_socket.recv()
- protocolinfo_response = stem.connection.get_protocolinfo(control_socket)
+ protocolinfo_response = await stem.connection.get_protocolinfo(control_socket)
self.assert_matches_test_config(protocolinfo_response)
def assert_matches_test_config(self, protocolinfo_response):
diff --git a/test/integ/socket/control_message.py b/test/integ/socket/control_message.py
index e0a4cca2..80bf4762 100644
--- a/test/integ/socket/control_message.py
+++ b/test/integ/socket/control_message.py
@@ -9,11 +9,13 @@ import stem.socket
import stem.version
import test.require
import test.runner
+from test.async_util import async_test
class TestControlMessage(unittest.TestCase):
@test.require.controller
- def test_unestablished_socket(self):
+ @async_test
+ async def test_unestablished_socket(self):
"""
Checks message parsing when we have a valid but unauthenticated socket.
"""
@@ -22,10 +24,10 @@ class TestControlMessage(unittest.TestCase):
# PROTOCOLINFO then tor will give an 'Authentication required.' message and
# hang up.
- control_socket = test.runner.get_runner().get_tor_socket(False)
- control_socket.send('GETINFO version')
+ control_socket = await test.runner.get_runner().get_tor_socket(False)
+ await control_socket.send('GETINFO version')
- auth_required_response = control_socket.recv()
+ auth_required_response = await control_socket.recv()
self.assertEqual('Authentication required.', str(auth_required_response))
self.assertEqual(['Authentication required.'], list(auth_required_response))
self.assertEqual('514 Authentication required.\r\n', auth_required_response.raw_content())
@@ -35,54 +37,64 @@ class TestControlMessage(unittest.TestCase):
# checked in more depth by the ControlSocket integ tests.
self.assertTrue(control_socket.is_alive())
- self.assertRaises(stem.SocketClosed, control_socket.recv)
+ with self.assertRaises(stem.SocketClosed):
+ await control_socket.recv()
self.assertFalse(control_socket.is_alive())
# Additional socket usage should fail, and pulling more responses will fail
# with more closed exceptions.
- self.assertRaises(stem.SocketError, control_socket.send, 'GETINFO version')
- self.assertRaises(stem.SocketClosed, control_socket.recv)
- self.assertRaises(stem.SocketClosed, control_socket.recv)
- self.assertRaises(stem.SocketClosed, control_socket.recv)
+ with self.assertRaises(stem.SocketClosed):
+ await control_socket.send('GETINFO version')
+ with self.assertRaises(stem.SocketClosed):
+ await control_socket.recv()
+ with self.assertRaises(stem.SocketClosed):
+ await control_socket.recv()
+ with self.assertRaises(stem.SocketClosed):
+ await control_socket.recv()
# The socket connection is already broken so calling close shouldn't have
# an impact.
- control_socket.close()
- self.assertRaises(stem.SocketClosed, control_socket.send, 'GETINFO version')
- self.assertRaises(stem.SocketClosed, control_socket.recv)
+ await control_socket.close()
+ with self.assertRaises(stem.SocketClosed):
+ await control_socket.send('GETINFO version')
+ with self.assertRaises(stem.SocketClosed):
+ await control_socket.recv()
@test.require.controller
- def test_invalid_command(self):
+ @async_test
+ async def test_invalid_command(self):
"""
Parses the response for a command which doesn't exist.
"""
- with test.runner.get_runner().get_tor_socket() as control_socket:
- control_socket.send('blarg')
- unrecognized_command_response = control_socket.recv()
+ async with await test.runner.get_runner().get_tor_socket() as control_socket:
+ await control_socket.send('blarg')
+ unrecognized_command_response = await control_socket.recv()
self.assertEqual('Unrecognized command "blarg"', str(unrecognized_command_response))
self.assertEqual(['Unrecognized command "blarg"'], list(unrecognized_command_response))
self.assertEqual('510 Unrecognized command "blarg"\r\n', unrecognized_command_response.raw_content())
self.assertEqual([('510', ' ', 'Unrecognized command "blarg"')], unrecognized_command_response.content())
@test.require.controller
- def test_invalid_getinfo(self):
+ @async_test
+ async def test_invalid_getinfo(self):
"""
Parses the response for a GETINFO query which doesn't exist.
"""
- with test.runner.get_runner().get_tor_socket() as control_socket:
- control_socket.send('GETINFO blarg')
- unrecognized_key_response = control_socket.recv()
+ async with await test.runner.get_runner().get_tor_socket() as control_socket:
+ await control_socket.send('GETINFO blarg')
+ unrecognized_key_response = await control_socket.recv()
self.assertEqual('Unrecognized key "blarg"', str(unrecognized_key_response))
self.assertEqual(['Unrecognized key "blarg"'], list(unrecognized_key_response))
self.assertEqual('552 Unrecognized key "blarg"\r\n', unrecognized_key_response.raw_content())
self.assertEqual([('552', ' ', 'Unrecognized key "blarg"')], unrecognized_key_response.content())
@test.require.controller
- def test_getinfo_config_file(self):
+ @async_test
+ async def test_getinfo_config_file(self):
"""
Parses the 'GETINFO config-file' response.
"""
@@ -90,16 +102,17 @@ class TestControlMessage(unittest.TestCase):
runner = test.runner.get_runner()
torrc_dst = runner.get_torrc_path()
- with runner.get_tor_socket() as control_socket:
- control_socket.send('GETINFO config-file')
- config_file_response = control_socket.recv()
+ async with await runner.get_tor_socket() as control_socket:
+ await control_socket.send('GETINFO config-file')
+ config_file_response = await control_socket.recv()
self.assertEqual('config-file=%s\nOK' % torrc_dst, str(config_file_response))
self.assertEqual(['config-file=%s' % torrc_dst, 'OK'], list(config_file_response))
self.assertEqual('250-config-file=%s\r\n250 OK\r\n' % torrc_dst, config_file_response.raw_content())
self.assertEqual([('250', '-', 'config-file=%s' % torrc_dst), ('250', ' ', 'OK')], config_file_response.content())
@test.require.controller
- def test_getinfo_config_text(self):
+ @async_test
+ async def test_getinfo_config_text(self):
"""
Parses the 'GETINFO config-text' response.
"""
@@ -120,9 +133,9 @@ class TestControlMessage(unittest.TestCase):
if line and not line.startswith('#'):
torrc_contents.append(line)
- with runner.get_tor_socket() as control_socket:
- control_socket.send('GETINFO config-text')
- config_text_response = control_socket.recv()
+ async with await runner.get_tor_socket() as control_socket:
+ await control_socket.send('GETINFO config-text')
+ config_text_response = await control_socket.recv()
# the response should contain two entries, the first being a data response
self.assertEqual(2, len(list(config_text_response)))
@@ -140,14 +153,15 @@ class TestControlMessage(unittest.TestCase):
self.assertTrue('%s' % torrc_entry in config_text_response.content()[0][2])
@test.require.controller
- def test_setconf_event(self):
+ @async_test
+ async def test_setconf_event(self):
"""
Issues 'SETEVENTS CONF_CHANGED' and parses an events.
"""
- with test.runner.get_runner().get_tor_socket() as control_socket:
- control_socket.send('SETEVENTS CONF_CHANGED')
- setevents_response = control_socket.recv()
+ async with await test.runner.get_runner().get_tor_socket() as control_socket:
+ await control_socket.send('SETEVENTS CONF_CHANGED')
+ setevents_response = await control_socket.recv()
self.assertEqual('OK', str(setevents_response))
self.assertEqual(['OK'], list(setevents_response))
self.assertEqual('250 OK\r\n', setevents_response.raw_content())
@@ -156,9 +170,9 @@ class TestControlMessage(unittest.TestCase):
# We'll receive both a CONF_CHANGED event and 'OK' response for the
# SETCONF, but not necessarily in any specific order.
- control_socket.send('SETCONF NodeFamily=FD4CC275C5AA4D27A487C6CA29097900F85E2C33')
- msg1 = control_socket.recv()
- msg2 = control_socket.recv()
+ await control_socket.send('SETCONF NodeFamily=FD4CC275C5AA4D27A487C6CA29097900F85E2C33')
+ msg1 = await control_socket.recv()
+ msg2 = await control_socket.recv()
if msg1.content()[0][0] == '650':
conf_changed_event, setconf_response = msg1, msg2
diff --git a/test/integ/socket/control_socket.py b/test/integ/socket/control_socket.py
index f479892c..bb2d8873 100644
--- a/test/integ/socket/control_socket.py
+++ b/test/integ/socket/control_socket.py
@@ -8,6 +8,7 @@ those focus on parsing and correctness of the content these are more concerned
with the behavior of the socket itself.
"""
+import asyncio
import time
import unittest
@@ -17,11 +18,13 @@ import stem.socket
import test
import test.require
import test.runner
+from test.async_util import async_test
class TestControlSocket(unittest.TestCase):
@test.require.controller
- def test_connection_time(self):
+ @async_test
+ async def test_connection_time(self):
"""
Checks that our connection_time method tracks when our state's changed.
"""
@@ -29,7 +32,7 @@ class TestControlSocket(unittest.TestCase):
test_start = time.time()
runner = test.runner.get_runner()
- with runner.get_tor_socket() as control_socket:
+ async with await runner.get_tor_socket() as control_socket:
connection_time = control_socket.connection_time()
# connection time should be between our tests start and now
@@ -38,54 +41,58 @@ class TestControlSocket(unittest.TestCase):
# connection time should be absolute (shouldn't change as time goes on)
- time.sleep(0.001)
+ await asyncio.sleep(0.001)
self.assertEqual(connection_time, control_socket.connection_time())
# should change to the disconnection time if we detactch
- control_socket.close()
+ await control_socket.close()
disconnection_time = control_socket.connection_time()
self.assertTrue(connection_time < disconnection_time <= time.time())
# then change again if we reconnect
- time.sleep(0.001)
- control_socket.connect()
+ await asyncio.sleep(0.001)
+ await control_socket.connect()
reconnection_time = control_socket.connection_time()
self.assertTrue(disconnection_time < reconnection_time <= time.time())
@test.require.controller
- def test_send_buffered(self):
+ @async_test
+ async def test_send_buffered(self):
"""
Sends multiple requests before receiving back any of the replies.
"""
runner = test.runner.get_runner()
- with runner.get_tor_socket() as control_socket:
+ async with await runner.get_tor_socket() as control_socket:
for _ in range(100):
- control_socket.send('GETINFO version')
+ await control_socket.send('GETINFO version')
for _ in range(100):
- response = control_socket.recv()
+ response = await control_socket.recv()
self.assertTrue(str(response).startswith('version=%s' % test.tor_version()))
self.assertTrue(str(response).endswith('\nOK'))
@test.require.controller
- def test_send_closed(self):
+ @async_test
+ async def test_send_closed(self):
"""
Sends a message after we've closed the connection.
"""
- with test.runner.get_runner().get_tor_socket() as control_socket:
+ async with await test.runner.get_runner().get_tor_socket() as control_socket:
self.assertTrue(control_socket.is_alive())
- control_socket.close()
+ await control_socket.close()
self.assertFalse(control_socket.is_alive())
- self.assertRaises(stem.SocketClosed, control_socket.send, 'blarg')
+ with self.assertRaises(stem.SocketClosed):
+ await control_socket.send('blarg')
@test.require.controller
- def test_send_disconnected(self):
+ @async_test
+ async def test_send_disconnected(self):
"""
Sends a message to a socket that has been disconnected by the other end.
@@ -95,64 +102,71 @@ class TestControlSocket(unittest.TestCase):
call. With a file socket, however, we'll also fail when calling send().
"""
- with test.runner.get_runner().get_tor_socket() as control_socket:
- control_socket.send('QUIT')
- self.assertEqual('closing connection', str(control_socket.recv()))
+ async with await test.runner.get_runner().get_tor_socket() as control_socket:
+ await control_socket.send('QUIT')
+ self.assertEqual('closing connection', str(await control_socket.recv()))
self.assertTrue(control_socket.is_alive())
# If we send another message to a port based socket then it will seem to
# succeed. However, a file based socket should report a failure.
if isinstance(control_socket, stem.socket.ControlPort):
- control_socket.send('blarg')
+ await control_socket.send('blarg')
self.assertTrue(control_socket.is_alive())
else:
- self.assertRaises(stem.SocketClosed, control_socket.send, 'blarg')
+ with self.assertRaises(stem.SocketClosed):
+ await control_socket.send('blarg')
self.assertFalse(control_socket.is_alive())
@test.require.controller
- def test_recv_closed(self):
+ @async_test
+ async def test_recv_closed(self):
"""
Receives a message after we've closed the connection.
"""
- with test.runner.get_runner().get_tor_socket() as control_socket:
+ async with await test.runner.get_runner().get_tor_socket() as control_socket:
self.assertTrue(control_socket.is_alive())
- control_socket.close()
+ await control_socket.close()
self.assertFalse(control_socket.is_alive())
- self.assertRaises(stem.SocketClosed, control_socket.recv)
+ with self.assertRaises(stem.SocketClosed):
+ await control_socket.recv()
@test.require.controller
- def test_recv_disconnected(self):
+ @async_test
+ async def test_recv_disconnected(self):
"""
Receives a message from a socket that has been disconnected by the other
end.
"""
- with test.runner.get_runner().get_tor_socket() as control_socket:
- control_socket.send('QUIT')
- self.assertEqual('closing connection', str(control_socket.recv()))
+ async with await test.runner.get_runner().get_tor_socket() as control_socket:
+ await control_socket.send('QUIT')
+ self.assertEqual('closing connection', str(await control_socket.recv()))
# Neither a port or file based socket will know that tor has hung up on
# the connection at this point. We should know after calling recv(),
# however.
self.assertTrue(control_socket.is_alive())
- self.assertRaises(stem.SocketClosed, control_socket.recv)
+ with self.assertRaises(stem.SocketClosed):
+ await control_socket.recv()
self.assertFalse(control_socket.is_alive())
@test.require.controller
- def test_connect_repeatedly(self):
+ @async_test
+ async def test_connect_repeatedly(self):
"""
Checks that we can reconnect, use, and disconnect a socket repeatedly.
"""
- with test.runner.get_runner().get_tor_socket(False) as control_socket:
+ async with await test.runner.get_runner().get_tor_socket(False) as control_socket:
for _ in range(10):
# this will raise if the PROTOCOLINFO query fails
- stem.connection.get_protocolinfo(control_socket)
+ await stem.connection.get_protocolinfo(control_socket)
- control_socket.close()
- self.assertRaises(stem.SocketClosed, control_socket.send, 'PROTOCOLINFO 1')
- control_socket.connect()
+ await control_socket.close()
+ with self.assertRaises(stem.SocketClosed):
+ await control_socket.send('PROTOCOLINFO 1')
+ await control_socket.connect()
diff --git a/test/integ/util/connection.py b/test/integ/util/connection.py
index f1745ec0..c35d8448 100644
--- a/test/integ/util/connection.py
+++ b/test/integ/util/connection.py
@@ -13,11 +13,13 @@ import test.require
import test.runner
from stem.util.connection import Resolver
+from test.async_util import async_test
class TestConnection(unittest.TestCase):
@test.require.ptrace
- def check_resolver(self, resolver):
+ @async_test
+ async def check_resolver(self, resolver):
runner = test.runner.get_runner()
if test.runner.Torrc.PORT not in runner.get_options():
@@ -25,7 +27,7 @@ class TestConnection(unittest.TestCase):
elif resolver not in stem.util.connection.system_resolvers():
self.skipTest('(resolver unavailable on this platform)')
- with runner.get_tor_socket():
+ async with await runner.get_tor_socket():
connections = stem.util.connection.get_connections(resolver, process_pid = runner.get_pid())
for conn in connections:
diff --git a/test/integ/util/proc.py b/test/integ/util/proc.py
index 315082d5..4038984c 100644
--- a/test/integ/util/proc.py
+++ b/test/integ/util/proc.py
@@ -10,6 +10,7 @@ import test.require
import test.runner
from stem.util import proc
+from test.async_util import async_test
class TestProc(unittest.TestCase):
@@ -63,7 +64,8 @@ class TestProc(unittest.TestCase):
@test.require.proc
@test.require.ptrace
- def test_connections(self):
+ @async_test
+ async def test_connections(self):
"""
Checks for our control port in the stem.util.proc.connections output if
we have one.
@@ -78,7 +80,7 @@ class TestProc(unittest.TestCase):
self.skipTest('(proc lacks read permissions)')
# making a controller connection so that we have something to query for
- with runner.get_tor_socket():
+ async with await runner.get_tor_socket():
tor_pid = test.runner.get_runner().get_pid()
for conn in proc.connections(tor_pid):
diff --git a/test/integ/version.py b/test/integ/version.py
index 641629d4..d02014a5 100644
--- a/test/integ/version.py
+++ b/test/integ/version.py
@@ -8,6 +8,7 @@ import unittest
import stem.version
import test.require
import test.runner
+from test.async_util import async_test
class TestVersion(unittest.TestCase):
@@ -30,16 +31,17 @@ class TestVersion(unittest.TestCase):
self.assertRaises(IOError, stem.version.get_system_tor_version, 'blarg')
@test.require.controller
- def test_getinfo_version_parsing(self):
+ @async_test
+ async def test_getinfo_version_parsing(self):
"""
Issues a 'GETINFO version' query to our test instance and makes sure that
we can parse it.
"""
- control_socket = test.runner.get_runner().get_tor_socket()
- control_socket.send('GETINFO version')
- version_response = control_socket.recv()
- control_socket.close()
+ control_socket = await test.runner.get_runner().get_tor_socket()
+ await control_socket.send('GETINFO version')
+ version_response = await control_socket.recv()
+ await control_socket.close()
# the getinfo response looks like...
# 250-version=0.2.3.10-alpha-dev (git-65420e4cb5edcd02)
diff --git a/test/runner.py b/test/runner.py
index a8079908..4a38e824 100644
--- a/test/runner.py
+++ b/test/runner.py
@@ -32,6 +32,7 @@ about the tor test instance they're running against.
+- get_tor_command - provides the command used to start tor
"""
+import asyncio
import logging
import os
import shutil
@@ -86,8 +87,8 @@ class TorInaccessable(Exception):
'Raised when information is needed from tor but the instance we have is inaccessible'
-def exercise_controller(test_case, controller):
- """
+async def exercise_controller(test_case, controller):
+ """with await test.runner.get_runner().get_tor_socket
Checks that we can now use the socket by issuing a 'GETINFO config-file'
query. Controller can be either a :class:`stem.socket.ControlSocket` or
:class:`stem.control.BaseController`.
@@ -100,10 +101,12 @@ def exercise_controller(test_case, controller):
torrc_path = runner.get_torrc_path()
if isinstance(controller, stem.socket.ControlSocket):
- controller.send('GETINFO config-file')
- config_file_response = controller.recv()
+ await controller.send('GETINFO config-file')
+ config_file_response = await controller.recv()
else:
config_file_response = controller.msg('GETINFO config-file')
+ if asyncio.iscoroutine(config_file_response):
+ config_file_response = await config_file_response
test_case.assertEqual('config-file=%s\nOK' % torrc_path, str(config_file_response))
@@ -134,8 +137,8 @@ class _MockChrootFile(object):
self.wrapped_file = wrapped_file
self.strip_text = strip_text
- def readline(self):
- return self.wrapped_file.readline().replace(self.strip_text, '')
+ async def readline(self):
+ return (await self.wrapped_file.readline()).replace(self.strip_text, '')
class Runner(object):
@@ -252,13 +255,15 @@ class Runner(object):
self._original_recv_message = stem.socket.recv_message
self._chroot_path = data_dir_path
- def _chroot_recv_message(control_file):
- return self._original_recv_message(_MockChrootFile(control_file, data_dir_path))
+ async def _chroot_recv_message(control_file):
+ return await self._original_recv_message(_MockChrootFile(control_file, data_dir_path))
stem.socket.recv_message = _chroot_recv_message
if self.is_accessible():
- self._owner_controller = self.get_tor_controller(True)
+ self._owner_controller = stem.control.Controller(self._get_unconnected_socket(), False)
+ self._owner_controller.connect()
+ self._authenticate_controller(self._owner_controller)
if test.Target.RELATIVE in self.attribute_targets:
os.chdir(original_cwd) # revert our cwd back to normal
@@ -440,7 +445,17 @@ class Runner(object):
tor_process = self._get('_tor_process')
return tor_process.pid
- def get_tor_socket(self, authenticate = True):
+ def _get_unconnected_socket(self):
+ if Torrc.PORT in self._custom_opts:
+ control_socket = stem.socket.ControlPort(port = CONTROL_PORT)
+ elif Torrc.SOCKET in self._custom_opts:
+ control_socket = stem.socket.ControlSocketFile(CONTROL_SOCKET_PATH)
+ else:
+ raise TorInaccessable('Unable to connect to tor')
+
+ return control_socket
+
+ async def get_tor_socket(self, authenticate = True):
"""
Provides a socket connected to our tor test instance.
@@ -451,19 +466,18 @@ class Runner(object):
:raises: :class:`test.runner.TorInaccessable` if tor can't be connected to
"""
- if Torrc.PORT in self._custom_opts:
- control_socket = stem.socket.ControlPort(port = CONTROL_PORT)
- elif Torrc.SOCKET in self._custom_opts:
- control_socket = stem.socket.ControlSocketFile(CONTROL_SOCKET_PATH)
- else:
- raise TorInaccessable('Unable to connect to tor')
+ control_socket = self._get_unconnected_socket()
+ await control_socket.connect()
if authenticate:
- stem.connection.authenticate(control_socket, CONTROL_PASSWORD, self.get_chroot())
+ await stem.connection.authenticate(control_socket, CONTROL_PASSWORD, self.get_chroot())
return control_socket
- def get_tor_controller(self, authenticate = True):
+ def _authenticate_controller(self, controller):
+ controller.authenticate(password=CONTROL_PASSWORD, chroot_path=self.get_chroot())
+
+ async def get_tor_controller(self, authenticate = True):
"""
Provides a controller connected to our tor test instance.
@@ -474,11 +488,19 @@ class Runner(object):
:raises: :class: `test.runner.TorInaccessable` if tor can't be connected to
"""
- control_socket = self.get_tor_socket(False)
- controller = stem.control.Controller(control_socket)
+ async_controller_thread = stem.control._AsyncControllerThread()
+ async_controller_thread.start()
+
+ try:
+ control_socket = asyncio.run_coroutine_threadsafe(self.get_tor_socket(False), async_controller_thread.loop).result()
+ controller = stem.control.Controller(control_socket, started_async_controller_thread = async_controller_thread)
+ except Exception:
+ if async_controller_thread.is_alive():
+ async_controller_thread.join()
+ raise
if authenticate:
- controller.authenticate(password = CONTROL_PASSWORD, chroot_path = self.get_chroot())
+ self._authenticate_controller(controller)
return controller
diff --git a/test/unit/connection/authentication.py b/test/unit/connection/authentication.py
index 8df38c8f..5e59adae 100644
--- a/test/unit/connection/authentication.py
+++ b/test/unit/connection/authentication.py
@@ -18,7 +18,7 @@ from unittest.mock import patch
from stem.response import ControlMessage
from stem.util import log
-from test.unit.async_util import (
+from test.async_util import (
async_test,
coro_func_raising_exc,
coro_func_returning_value,
diff --git a/test/unit/connection/connect.py b/test/unit/connection/connect.py
index 2112f678..3a0e0767 100644
--- a/test/unit/connection/connect.py
+++ b/test/unit/connection/connect.py
@@ -11,7 +11,7 @@ import stem.socket
from unittest.mock import Mock, patch
-from test.unit.async_util import (
+from test.async_util import (
async_test,
coro_func_raising_exc,
coro_func_returning_value,
diff --git a/test/unit/control/controller.py b/test/unit/control/controller.py
index 99bd5f19..4c03dea3 100644
--- a/test/unit/control/controller.py
+++ b/test/unit/control/controller.py
@@ -21,7 +21,7 @@ from stem import ControllerError, DescriptorUnavailable, InvalidArguments, Inval
from stem.control import MALFORMED_EVENTS, _parse_circ_path, Listener, Controller, EventType
from stem.response import ControlMessage
from stem.exit_policy import ExitPolicy
-from test.unit.async_util import (
+from test.async_util import (
async_test,
coro_func_raising_exc,
coro_func_returning_value,
1
0