Commit a2cfcf22 authored by Dom Sekotill's avatar Dom Sekotill
Browse files

Use subTest context to reset selected mocks

This ensures mocks are reset in the event of exceptions being raised,
thus preventing subsequent subTests from failing due to poisoned mocks.
parent c800d570
Loading
Loading
Loading
Loading
+25 −14
Original line number Diff line number Diff line
@@ -17,6 +17,7 @@ Test cases for wpa_supplicant.client.interfaces.InterfaceClient
"""

import unittest
from contextlib import contextmanager
from unittest.mock import call

from tests import _anyio as anyio_mock
@@ -34,6 +35,15 @@ class MethodsTests(unittest.TestCase):
		client.sock = anyio_mock.AsyncMock()
		client.sock.send.return_value = None

	@contextmanager
	def subTest(self, *args, reset=[], **kwargs):
		with super().subTest(*args, **kwargs):
			try:
				yield
			finally:
				for mock in reset:
					mock.reset_mock()

	@anyio_mock.with_anyio()
	async def test_scan(self):
		"""
@@ -63,36 +73,37 @@ class MethodsTests(unittest.TestCase):
			client.sock.receive.return_value = b"OK"
			send = client.sock.send

			with self.subTest("good string"):
			with self.subTest("good string", reset=[send]):
				await client.set_network("0", "ssid", "example")
				send.assert_called_once_with(b'SET_NETWORK 0 ssid "example"')
				send.reset_mock()

			with self.subTest("good int"):
			with self.subTest("good int", reset=[send]):
				await client.set_network("0", "priority", 1)
				send.assert_called_once_with(b"SET_NETWORK 0 priority 1")
				send.reset_mock()

			with self.subTest("good enum"):
			with self.subTest("good enum", reset=[send]):
				await client.set_network("0", "key_mgmt", config.KeyManagementValue.WPA_PSK)  # type: ignore
				send.assert_called_once_with(b"SET_NETWORK 0 key_mgmt WPA-PSK")
				send.reset_mock()

			with self.subTest("int not a string"), self.assertRaises(TypeError):
			with \
					self.subTest("int not a string", reset=[send]), \
					self.assertRaises(TypeError):
				await client.set_network("0", "ssid", 1)
				send.reset_mock()

			with self.subTest("string not an int"), self.assertRaises(TypeError):
			with \
					self.subTest("string not an int", reset=[send]), \
					self.assertRaises(TypeError):
				await client.set_network("0", "priority", "example")
				send.reset_mock()

			with self.subTest("string not an enum"), self.assertRaises(TypeError):
			with \
					self.subTest("string not an enum", reset=[send]), \
					self.assertRaises(TypeError):
				await client.set_network("0", "key_mgmt", "example")
				send.reset_mock()

			with self.subTest("int not an enum"), self.assertRaises(TypeError):
			with \
					self.subTest("int not an enum", reset=[send]), \
					self.assertRaises(TypeError):
				await client.set_network("0", "key_mgmt", 1)
				send.reset_mock()

	@anyio_mock.with_anyio()
	async def test_add_network(self):