def mock_values(mocker: MockFixture): mock_values = mocker.NonCallableMock() mocker.patch( PATH.format('get_spreadsheets_values'), return_value=mock_values, ) return mock_values
def window(model: Model, qtbot: QtBot, mocker: MockFixture): """the window.""" message_box = 'usc_lr_timer.app.QtWidgets.QMessageBox.{}' mocker.patch(message_box.format('question'), return_value=QtWidgets.QMessageBox.Yes) mocker.patch(message_box.format('information')) window = MainWindow(model) qtbot.add_widget(window) return window
def test_get_spreadsheets_values(mocker: MockFixture): mock_creds = mocker.create_autospec(Credentials, instance=True) mocker.patch(PATH.format('get_credentials'), return_value=mock_creds) mock_resource = mocker.NonCallableMock() mock_build = mocker.patch(PATH.format('build'), return_value=mock_resource) mock_values = mock_resource.spreadsheets().values() values = google_sheets.get_spreadsheets_values() assert values is mock_values mock_build.assert_called_once_with('sheets', 'v4', credentials=mock_creds)
def test_parse_RequiredArguments(mocker: MockFixture, argv: list): mocker.patch('sys.argv', argv) args = parse() assert len(vars(args)) == 7 assert args.api_endpoint == 'endpoint' assert args.owner == 'owner' assert args.repo == 'repo' assert args.token == 'token' assert args.mapping is None assert args.output is None assert args.write_apiresponse is False
def test_parse_OptionalArguments(mocker: MockFixture, argv: list): argv.append('--mapping=mapping') argv.append('--output=output') argv.append('--write-apiresponse') mocker.patch('sys.argv', argv) args = parse() assert len(vars(args)) == 7 assert args.api_endpoint == 'endpoint' assert args.owner == 'owner' assert args.repo == 'repo' assert args.token == 'token' assert args.mapping == 'mapping' assert args.output == 'output' assert args.write_apiresponse
def mock_ttg(mocker: MockFixture): mock_ttg = mocker.patch( PATH.format('talk_to_google.talk_to_google'), autospec=True, ) mock_ttg.return_value = Results.success, [['a', '1'], ['b', '2']] return mock_ttg
def test_file_isWritable(self, mocker: MockFixture) -> None: # mock mock_os_access = mocker.MagicMock(name="mock_os_access") # patch mocker.patch.object(ultron8.paths.os, "access", mock_os_access) # mock_is_readable_dir = mocker.patch.object( # ultron8.paths, "is_readable_dir", return_value=False, autospec=True # ) mock_is_readable_dir = mocker.patch.object( ultron8.paths, "is_readable_dir", return_value={"result": False}, autospec=True, ) path = "file:///tmp/fake_file" # patch return values mock_os_access.return_value = True # run test result = paths.isWritable(path) # tests mock_is_readable_dir.assert_called_once_with("file:///tmp/fake_file") mock_os_access.assert_called_once_with("file:///tmp", os.W_OK) assert result == True
def test_mkdir_if_does_not_exist_true(self, mocker: MockFixture) -> None: # mock mock_mkdir_p = mocker.MagicMock(name="mock_mkdir_p") mock_dir_exists = mocker.MagicMock(name="mock_dir_exists", return_value=True) # patch mocker.patch.object(ultron8.paths, "mkdir_p", mock_mkdir_p) mocker.patch.object(ultron8.paths, "dir_exists", mock_dir_exists) path = "/opt/ultron8" # run test result = paths.mkdir_if_does_not_exist(path) # assert assert mock_mkdir_p.call_count == 0 assert mock_dir_exists.call_count == 1 assert result == False
def test_get_credentials(mocker: MockFixture): mock_from_service_account_file = mocker.patch( PATH.format('service_account.Credentials.from_service_account_file')) google_sheets.get_credentials() mock_from_service_account_file.assert_called_once_with( str(google_sheets.SERVICE_ACCOUNT_FILE), scopes=['https://www.googleapis.com/auth/spreadsheets'], )
def test_read_sheet(mocker: MockFixture, mock_values: Mock): mock_request = mocker.Mock() mock_values.get.return_value = mock_request mock_request.execute.return_value = {'values': [1, 2, 3]} assert google_sheets.read_sheet('abc123', 'A1:A3') == [1, 2, 3] mock_values.get.assert_called_with( spreadsheetId='abc123', range='A1:A3', )
def test_talk_to_google_cancel(qtbot: QtBot, mocker: MockFixture): def fn(a, b): qtbot.wait(600) mocker.patch(PATH.format('ALLOWED_METHODS'), [fn]) progress = QtWidgets.QProgressDialog('test', 'test', 0, 0) def exec_(*args, **kwargs): progress.cancel() mock_exec = mocker.patch.object(progress, 'exec_', side_effect=exec_) mock_Progress = mocker.patch(PATH.format('QtWidgets.QProgressDialog'), return_value=progress) result, data = talk_to_google.talk_to_google(fn, 1, b=2) assert result == talk_to_google.Results.canceled assert data is None mock_exec.assert_called_once_with() mock_Progress.assert_called_once_with('Talking to Google...', 'Stop', 0, 0)
def test_get_categories(mocker: MockFixture, mock_values: Mock): mock_request = mocker.Mock() mock_values.get.return_value = mock_request mock_request.execute.return_value = {'values': [['a'], ['b'], ['c']]} assert google_sheets.get_categories('abc123') == ['a', 'b', 'c'] mock_values.get.assert_called_once_with( spreadsheetId='abc123', range='Categories!A2:A', )
def test_getIssuesPerPage_RequestParameters(mocker: MockFixture, emptyRequests: MagicMock): mocker.patch('requests.get', emptyRequests) GitbucketApi('endpoint', 'owner', 'repo', 'token').getIssuesPerPage(1) issues_endpoint, optional_args = emptyRequests.call_args # Check Request Header assert 'headers' in optional_args header = optional_args['headers'] assert header['Authorization'] == 'token token' assert header['content-type'] == 'application/json' assert 'params' in optional_args payload = optional_args['params'] assert payload['page'] == 1 assert payload['state'] == 'open' assert issues_endpoint[0] == 'endpoint/api/v3/repos/owner/repo/issues' assert header['Authorization'] == 'token token' assert header['content-type'] == 'application/json'
def test_get_names(mocker: MockFixture, mock_values: Mock): mock_request = mocker.Mock() mock_values.get.return_value = mock_request mock_request.execute.return_value = { 'values': [['a', '1'], ['b', '2'], ['c', '3']] } assert google_sheets.get_names('abc123') == {'a': '1', 'b': '2', 'c': '3'} mock_values.get.assert_called_once_with( spreadsheetId='abc123', range='Names!A2:B', )
def test_add_row(mocker: MockFixture, mock_values: Mock): mock_request = mocker.Mock() mock_values.append.return_value = mock_request mock_request.execute.return_value = {'values': [1, 2, 3]} result = google_sheets.add_row('abc123', 'A1:A3', [1, 2, 3]) mock_values.append.assert_called_with( spreadsheetId='abc123', range='A1:A3', valueInputOption='RAW', body={'values': [[1, 2, 3]]}, ) assert result == {'values': [1, 2, 3]}
def test_talk_to_google_error(qtbot: QtBot, mocker: MockFixture): def fn(a, b): raise RuntimeError('Test Exception') mocker.patch(PATH.format('ALLOWED_METHODS'), [fn]) progress = QtWidgets.QProgressDialog('test', 'test', 0, 0) def exec_(*args, **kwargs): while progress.result() != progress.Accepted: qtbot.wait(200) mock_exec = mocker.patch.object(progress, 'exec_', side_effect=exec_) mock_Progress = mocker.patch(PATH.format('QtWidgets.QProgressDialog'), return_value=progress) mock_critical = mocker.patch(PATH.format('QtWidgets.QMessageBox.critical')) result, data = talk_to_google.talk_to_google(fn, 1, b=2) assert result == talk_to_google.Results.error assert data is None mock_exec.assert_called_once_with() mock_Progress.assert_called_once_with('Talking to Google...', 'Stop', 0, 0) mock_critical.assert_called_once_with(None, 'Error', 'Test Exception')
def test_mkdir_p(self, mocker: MockFixture) -> None: # mock # mock_logger_info = mocker.MagicMock(name="mock_logger_info") mock_dir_exists = mocker.MagicMock(name="mock_dir_exists") mock_path = mocker.MagicMock(name="mock_path") # patch mocker.patch.object(ultron8.paths, "dir_exists", mock_dir_exists) mocker.patch.object(ultron8.paths, "Path", mock_path) path = "/opt/ultron8" mock_dir_exists.return_value = True # run test paths.mkdir_p(path) # assert mock_path.assert_called_once_with(path) mock_path().mkdir.assert_any_call(parents=True, exist_ok=True)
def mock_progress(mocker: MockFixture, qtbot: QtBot): progress = QtWidgets.QProgressDialog('test', 'test', 0, 0) def exec_(*args, **kwargs): while progress.result() != progress.Accepted: qtbot.wait(200) mocker.patch.object(progress, 'exec_', side_effect=exec_) mock_Progress = mocker.patch( 'usc_lr_timer.model.talk_to_google.QtWidgets.QProgressDialog', return_value=progress, ) return mock_Progress
def mock_talk_to_google(mocker: MockFixture, mock_progress: Mock): mock_talk_to_google = mocker.patch( 'usc_lr_timer.model.talk_to_google.talk_to_google', autospec=True, ) def talk_to_google(method, *args, **kwargs): if method is google_sheets.get_categories: return Results.success, ['testing', 'other'] elif method is google_sheets.add_time: return Results.success, None else: raise NotImplementedError mock_talk_to_google.side_effect = talk_to_google return mock_talk_to_google
def repository(mocker: MockFixture, env: MockEnv) -> InstalledRepository: mocker.patch( "poetry.utils._compat.metadata.Distribution.discover", return_value=INSTALLED_RESULTS, ) mocker.patch( "poetry.core.vcs.git.Git.rev_parse", return_value="bb058f6b78b2d28ef5d9a5e759cfa179a1a713d6", ) mocker.patch( "poetry.core.vcs.git.Git.remote_urls", side_effect=[ {"remote.origin.url": "https://github.com/sdispater/pendulum.git"}, {"remote.origin.url": "[email protected]:sdispater/pendulum.git"}, ], ) mocker.patch("poetry.repositories.installed_repository._VENDORS", str(VENDOR_DIR)) return InstalledRepository.load(env)
def fake_environ( mocker: MockFixture, monkeypatch: MonkeyPatch ) -> Iterator[Dict[str, Dict[str, Union[str, int]]]]: os.environ environ = dict() environ["DEBUG"] = "True" environ["TESTING"] = "True" environ["SECRET_KEY"] = "43n080musdfjt54t-09sdgr" environ["REDIS_URL"] = "redis://localhost" environ["REDIS_ENDPOINT"] = "127.0.0.1" environ["REDIS_PORT"] = "6379" environ["REDIS_DB"] = "0" environ["DATABASE_URL"] = "sqlite:///dev.db" environ["TEST_DATABASE_URL"] = "sqlite:///test.db" environ["DEFAULT_MODULE_NAME"] = "ultron8.web" environ["VARIABLE_NAME"] = "app" environ["MODULE_NAME"] = "ultron8.web" environ["APP_MODULE"] = "ultron8.web:app" # environ["DEFAULT_GUNICORN_CONF"] = /Users/malcolm/dev/bossjones/ultron8/gunicorn_conf.py # environ["PRE_START_PATH"] = /Users/malcolm/dev/bossjones/ultron8/migrations/gunicorn-prestart.sh environ["DOMAIN"] = "localhost" environ["HOST"] = "localhost" environ["PORT"] = "11267" environ["LOG_LEVEL"] = logging.DEBUG environ["BETTER_EXCEPTIONS"] = "1" environ["SERVER_NAME"] = "localhost:11267" environ["SERVER_HOST"] = "http://*****:*****@ultron8.com" environ["FLOWER_AUTH"] = "admin:password" environ["USERS_OPEN_REGISTRATION"] = "False" environ["BACKEND_CORS_ORIGINS"] = "*" mocks = {"environ": mocker.patch("os.environ", environ)} yield mocks
def test_fname_exists_true(self, mocker: MockFixture) -> None: # mock mock_path = mocker.MagicMock(name="mock_path") # patch mocker.patch.object(ultron8.paths, "Path", mock_path) path = "/opt/ultron8/generator.dot" mock_path_instance = mock_path() mock_path_instance.exists.return_value = True # run test result = paths.fname_exists(path) assert mock_path_instance.exists.call_count == 1 mock_path.assert_any_call(path) assert result == True
def test_add_time(mocker: MockFixture, mock_values: Mock): mock_request = mocker.Mock() mock_values.append.return_value = mock_request mock_request.execute.return_value = {'values': [1, 2, 3]} result = google_sheets.add_time( 'abc123', 'Vincent', 'Fall', timedelta(days=1), 'testing', ) mock_values.append.assert_called_with( spreadsheetId='abc123', range='Submissions', valueInputOption='RAW', body={ 'values': [['Vincent', 'Fall', 1.0, '10/24/2020 12:13:14', 'testing']] }, ) assert result == {'values': [1, 2, 3]}
def test_submit(model: Model, mocker: MockFixture): mock_ttg = mocker.patch('usc_lr_timer.model.talk_to_google.talk_to_google') mock_ttg.return_value = Results.success, None model._name = None assert model.submit(True) == SubmitResult(None, 'Name not chosen') model._name = 'Vincent' assert model.submit(True) == SubmitResult(None, 'Category not chosen') model._categories = ['', 'testing'] model.set_category_index(1) model.set_manual_minutes(61) model.set_manual_seconds(61) result = SubmitResult(None, 'Minutes must be between 0 and 60') assert model.submit(True) == result model.set_manual_minutes(0) result = SubmitResult(None, 'Seconds must be between 0 and 60') assert model.submit(True) == result model.set_manual_seconds(0) assert model.submit(True) == SubmitResult(None, 'No time recorded') model.set_manual_seconds(42) assert model.submit(True) == SubmitResult(Results.success, None) mock_ttg.assert_called_with( google_sheets.add_time, spreadsheet_id='abc123', name='Vincent', semester='Fall', duration=timedelta(seconds=42), category='testing', ) assert model.submit(False) == SubmitResult(None, 'No time recorded') model.increment_duration(24) assert model.submit(False) == SubmitResult(Results.success, None) mock_ttg.assert_called_with( google_sheets.add_time, spreadsheet_id='abc123', name='Vincent', semester='Fall', duration=timedelta(seconds=24), category='testing', )
def test_dir_exists_false(self, mocker: MockFixture) -> None: # mock # mock_logger_error = mocker.MagicMock(name="mock_logger_error") mock_path = mocker.MagicMock(name="mock_path") # patch # mocker.patch.object( # scarlett_os.subprocess.logging.Logger, "error", mock_logger_error # ) mocker.patch.object(ultron8.paths, "Path", mock_path) path = "/opt/ultron8" mock_path_instance = mock_path() mock_path_instance.is_dir.return_value = False # run test paths.dir_exists(path) # assert # assert mock_logger_error.call_count == 1 assert mock_path_instance.is_dir.call_count == 2
def model_mock_ttg(mocker: MockFixture): mock_ttg = mocker.patch('usc_lr_timer.model.talk_to_google.talk_to_google') mock_ttg.return_value = Results.success, ['testing'] return mock_ttg
def mock_journals(mocker: MockFixture, tmpdir: LocalPath): journals: LocalPath = tmpdir.join('journals.json') mocker.patch(PATH.format('JOURNALS'), str(journals)) with journals.open('w') as stream: json.dump({'w': 'x', 'y': 'z'}, stream)
def mock_journals(mocker: MockFixture, tmpdir: LocalPath): journals: LocalPath = tmpdir.join('journals.json') mocker.patch('usc_lr_timer.login.JOURNALS', str(journals)) with journals.open('w') as stream: json.dump({'Law Review': 'abc123', 'RLSJ': 'xyz789'}, stream)
def mock_critical(mocker: MockFixture): return mocker.patch('usc_lr_timer.login.QtWidgets.QMessageBox.critical')
def train_func_mocker(mocker: MockFixture): mocker.patch('langmodels.training.cli.train') return mocker