def test_mkdir_remote_get(self, monkeypatch: MonkeyPatch): class MockSSHShell: def run(self, cmd, exitcode=True): return True, "" class datetime: def strftime(time, fmt): return "20220609231003" def now(): pass scs = init_shared() scs.sshshell = MockSSHShell() scs.get_op = True scs.remote_file = "foobar" monkeypatch.setattr("datetime.datetime", datetime) result = scs.mkdir_remote() expected = "/var/tmp/splitcopy_foobar.20220609231003" assert expected == result
def test_looponfail_multiple_errors( self, pytester: pytest.Pytester, monkeypatch: pytest.MonkeyPatch) -> None: modcol = pytester.getmodulecol( textwrap.dedent(""" def test_one(): assert 0 """)) remotecontrol = RemoteControl(modcol.config) orig_runsession = remotecontrol.runsession def runsession_dups(): # twisted.trial test cases may report multiple errors. failures, reports, collection_failed = orig_runsession() print(failures) return failures * 2, reports, collection_failed monkeypatch.setattr(remotecontrol, "runsession", runsession_dups) remotecontrol.loop_once() assert len(remotecontrol.failures) == 1
def test_file_split_size_low_cpu_count(self, monkeypatch: MonkeyPatch): def cpu_count(): return 1 def pool_executor(max_workers, thread_name_prefix): return True scs = init_shared() monkeypatch.setattr("os.cpu_count", cpu_count) monkeypatch.setattr("concurrent.futures.ThreadPoolExecutor", pool_executor) file_size = 100000 sshd_version = 8.2 bsd_version = float() evo = False copy_proto = "scp" result = scs.file_split_size(file_size, sshd_version, bsd_version, evo, copy_proto) expected = 20000, True assert expected == result
def test_execute_automation_post_21(self, monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr( automations.request, "headers", {"x-checkmk-version": "2.1.0i1"}, ) automations.CheckmkAutomationBackgroundJob( "job_id", api_request := automations.CheckmkAutomationRequest( command="test", args=None, indata=None, stdin_data=None, timeout=None, ), ).execute_automation( MagicMock(), api_request, ) assert RESULT == "(2, None)"
def test_uninstall_non_local_distutils(caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch, tmpdir: Path) -> None: einfo = tmpdir.joinpath("thing-1.0.egg-info") with open(einfo, "wb"): pass get_dist = Mock() get_dist.return_value = Mock( key="thing", project_name="thing", egg_info=einfo, location=einfo, ) monkeypatch.setattr("pip._vendor.pkg_resources.get_distribution", get_dist) req = install_req_from_line("thing") req.uninstall() assert os.path.exists(einfo)
def test_get_install_target_to_platforms_map( platform_names: List[str], expected_map: Dict[str, Any], expected_err: Type[Exception], monkeypatch: pytest.MonkeyPatch): """Test that get_install_target_to_platforms_map works as expected.""" monkeypatch.setattr('cylc.flow.platforms.platform_from_name', lambda x: platform_from_name(x, PLATFORMS_TREK)) if expected_err: with pytest.raises(expected_err): get_install_target_to_platforms_map(platform_names) else: result = get_install_target_to_platforms_map(platform_names) # Sort the maps: for _map in (result, expected_map): for install_target in _map: _map[install_target] = sorted(_map[install_target], key=lambda k: k['name']) assert result == expected_map
def test_which_proto_ftp_success_with_password(self, monkeypatch: MonkeyPatch): class MockSSHShell: def __init__(self): self.kwargs = {} self.kwargs["password"] = "******" def ftp_port_check(): return True def ftp_login_check(passwd): return True scs = init_shared() scs.sshshell = MockSSHShell() monkeypatch.setattr(scs, "ftp_port_check", ftp_port_check) monkeypatch.setattr(scs, "ftp_login_check", ftp_login_check) result = scs.which_proto("ftp") expected = "ftp", "foobar" assert expected == result
def test_context_manager(self, monkeypatch: MonkeyPatch): def quit(self): pass monkeypatch.setattr(logging, "getLogger", mockgetlogger) monkeypatch.setattr("logging.Logger", MockLogger) monkeypatch.setattr("ftplib.FTP", mockFTP) monkeypatch.setattr(FTP, "quit", quit) ftp = init_ftp() with ftp as foo: result = True expected = True assert expected == result
def test_filechange_deletion_race(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: tmp = tmp_path pytmp = py.path.local(tmp) sd = StatRecorder([pytmp]) changed = sd.check() assert not changed p = tmp.joinpath("new.py") p.touch() changed = sd.check() assert changed p.unlink() # make check()'s visit() call return our just removed # path as if we were in a race condition monkeypatch.setattr(pytmp, "visit", lambda *args: [py.path.local(p)]) changed = sd.check() assert changed
def test_open_after_create(bus: Bus, monkeypatch: MonkeyPatch) -> None: """It opens the URL in a browser.""" event = events.PullRequestCreated( EXAMPLE_TEMPLATE, EXAMPLE_TEMPLATE_PULL, EXAMPLE_PROJECT_PULL, ) urls = [] def _webbrowser_open(url: str) -> None: urls.append(url) monkeypatch.setattr("webbrowser.open", _webbrowser_open) __main__.register_pull_request_viewer(bus=bus) bus.events.publish(event) assert urls == [event.template_pull.html_url]
def test_init_db_command(test_app: Flask, monkeypatch: MonkeyPatch): """Test init-db command.""" runner = test_app.test_cli_runner() class Recorder: drop_called: bool = False create_called: bool = False def fake_drop_all() -> None: Recorder.drop_called = True def fake_create_all() -> None: Recorder.create_called = True monkeypatch.setattr("app.db.drop_all", fake_drop_all) monkeypatch.setattr("app.db.create_all", fake_create_all) result = runner.invoke(args=["init-db"]) assert "Initialized database" in result.output assert Recorder.drop_called assert Recorder.create_called
def test_sys_modules(self, caplog: LogCaptureFixture, monkeypatch: MonkeyPatch) -> None: """Test sys.modules interactions.""" caplog.set_level(logging.DEBUG, "runway.SafeHaven") monkeypatch.setattr(SafeHaven, "reset_all", MagicMock()) # pylint: disable=unnecessary-comprehension orig_val = {k: v for k, v in sys.modules.items()} expected_logs = [ "entering a safe haven...", "resetting sys.modules..." ] with SafeHaven() as obj: from .fixtures import mock_hooks # noqa pylint: disable=E,W,C assert sys.modules != orig_val obj.reset_sys_modules() assert sys.modules == orig_val assert caplog.messages[:2] == expected_logs assert caplog.messages[-1] == "leaving the safe haven..."
def test_catching_api_error(self, caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch) -> None: """Test catching API error. Args: caplog: the built-in pytest fixture. monkeypatch: the built-in pytest fixture. """ def raise_exception(*args, **kwargs): # type: ignore """Mock function to raise an Exception.""" raise requests.exceptions.RequestException() monkeypatch.setattr(requests, "get", raise_exception) DOIParser().parse("10.1021/acs.chemrev.8b00803") assert ( "cobib.parsers.doi", logging.ERROR, "An Exception occurred while trying to query the DOI: 10.1021/acs.chemrev.8b00803.", ) in caplog.record_tuples
def test_detect_symlink_dirs(self, monkeypatch: pytest.MonkeyPatch, tmpdir: Path) -> None: monkeypatch.setattr(pip._internal.req.req_uninstall, "is_local", mock_is_local) # construct 2 paths: # tmpdir/dir/file # tmpdir/dirlink/file (where dirlink is a link to dir) d = tmpdir.joinpath("dir") d.mkdir() dlink = tmpdir.joinpath("dirlink") os.symlink(d, dlink) d.joinpath("file").touch() path1 = str(d.joinpath("file")) path2 = str(dlink.joinpath("file")) ups = UninstallPathSet(dist=Mock()) ups.add(path1) ups.add(path2) assert ups._paths == {path1}
def test_process_startcp(startcp: Optional[str], expected: str, monkeypatch: pytest.MonkeyPatch, set_cycling_type: Fixture) -> None: """Test WorkflowConfig.process_start_cycle_point(). An icp of 1899-05-01T00+0530 is assumed, and "now" is assumed to be 2005-01-02T06:15+0530 Params: startcp: The start cycle point given by cli option. expected: The expected startcp value that gets set. """ set_cycling_type(ISO8601_CYCLING_TYPE, time_zone="+0530") mocked_config = Mock(initial_point='18990501T0000+0530') mocked_config.options.startcp = startcp monkeypatch.setattr('cylc.flow.config.get_current_time_string', lambda: '20050102T0615+0530') WorkflowConfig.process_start_cycle_point(mocked_config) assert str(mocked_config.start_point) == expected
def test_generate_interactive_exitcode(monkeypatch: MonkeyPatch) -> None: """Check that we exit correctly based on different parameters.""" # Monkeypatch everything we don't want to check in this test monkeypatch.setattr( "pylint.config._pylint_config.utils.get_and_validate_format", lambda: "toml") monkeypatch.setattr( "pylint.config._pylint_config.utils.get_and_validate_output_file", lambda: (False, Path()), ) with warnings.catch_warnings(): warnings.filterwarnings("ignore", message="NOTE:.*", category=UserWarning) with pytest.raises(SystemExit) as ex: Run(["generate", "--interactive"]) assert ex.value.code == 0 Run(["generate", "--interactive"], exit=False)
def test_keyring_set_password( monkeypatch: pytest.MonkeyPatch, response_status: int, creds: Tuple[str, str, bool], expect_save: bool, ) -> None: keyring = KeyringModuleV1() monkeypatch.setattr("pip._internal.network.auth.keyring", keyring) auth = MultiDomainBasicAuth(prompting=True) monkeypatch.setattr(auth, "_get_url_and_credentials", lambda u: (u, None, None)) monkeypatch.setattr(auth, "_prompt_for_password", lambda *a: creds) if creds[2]: # when _prompt_for_password indicates to save, we should save def should_save_password_to_keyring(*a: Any) -> bool: return True else: # when _prompt_for_password indicates not to save, we should # never call this function def should_save_password_to_keyring(*a: Any) -> bool: assert False, "_should_save_password_to_keyring should not be called" monkeypatch.setattr(auth, "_should_save_password_to_keyring", should_save_password_to_keyring) req = MockRequest("https://example.com") resp = MockResponse(b"") resp.url = req.url connection = MockConnection() def _send(sent_req: MockRequest, **kwargs: Any) -> MockResponse: assert sent_req is req assert "Authorization" in sent_req.headers r = MockResponse(b"") r.status_code = response_status return r # https://github.com/python/mypy/issues/2427 connection._send = _send # type: ignore[assignment] resp.request = req resp.status_code = 401 resp.connection = connection auth.handle_401(resp) if expect_save: assert keyring.saved_passwords == [("example.com", creds[0], creds[1])] else: assert keyring.saved_passwords == []
def test_config_openable_fields( self, setup: Any, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], ) -> None: """Test the `config.commands.open.fields` setting. Args: setup: the `tests.commands.command_test.CommandTest.setup` fixture. monkeypatch: the built-in pytest fixture. capsys: the built-in pytest fixture. """ config.commands.open.fields = ["note"] with open(get_resource("example_multi_file_entry.yaml", "commands"), "r", encoding="utf-8") as multi_file_entry: with open(config.database.file, "a", encoding="utf-8") as database: for line in multi_file_entry.readlines(): if line == " file:\n": database.write(" note:\n") else: database.write(line) Database().read() monkeypatch.setattr("sys.stdin", MockStdin()) OpenCommand().execute(["example_multi_file_entry"]) true_out = capsys.readouterr().out.split("\n") expected_out = [ " 1: [note] " + self.TMP_FILE_A, " 2: [note] " + self.TMP_FILE_B, "Entry to open [Type 'help' for more info]: ", ] for line, truth in zip(true_out, expected_out): assert line == truth
def test_adam(monkeypatch: pytest.MonkeyPatch) -> None: N, D = 4, 5 w = np.linspace(-0.4, 0.6, num=N * D).reshape(N, D) dw = np.linspace(-0.6, 0.4, num=N * D).reshape(N, D) m = np.linspace(0.6, 0.9, num=N * D).reshape(N, D) v = np.linspace(0.7, 0.5, num=N * D).reshape(N, D) model = Linear(N, D) monkeypatch.setattr(Adam, "init_context", lambda self, w: (m, v, 5)) optimizer = Adam(model, lr=1e-2) next_w, (next_m, next_v, _) = optimizer.update(optimizer.context["w"], w, dw) expected_next_w = np.asarray( [ [-0.40094747, -0.34836187, -0.29577703, -0.24319299, -0.19060977], [-0.1380274, -0.08544591, -0.03286534, 0.01971428, 0.0722929], [0.1248705, 0.17744702, 0.23002243, 0.28259667, 0.33516969], [0.38774145, 0.44031188, 0.49288093, 0.54544852, 0.59801459], ] ) expected_v = np.asarray( [ [0.69966, 0.68908382, 0.67851319, 0.66794809, 0.65738853], [0.64683452, 0.63628604, 0.6257431, 0.61520571, 0.60467385], [0.59414753, 0.58362676, 0.57311152, 0.56260183, 0.55209767], [0.54159906, 0.53110598, 0.52061845, 0.51013645, 0.49966], ] ) expected_m = np.asarray( [ [0.48, 0.49947368, 0.51894737, 0.53842105, 0.55789474], [0.57736842, 0.59684211, 0.61631579, 0.63578947, 0.65526316], [0.67473684, 0.69421053, 0.71368421, 0.73315789, 0.75263158], [0.77210526, 0.79157895, 0.81105263, 0.83052632, 0.85], ] ) assert np.allclose(next_w, expected_next_w) assert np.allclose(next_m, expected_m) assert np.allclose(next_v, expected_v)
def _set_up_fake_getaddrinfo(monkeypatch: pytest.MonkeyPatch) -> None: # Work around https://github.com/urllib3/urllib3/pull/2034 # Nothing prevents localhost to point to two different IPs. For example, in the # Ubuntu set up by GitHub Actions, localhost points both to 127.0.0.1 and ::1. # # In case of failure, PySocks will try the same request on both IPs, but our # handle_socks[45]_negotiation functions don't handle retries, which leads either to # a deadlock or a timeout in case of a failure on the first address. # # However, some tests need to exercise failure. We don't want retries there, but # can't affect PySocks retries via its API. Instead, we monkeypatch PySocks so that # it only sees a single address, which effectively disables retries. def fake_getaddrinfo( addr: str, port: int, family: int, socket_type: int ) -> List[Tuple[socket.AddressFamily, socket.SocketKind, int, str, Union[ Tuple[str, int], Tuple[str, int, int, int]], ]]: gai_list = real_getaddrinfo(addr, port, family, socket_type) gai_list = [gai for gai in gai_list if gai[0] == socket.AF_INET] return gai_list[:1] monkeypatch.setattr(py_socks.socket, "getaddrinfo", fake_getaddrinfo)
def test_preflight( caplog: LogCaptureFixture, cd_tmp_path: Path, cp_config: CpConfigTypeDef, monkeypatch: MonkeyPatch, ) -> None: """Test ``runway preflight``.""" cp_config("min_required", cd_tmp_path) caplog.set_level(logging.DEBUG, logger="runway.cli.commands.preflight") mock_forward = MagicMock() monkeypatch.setattr("click.Context.forward", mock_forward) runner = CliRunner() result = runner.invoke(cli, ["preflight", "--deploy-environment", "test"]) assert result.exit_code == 0 assert "forwarding to test..." in caplog.messages mock_forward.assert_called_once_with(test, debug=0, deploy_environment="test", no_color=False, verbose=False)
def test_notify_quotes( monkeypatch: pytest.MonkeyPatch, mocker: MockerFixture, OS: str, cmd_length: int, title: str, text: str, ) -> None: subprocess = mocker.patch(MODULE + ".subprocess") for os in ("LINUX", "MACOS", "WSL"): if os != OS: monkeypatch.setattr(zulipterminal.helper, os, False) else: monkeypatch.setattr(zulipterminal.helper, os, True) notify(title, text) params = subprocess.run.call_args_list assert len(params) == 1 # One external run call assert len(params[0][0][0]) == cmd_length
def test_remote_sha_get_regex_fail(self, monkeypatch: MonkeyPatch): class MockSplitCopyShared2(MockSplitCopyShared): def req_sha_binaries(self, sha_hash): return "shasum", 1 class MockSSHShell2(MockSSHShell): def run(self, cmd, timeout): result = True stdout = "" return result, stdout def find_existing_sha_files(): return False, "" scget = SplitCopyGet() monkeypatch.setattr(scget, "find_existing_sha_files", find_existing_sha_files) scget.sshshell = MockSSHShell2() scget.scs = MockSplitCopyShared2() with raises(SystemExit): scget.remote_sha_get()
def test_Progress(monkeypatch: pytest.MonkeyPatch): # Monkeypatch tqdm so that we can extract tqdm instance attributes tqdm_instance: List[Optional[tqdm.tqdm]] = [None] tqdm_cls = tqdm.tqdm def mock_tqdm(*args, **kwargs): tqdm_instance[0] = tqdm_cls(*args, **kwargs) return tqdm_instance[0] monkeypatch.setattr(tqdm, "tqdm", mock_tqdm) # Assert that the progress bar works with stream with Pipeline() as pipeline: item = Unpack(range(10)) result = Progress("Description") stream = pipeline.transform_stream() result = [o[item] for o in stream] assert result == list(range(10)) assert tqdm_instance[0].total == 10
def test_safe_cache_access(monkeypatch: pytest.MonkeyPatch) -> None: """Regression test against #94. Args: monkeypatch: the built-in pytest fixture. """ monkeypatch.setattr("sys.stdin", MockStdin()) # create an empty temporary directory tmp_dir = tempfile.mkdtemp() # use a path which surely does not exist tmp_cache_file = Path(tmp_dir) / "cache/version" try: # try to read the version from a file whose parent directory does not exist print_changelog("0.2", str(tmp_cache_file)) # if the test regresses, this will fail with a `FileNotFoundError` finally: if tmp_cache_file.exists(): tmp_cache_file.unlink() if tmp_cache_file.parent.exists(): tmp_cache_file.parent.rmdir() Path(tmp_dir).rmdir()
def test_readme_no_exist(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, patch_argv: PatchArgvType) -> None: """Test that ``IndexError`` is not raised by version request. Instead, ``restructuredtext_lint`` should raise ``FileNotFoundError``. :param tmp_path: Fixture for creating and returning temporary directory. :param monkeypatch: Mock patch environment and attributes. :param patch_argv: Set args with ``sys.argv``. Clears pytest arguments for this test. """ patch_argv() monkeypatch.setattr("readmetester._core._Path.cwd", lambda: tmp_path) with pytest.raises(FileNotFoundError) as err: readmetester.main() assert (str( err.value ) == f"[Errno 2] No such file or directory: '{Path.cwd() /'README.rst'}'")
def test_js_dev_cdn(self, version: str, monkeypatch: pytest.MonkeyPatch, driver: WebDriver, test_file_path_and_url: Tuple[str, str], test_plot: figure) -> None: monkeypatch.setattr(buv, "__version__", "1.4.0rc1") monkeypatch.setattr(resources, "__version__", "1.4.0rc1") js, tag = bes.autoload_static(test_plot, CDN, "some/path") page = PAGE.render(js=js, tag=tag) path, url = test_file_path_and_url with open(path, "w") as f: f.write(page) driver.get(url) scripts = driver.find_elements(By.CSS_SELECTOR, 'head script') assert len(scripts) == 5 for script in scripts: assert script.get_attribute("crossorigin") == None assert script.get_attribute("integrity") == ""
def test_add_point(monkeypatch: MonkeyPatch) -> None: from DLA.plane import plane, base_plane monkeypatch.setattr(plane, 'WINDOW_SIZE', 512) monkeypatch.setattr(plane, 'SECOND_MIN_BOX_SIZE', 32) monkeypatch.setattr(plane, 'STARTING_POS', (14, 16)) monkeypatch.setattr(plane, 'NUM_OF_PARTICLES', 0) monkeypatch.setattr(base_plane, 'RADIUS', 1) p = plane.Plane.new() assert len(p) == 1 # type: ignore assert p[0] # type: ignore assert len(p[0]) == 1 # type: ignore assert p[0][0] # type: ignore assert len(p[0][0]) == 1 # type: ignore assert p[0][0][0] # type: ignore assert len(p[0][0][0]) == 1 # type: ignore assert p[0][0][0][0] # type: ignore assert len(p[0][0][0][0] # type: ignore ) == 2 assert p[0][0][0][0][0] # type: ignore assert p[0][0][0][0][2] # type: ignore
def test_auth_using_agent(self, monkeypatch: MonkeyPatch): class Agent: def __init__(self): pass def get_keys(self): keys = [AgentKey("foo", "bar")] return keys class AgentKey: def __init__(self, agent, blob): self.agent = agent self.blob = blob self.name = "foobar" def get_name(self): return self.name class Transport: def auth_publickey(username, pkey): return True monkeypatch.setattr("paramiko.Agent", Agent) monkeypatch.setattr("paramiko.AgentKey", AgentKey) paramikoshell = init_paramikoshell(username="******") monkeypatch.setattr(paramikoshell, "_transport", Transport) result = paramikoshell.auth_using_agent() assert result == True
async def test_climate_service_failed(hass: HomeAssistant, load_int: ConfigEntry, monkeypatch: pytest.MonkeyPatch) -> None: """Test the Sensibo climate service failed.""" monkeypatch.setattr(DATA_FROM_API.parsed["ABC999111"], "hvac_mode", "heat") monkeypatch.setattr(DATA_FROM_API.parsed["ABC999111"], "device_on", True) with patch( "homeassistant.components.sensibo.coordinator.SensiboClient.async_get_devices_data", return_value=DATA_FROM_API, ): async_fire_time_changed( hass, dt.utcnow() + timedelta(minutes=5), ) await hass.async_block_till_done() state1 = hass.states.get("climate.hallway") assert state1.state == "heat" with patch( "homeassistant.components.sensibo.util.SensiboClient.async_set_ac_state_property", return_value={ "result": { "status": "Error", "failureReason": "Did not work" } }, ): with pytest.raises(HomeAssistantError): await hass.services.async_call( CLIMATE_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: state1.entity_id}, blocking=True, ) await hass.async_block_till_done() state2 = hass.states.get("climate.hallway") assert state2.state == "heat"