async def test_price(app: App, mocker: MockerFixture): """测试查价""" from nonebot import get_driver from nonebot.adapters.onebot.v11 import Adapter, Bot, Message from nonebug.mixin.call_api.fake import make_fake_adapter, make_fake_bot from src.plugins.ff14 import price_cmd get = mocker.patch("httpx.AsyncClient.get", side_effect=mocked_get) async with app.test_matcher(price_cmd) as ctx: adapter = make_fake_adapter(Adapter)(get_driver(), ctx) bot = make_fake_bot(Bot)(adapter, "1") event = fake_group_message_event(message=Message("/查价 萨维奈舞裙 猫小胖")) ctx.receive_event(bot, event) ctx.should_call_send( event, "萨维奈舞裙 在市场的价格是:\n233100*1 服务器: 静语庄园\n233193*1 HQ 服务器: 静语庄园\n233330*1 服务器: 静语庄园\n233334*1 服务器: 静语庄园\n239166*1 HQ 服务器: 紫水栈桥\n239166*1 HQ 服务器: 紫水栈桥\n数据更新时间: 2021年12月29日 05时00分", True, ) ctx.should_finished() get.assert_has_calls([ mocker.call("https://cafemaker.wakingsands.com/search?string=萨维奈舞裙"), mocker.call("https://universalis.app/api/v2/猫小胖/10393?listings=6"), ])
def test_create_opc_client( event_loop: asyncio.AbstractEventLoop, expect_user_pass: bool, mocker: MockerFixture, url: str, with_cert_file: bool, ) -> None: mocked_asyncua_client = mocker.patch("asyncua.Client") mocked_asyncua_client.return_value.set_security = mocker.AsyncMock() config = mocker.Mock(server_url=url) if with_cert_file: config.configure_mock(cert_file="certFile", private_key_file="keyFile") else: config.configure_mock(cert_file=None, private_key_file=None) opcua_client = OPCUAClient(config, mocker.Mock(), mocker.Mock(), mocker.Mock()) created_client = event_loop.run_until_complete( opcua_client._create_opc_client()) assert mocked_asyncua_client.call_args_list == [ mocker.call(url="//opc/server.url") ] set_user = cast(Mock, created_client.set_user) set_password = cast(Mock, created_client.set_password) expected_set_user_call = [] expected_set_pw_call = [] expected_set_security_call = [] if expect_user_pass: expected_set_user_call.append(mocker.call("user")) expected_set_pw_call.append(mocker.call("pass")) if with_cert_file: expected_set_security_call.append( mocker.call(SecurityPolicyBasic256Sha256, "certFile", "keyFile")) assert set_user.call_args_list == expected_set_user_call assert set_password.call_args_list == expected_set_pw_call assert created_client.set_security.await_args_list == expected_set_security_call
def test_datachange_notification( influx_write: bool, mocker: MockerFixture, node_id: str, opcua_client: OPCUAClient, ) -> None: data_change_message_mock = mocker.patch( "opcua_webhmi_bridge.opcua.OPCDataChangeMessage") node = mocker.Mock() node.configure_mock(**{"nodeid.Identifier": node_id}) value = mocker.sentinel.value mocker.patch.object(opcua_client, "set_status") opcua_client.datachange_notification(node, value, mocker.Mock()) set_status = cast(Mock, opcua_client.set_status) message_instance = data_change_message_mock.return_value assert set_status.call_args_list == [mocker.call(LinkStatus.Up)] assert data_change_message_mock.call_args_list == [ mocker.call(node_id=node_id, ua_object=value) ] record_last_opc_data = cast( Mock, opcua_client._centrifugo_proxy_server.record_last_opc_data) assert record_last_opc_data.call_args_list == [ mocker.call(message_instance) ] messaging_writer_put = cast(Mock, opcua_client._frontend_messaging_writer.put) assert messaging_writer_put.call_args_list == [ mocker.call(message_instance) ] influx_writer_put = cast(Mock, opcua_client._influx_writer.put) expected_influx_put_call = [mocker.call(message_instance) ] if influx_write else [] assert influx_writer_put.call_args_list == expected_influx_put_call
def test_show_typing_notification( self, mocker: MockerFixture, controller: Controller, active_conversation_info: Dict[str, str], ) -> None: set_footer_text = mocker.patch(VIEW + ".set_footer_text") sleep = mocker.patch(MODULE + ".time.sleep") controller.active_conversation_info = active_conversation_info def mock_typing() -> None: controller.active_conversation_info = {} Timer(0.1, mock_typing).start() Thread(controller.show_typing_notification()).start() if active_conversation_info: set_footer_text.assert_has_calls( [ mocker.call([("footer_contrast", " hamlet "), " is typing"]), mocker.call([("footer_contrast", " hamlet "), " is typing."]), mocker.call([("footer_contrast", " hamlet "), " is typing.."]), mocker.call([("footer_contrast", " hamlet "), " is typing..."]), ] ) set_footer_text.assert_called_with() else: set_footer_text.assert_called_once_with() assert controller.is_typing_notification_in_progress is False assert controller.active_conversation_info == {}
async def test_roll_complex( app: App, mocker: MockerFixture, ): """测试点数,复杂点的输入""" from nonebot import get_driver from nonebot.adapters.onebot.v11 import Adapter, Bot, Message from nonebug.mixin.call_api.fake import make_fake_adapter, make_fake_bot from src.plugins.roll import roll_cmd randint = mocker.patch("src.plugins.roll.roll.randint") randint.return_value = 1 async with app.test_matcher(roll_cmd) as ctx: adapter = make_fake_adapter(Adapter)(get_driver(), ctx) bot = make_fake_bot(Bot)(adapter, "1") event = fake_group_message_event(message=Message("/roll d100+2d50")) ctx.receive_event(bot, event) ctx.should_call_send( event, "d100+2d50=d100(1)+d50(1)+d50(1)=3", "result", at_sender=True, ) ctx.should_finished() randint.assert_has_calls( [ mocker.call(1, 100), mocker.call(1, 50), mocker.call(1, 50), ] )
def test_generic_wrapper_proxy_when_not_terminating(mocker: MockerFixture): """ Checks behaviour when proxy cannot be terminated, but can be killed. """ # Create fake proxy class that dies right away class ActualProxy(AbstractWrapper): def __enter__(self): self._proxy = subprocess.Popen("/bin/true") return self def _readiness_check(self): return True # Ensure that communicate() is called three times (no action, terminate, kill). # Also ensure that the first two communicate() raise a timeout exception. mocker.patch.object(subprocess.Popen, 'communicate', side_effect=[ subprocess.TimeoutExpired("cmd", 0), subprocess.TimeoutExpired("cmd", 0), (b'stdout', b'stderr'), ]) mocker.patch.object(subprocess.Popen, 'terminate') with ActualProxy() as p: p.wait_for_readiness() subprocess.Popen.terminate.assert_called_once_with() subprocess.Popen.communicate.assert_has_calls([ mocker.call(input=None, timeout=1), mocker.call(input=None, timeout=1), mocker.call(input=None, timeout=1) ])
async def test_price_world_not_found(app: App, mocker: MockerFixture): """测试查价,服务器/大区不存在""" from nonebot import get_driver from nonebot.adapters.onebot.v11 import Adapter, Bot, Message from nonebug.mixin.call_api.fake import make_fake_adapter, make_fake_bot from src.plugins.ff14 import price_cmd get = mocker.patch("httpx.AsyncClient.get", side_effect=mocked_get) async with app.test_matcher(price_cmd) as ctx: adapter = make_fake_adapter(Adapter)(get_driver(), ctx) bot = make_fake_bot(Bot)(adapter, "1") event = fake_group_message_event(message=Message("/查价 萨维奈舞裙 静语")) ctx.receive_event(bot, event) ctx.should_call_send( event, "抱歉,没有找到 静语 的数据,请检查大区或服务器名称是否正确。", True, ) ctx.should_finished() get.assert_has_calls([ mocker.call("https://cafemaker.wakingsands.com/search?string=萨维奈舞裙"), mocker.call("https://universalis.app/api/v2/静语/10393?listings=6"), ])
def test_database_connect(mocker: MockerFixture): db = MysqldbDatabase("loc", "user", "password", "database") mocker.patch.object(MySQLdb, "connect") query = mocker.MagicMock() query.return_value = [] mocker.patch.object(db, "query", query) db.connect() MySQLdb.connect.assert_has_calls([ mocker.call( "loc", "user", "password", "database", use_unicode=True, charset="utf8mb4", ) ]) query.assert_has_calls([mocker.call("show", "tables")]) db.close() db.query = lambda a, b: [{"": "foo"}] if a == "show" else [] query_spy = mocker.spy(db, "query") mocker.patch.object(db, "query", query_spy) db.connect() query_spy.assert_has_calls( [mocker.call("show", "tables"), mocker.call("describe", "foo")]) assert "foo" in db.table_names
def test_instance_method_by_class_spy(mocker: MockerFixture) -> None: class Foo: def bar(self, arg): return arg * 2 spy = mocker.spy(Foo, "bar") foo = Foo() other = Foo() assert foo.bar(arg=10) == 20 assert other.bar(arg=10) == 20 calls = [mocker.call(foo, arg=10), mocker.call(other, arg=10)] assert spy.call_args_list == calls
def test_run_pre_start_script_no_file( self, mock_logger: logging.Logger, mocker: MockerFixture, monkeypatch: MonkeyPatch, ) -> None: """Test `start.run_pre_start_script` with an incorrect file path.""" monkeypatch.setenv("PRE_START_PATH", "/no/file/here") start.run_pre_start_script(logger=mock_logger) mock_logger.debug.assert_has_calls( # type: ignore[attr-defined] calls=[ mocker.call("Checking for pre-start script."), mocker.call("No pre-start script found."), ])
def test_run_pre_start_script_no_file( self, mocker: MockerFixture, monkeypatch: pytest.MonkeyPatch, ) -> None: """Test `start.run_pre_start_script` with an incorrect file path.""" logger = mocker.patch.object(start.logging, "root", autospec=True) monkeypatch.setenv("PRE_START_PATH", "/no/file/here") start.run_pre_start_script(logger=logger) logger.debug.assert_has_calls( calls=[ mocker.call("Checking for pre-start script."), mocker.call("No pre-start script found."), ] )
def test_authenticate_bad_key_good_key_input( local_dandi_api: DandiAPI, mocker: MockerFixture, monkeypatch: pytest.MonkeyPatch) -> None: good_key = local_dandi_api.api_key bad_key = "1234567890" client_name = local_dandi_api.instance_id app_id = f"dandi-api-{client_name}" backend_mock = mocker.Mock(spec=["set_password"]) keyring_lookup_mock = mocker.patch("dandi.dandiapi.keyring_lookup", return_value=(backend_mock, None)) input_mock = mocker.patch("dandi.dandiapi.input", side_effect=[bad_key, good_key]) is_interactive_mock = mocker.patch("dandi.dandiapi.is_interactive", return_value=True) confirm_mock = mocker.patch("click.confirm", return_value=True) monkeypatch.delenv("DANDI_API_KEY", raising=False) client = DandiAPIClient(local_dandi_api.api_url) assert "Authorization" not in client.session.headers client.dandi_authenticate() assert client.session.headers["Authorization"] == f"token {good_key}" backend_mock.set_password.assert_called_once_with(app_id, "key", good_key) keyring_lookup_mock.assert_called_once_with(app_id, "key") assert input_mock.call_args_list == ( [mocker.call(f"Please provide API Key for {client_name}: ")] * 2) is_interactive_mock.assert_called_once() confirm_mock.assert_called_once_with("API key is invalid; enter another?")
def test_status_changed( self, status_message_mock: Mock, mocker: MockerFixture, opcua_client: OPCUAClient, ) -> None: opcua_client.set_status(LinkStatus.Up) assert opcua_client._status == LinkStatus.Up messaging_writer_put = cast( Mock, opcua_client._frontend_messaging_writer.put) assert messaging_writer_put.call_args_list == [ mocker.call(status_message_mock.return_value) ] assert status_message_mock.call_args_list == [ mocker.call(payload=LinkStatus.Up) ]
def test_write_nx_ny_nz_true(mocker: MockerFixture, tmp_path, basic_regular_grid): # Arrange file_name = f'{tmp_path}/test' open_mock = mocker.mock_open() mocker.patch("builtins.open", open_mock) expected_calls = get_expected_calls(mocker, file_name) expected_calls[4:4] = [ mocker.call().write('NX NY NZ\n'), mocker.call().write('2 2 2 \n\n') ] # Act write_nexus_corp(basic_regular_grid, file_name, write_nx_ny_nz = True) # Assert open_mock.assert_has_calls(expected_calls)
def test_write_pure_binary_data(mocker: MockerFixture, caplog): # Arrange test_array = np.array([[[0, 0], [0, 0]], [[0, 0], [0, 0]]]) open_mock = mocker.mock_open() fileno_mock = mocker.Mock(return_value = 1, name = 'fileno_mock') open_mock.return_value.fileno = fileno_mock mocker.patch("builtins.open", open_mock) expected_calls = [mocker.call('test', 'wb'), mocker.call().__enter__()] # Act wd.write_pure_binary_data('test', test_array) # Assert open_mock.assert_has_calls(expected_calls) assert 'Binary data file test created' in caplog.text
def test_write_array_to_ascii_file_binary(mocker: MockerFixture, caplog): # Arrange test_extent = np.array([2, 2, 2]) test_array = np.array([[[0, 0], [0, 0]], [[0, 0], [0, 0]]]) open_mock = mocker.mock_open() fileno_mock = mocker.Mock(return_value = 1, name = 'fileno_mock') open_mock.return_value.fileno = fileno_mock mocker.patch("builtins.open", open_mock) expected_calls = [mocker.call('test.db', 'wb'), mocker.call().__enter__()] # Act wd.write_array_to_ascii_file('test', test_extent, test_array, use_binary = True, binary_only = True) # Assert open_mock.assert_has_calls(expected_calls) assert 'Failed to write data to binary file test' not in caplog.text
def test_write_array_to_ascii_file_no_headers(mocker: MockerFixture): # Arrange test_extent = np.array([2, 2, 2]) test_array = np.array([[[0, 0], [0, 0]], [[0, 0], [0, 0]]]) open_mock = mocker.mock_open() mocker.patch("builtins.open", open_mock) unexpected_calls = [ mocker.call().write('! Data written by write_array_to_ascii_file() python function\n'), mocker.call().write('! Extent of array is: [2, 2, 2]\n'), mocker.call().write('! Maximum 20 data items per line\n') ] # Act wd.write_array_to_ascii_file('test', test_extent, test_array, headers = False) # Assert assert unexpected_calls not in open_mock.mock_calls
def test_set_app_module( self, module: str, mocker: MockerFixture, monkeypatch: pytest.MonkeyPatch ) -> None: """Test `start.set_app_module` with default module path.""" logger = mocker.patch.object(start.logging, "root", autospec=True) monkeypatch.setenv("APP_MODULE", f"inboard.app.main_{module}:app") start.set_app_module(logger=logger) assert mocker.call(f"App module set to inboard.app.main_{module}:app.")
def test_run_pre_start_script_sh( self, mocker: MockerFixture, monkeypatch: pytest.MonkeyPatch, pre_start_script_tmp_sh: Path, ) -> None: """Test `start.run_pre_start_script` using temporary pre-start shell script.""" logger = mocker.patch.object(start.logging, "root", autospec=True) monkeypatch.setenv("PRE_START_PATH", str(pre_start_script_tmp_sh)) pre_start_path = os.getenv("PRE_START_PATH") start.run_pre_start_script(logger=logger) logger.debug.assert_has_calls( calls=[ mocker.call("Checking for pre-start script."), mocker.call(f"Running pre-start script with sh {pre_start_path}."), mocker.call(f"Ran pre-start script with sh {pre_start_path}."), ] )
def test_set_footer_text_with_duration( self, view: View, mocker: MockerFixture, custom_text: str = "custom", duration: Optional[float] = 5.3, ) -> None: mocker.patch(VIEW + ".get_random_help", return_value=["some help text"]) mock_sleep = mocker.patch("time.sleep") view.set_footer_text([custom_text], duration=duration) view.frame.footer.set_text.assert_has_calls( [mocker.call([custom_text]), mocker.call(["some help text"])]) mock_sleep.assert_called_once_with(duration) assert view.controller.update_screen.call_count == 2
async def test_publish_with_basedir( mocker: MockerFixture, fs: FakeFilesystem, root: Path, config: Config, ) -> None: """ Test ``publish`` when a base directory is specified. """ FTP = mocker.patch("nefelibata.publishers.ftp.FTP") ftp = FTP.return_value.__enter__.return_value ftp.pwd.return_value = "/ftp/upload" mocker.patch.object( FTPPublisher, "find_modified_files", return_value=iter( [root / "build/generic/subdir1/one", root / "build/generic/subdir2/two"], ), ) fs.create_file(root / "build/generic/subdir1/one", contents="Hello, world!") fs.create_file(root / "build/generic/subdir2/two", contents="Goodbye, world!") publisher = FTPPublisher( root, config, "generic", "ftp.example.com", "username", "password", "ftp/upload", ) await publisher.publish() ftp.cwd.assert_has_calls( [ mocker.call("ftp/upload"), mocker.call("subdir1"), mocker.call("/ftp/upload"), mocker.call("subdir2"), ], )
def test_initialize_controller( self, controller: Controller, mocker: MockerFixture ) -> None: self.client.assert_called_once_with( config_file=self.config_file, client="ZulipTerminal/" + ZT_VERSION + " " + platform(), ) self.model.assert_called_once_with(controller) self.view.assert_called_once_with(controller) self.poll_for_events.assert_called_once_with() assert controller.theme == self.theme assert controller.maximum_footlinks == self.maximum_footlinks assert self.main_loop.call_count == 1 controller.loop.watch_pipe.assert_has_calls( [ mocker.call(controller._draw_screen), mocker.call(controller._raise_exception), ] )
def test_run_pre_start_script_none(self, mocker: MockerFixture) -> None: """Test `start.run_pre_start_script` with `PRE_START_PATH` set to `None`.""" logger = mocker.patch.object(start.logging, "root", autospec=True) start.run_pre_start_script(logger=logger) logger.debug.assert_has_calls( calls=[ mocker.call("Checking for pre-start script."), mocker.call("No pre-start script specified."), ] )
def test_setup_cloudwatch_log_groups(fmt: str, mocker: MockerFixture) -> None: """A CloudWatchLog group should be created for each format""" mocker.patch(f"{__package__}.put_cloudwatch_logs.create_cloudwatch_log_group") d = "dest" r = "role" setup_cloudwatch_log_groups(d, r) call = mocker.call(f"/gds/test/{fmt}", d, r) assert call in put_cloudwatch_logs.create_cloudwatch_log_group.mock_calls # type: ignore # noqa: E501
def test_translator(mocker: MockerFixture): mocker.patch.object(MySQLdb, "escape_string") db = MysqldbDatabase("loc", "user", "password", "database") db.translator.escape_string("foo") MySQLdb.escape_string.assert_has_calls([mocker.call("foo")]) results, expect = None, None assert db.translator.interpret(results, method="foo", table="bar") == expect results, expect = ("foo", "bar"), ["foo", "bar"] assert db.translator.interpret(results, method="select", table="baz") == expect assert db.translator.interpret(results, method="distinct", table="baz") == expect results, expect = [["foo"]], "foo" assert (db.translator.interpret(results, method="count", table="bar", how=0) == expect) results, expect = [{"a": "foo"}], "foo" assert db.translator.interpret(results, method="count", table="bar") == expect results, expect = [("foo", "bar")], ["`foo` bar"] assert (db.translator.interpret(results, method="describe", table="baz", how=0) == expect) results, expect = [{ "COLUMNS.Field": "foo", "COLUMNS.Type": "bar" }], ["`foo` bar"] assert (db.translator.interpret(results, method="describe", table="baz", how=2) == expect) results, expect = [{"Field": "foo", "COLUMNS.Type": "bar"}], ["`foo` bar"] assert db.translator.interpret(results, method="describe", table="baz") == expect results, expect = [("foo", ), ("bar", )], ["foo", "bar"] assert (db.translator.interpret(results, method="show", table="tables", how=0) == expect) results, expect = [{"foo": "bar"}], ["bar"] assert db.translator.interpret(results, method="show", table="tables") == expect
def test_run_pre_start_script_sh( self, mock_logger: logging.Logger, mocker: MockerFixture, monkeypatch: MonkeyPatch, pre_start_script_tmp_sh: Path, ) -> None: """Test `start.run_pre_start_script` using temporary pre-start shell script.""" monkeypatch.setenv("PRE_START_PATH", str(pre_start_script_tmp_sh)) start.run_pre_start_script(logger=mock_logger) mock_logger.debug.assert_has_calls( # type: ignore[attr-defined] calls=[ mocker.call("Checking for pre-start script."), mocker.call( f"Running pre-start script with sh {os.getenv('PRE_START_PATH')}." ), mocker.call( f"Ran pre-start script with sh {os.getenv('PRE_START_PATH')}." ), ])
async def test_heweather_with_adm( app: App, mocker: MockerFixture, ): """测试和风天气,带行政区划""" from nonebot import get_driver from nonebot.adapters.onebot.v11 import Adapter, Bot, Message from nonebug.mixin.call_api.fake import make_fake_adapter, make_fake_bot from src.plugins.weather import weather_cmd from src.plugins.weather.heweather_api import plugin_config plugin_config.heweather_key = "1234567890" get = mocker.patch("httpx.AsyncClient.get", side_effect=mocked_get) async with app.test_matcher(weather_cmd) as ctx: adapter = make_fake_adapter(Adapter)(get_driver(), ctx) bot = make_fake_bot(Bot)(adapter, "1") event = fake_group_message_event(message=Message("/天气 成都 四川")) ctx.receive_event(bot, event) ctx.should_call_send( event, "中国 四川省 成都\n当前温度:9℃ 湿度:86%(体感温度:9℃)\n2022-01-08 阴转多云 温度:9~6℃ 峨眉月\n2022-01-09 多云转小雨 温度:10~7℃ 峨眉月\n2022-01-10 多云 温度:13~3℃ 上弦月", "result", ) ctx.should_finished() get.assert_has_calls([ mocker.call( "https://geoapi.qweather.com/v2/city/lookup?location=%E6%88%90%E9%83%BD&adm=%E5%9B%9B%E5%B7%9D&key=1234567890" ), mocker.call( "https://devapi.qweather.com/v7/weather/now?location=101270101&key=1234567890" ), mocker.call( "https://devapi.qweather.com/v7/weather/3d?location=101270101&key=1234567890" ), ])
def test_write_rh_keyword_if_needed_true(mocker: MockerFixture, tmp_path, basic_regular_grid): # Arrange file_name = f'{tmp_path}/test' open_mock = mocker.mock_open() mocker.patch("builtins.open", open_mock) expected_calls = get_expected_calls(mocker, file_name) expected_calls.insert(4, mocker.call().write('RIGHTHANDED\n\n')) # Act write_nexus_corp(basic_regular_grid, file_name, write_rh_keyword_if_needed = True) # Assert open_mock.assert_has_calls(expected_calls)
def test_local_coords_true(mocker: MockerFixture, tmp_path, basic_regular_grid): # Arrange file_name = f'{tmp_path}/test' open_mock = mocker.mock_open() mocker.patch("builtins.open", open_mock) expected_calls = get_expected_calls(mocker, file_name) expected_calls.insert(4, mocker.call().write('METRIC\n\n')) # Act write_nexus_corp(basic_regular_grid, file_name, write_units_keyword = True, local_coords = True) # Assert open_mock.assert_has_calls(expected_calls)
def test_write_array_to_ascii_file_append(mocker: MockerFixture): # Arrange test_extent = np.array([2, 2, 2]) test_array = np.array([[[0, 0], [0, 0]], [[0, 0], [0, 0]]]) open_mock = mocker.mock_open() mocker.patch("builtins.open", open_mock) expected_calls = [mocker.call('test', 'a')] # Act wd.write_array_to_ascii_file('test', test_extent, test_array, append = True) # Assert open_mock.assert_has_calls(expected_calls)