def test_find_tty_acm(self, mocker, path, avail, found): tty_nodes = ['ttyACM0', 'ttyACM1', 'ttyACM2', 'ttyACM10'] mocker.patch('nfc.clf.transport.open').return_value = True mocker.patch('nfc.clf.transport.termios.tcgetattr').side_effect = [ ([] if is_avail else termios.error) for is_avail in avail] mocker.patch('nfc.clf.transport.os.listdir').return_value = tty_nodes assert nfc.clf.transport.TTY.find(path) == found
def test_write_ndef(mocker, tag): # noqa: F811 read_ndef_data = mocker.patch("nfc.tag.Tag.NDEF._read_ndef_data") read_ndef_data.return_value = HEX('') assert isinstance(tag.ndef, nfc.tag.Tag.NDEF) with pytest.raises(AttributeError) as excinfo: tag.ndef.octets = HEX('D00000') assert str(excinfo.value) == "tag ndef area is not writeable" tag.ndef._writeable = True with pytest.raises(ValueError) as excinfo: tag.ndef.octets = HEX('D00000') assert str(excinfo.value) == "data length exceeds tag capacity" tag.ndef._capacity = 3 with pytest.raises(NotImplementedError) as excinfo: tag.ndef.octets = HEX('D00000') assert str(excinfo.value) == \ "_write_ndef_data is not implemented for this tag type" mocker.patch("nfc.tag.Tag.NDEF._write_ndef_data") tag.ndef.octets = HEX('D00000') assert tag.ndef.octets == HEX('D00000') tag.ndef.records = [ndef.Record('unknown')] assert tag.ndef.octets == HEX('D50000') tag.ndef.message = nfc.ndef.Message(nfc.ndef.Record()) assert tag.ndef.octets == HEX('D00000')
def test_init_linux_stty_set_460800(self, mocker, transport): # noqa: F811 mocker.patch('nfc.clf.pn532.Device.__init__').return_value = None mocker.patch('nfc.clf.pn532.open').side_effect = IOError stty = mocker.patch('os.system') stty.side_effect = [-1, 0, None] sys.platform = "linux" transport.write.return_value = None transport.read.side_effect = [ ACK(), RSP('03 32010607'), # GetFirmwareVersion ACK(), RSP('15'), # SAMConfiguration ACK(), RSP('11'), # SetSerialBaudrate ] device = nfc.clf.pn532.init(transport) assert isinstance(device, nfc.clf.pn532.Device) assert stty.mock_calls == [ call('stty -F /dev/ttyS0 921600 2> /dev/null'), call('stty -F /dev/ttyS0 460800 2> /dev/null'), call('stty -F /dev/ttyS0 115200 2> /dev/null'), ] assert transport.write.mock_calls == [call(_) for _ in [ HEX(10 * '00') + CMD('02'), # GetFirmwareVersion HEX(10 * '00') + CMD('14 010000'), # SAMConfiguration HEX(10 * '00') + CMD('10 06'), ACK(), # SetSerialBaudrate ]]
def test_init_raspi_tty_ama(self, mocker, transport): # noqa: F811 mocker.patch('nfc.clf.pn532.Device.__init__').return_value = None device_tree_model = mocker.mock_open(read_data=b"Raspberry Pi") mocker.patch('nfc.clf.pn532.open', device_tree_model) type(transport.tty).port = PropertyMock(return_value='/dev/ttyAMA0') stty = mocker.patch('os.system') stty.return_value = -1 sys.platform = "linux" transport.write.return_value = None transport.read.side_effect = [ ACK(), RSP('03 32010607'), # GetFirmwareVersion ACK(), RSP('15'), # SAMConfiguration ] device = nfc.clf.pn532.init(transport) assert stty.mock_calls == [ call('stty -F /dev/ttyAMA0 921600 2> /dev/null'), call('stty -F /dev/ttyAMA0 460800 2> /dev/null'), call('stty -F /dev/ttyAMA0 230400 2> /dev/null'), call('stty -F /dev/ttyAMA0 115200 2> /dev/null'), ] assert isinstance(device, nfc.clf.pn532.Device) assert transport.write.mock_calls == [call(_) for _ in [ HEX(10 * '00') + CMD('02'), # GetFirmwareVersion HEX(10 * '00') + CMD('14 010000'), # SAMConfiguration ]] assert transport.read.mock_calls == [ call(timeout=100), call(timeout=100), call(timeout=100), call(timeout=100), ]
def test_find_tty_mac(self, mocker, path, avail, found): tty_nodes = 'cu.usbserial-0', 'cu.usbserial-1', 'cu.usbserial-FTSI7X', mocker.patch('nfc.clf.transport.open').return_value = True mocker.patch('nfc.clf.transport.termios.tcgetattr').side_effect = [ ([] if is_avail else termios.error) for is_avail in avail] mocker.patch('nfc.clf.transport.os.listdir').return_value = tty_nodes assert nfc.clf.transport.TTY.find(path) == found
def test_init(mocker): # noqa: F811 nameinfo = ('127.0.0.1', '54321') mocker.patch('nfc.clf.udp.select.select').return_value = ([1], [], []) mocker.patch('nfc.clf.udp.socket.getnameinfo').return_value = nameinfo mocker.patch('nfc.clf.udp.socket.socket') device = nfc.clf.udp.init('localhost', 54321) assert isinstance(device, nfc.clf.udp.Device)
def test_init_linux_setbaud_rsp_err(self, mocker, transport): # noqa: F811 mocker.patch('nfc.clf.pn532.Device.__init__').return_value = None mocker.patch('nfc.clf.pn532.open').side_effect = IOError stty = mocker.patch('os.system') stty.side_effect = [-1, 0, None] sys.platform = "linux" transport.write.return_value = None transport.read.side_effect = [ ACK(), RSP('03 32010607'), # GetFirmwareVersion ACK(), RSP('15'), # SAMConfiguration ACK(), ERR(), # SetSerialBaudrate ] with pytest.raises(IOError) as excinfo: nfc.clf.pn532.init(transport) assert excinfo.value.errno == errno.ENODEV assert stty.mock_calls == [ call('stty -F /dev/ttyS0 921600 2> /dev/null'), call('stty -F /dev/ttyS0 460800 2> /dev/null'), call('stty -F /dev/ttyS0 115200 2> /dev/null'), ] assert transport.write.mock_calls == [call(_) for _ in [ HEX(10 * '00') + CMD('02'), # GetFirmwareVersion HEX(10 * '00') + CMD('14 010000'), # SAMConfiguration HEX(10 * '00') + CMD('10 06'), # SetSerialBaudrate ]]
def test_scraper_run(mocker, tariffs_page, landline, pay_monthly): mocker.patch("o2scraper.page.InternationalTariffsPage") run("Canada", tariff=pay_monthly, method=landline, tariff_page=tariffs_page) tariffs_page.go_to().assert_called_once() tariffs_page.search_for_country.assert_called_once_with("Canada") tariffs_page.select_tariff_type.assert_called_once_with(pay_monthly) tariffs_page.get_rate.assert_called_once_with(pay_monthly, landline)
def test_access_key_not_found_exception(mocker, mock_request): exponea = Exponea("test") response = { "error": "access key not found", "success": False } mocker.patch("requests.request", mock_request(response)) with pytest.raises(APIException) as exception: exponea.analyses.get_report("test") assert "access key not found" in str(exception.value)
def test_errors_global_exception(mocker, mock_request): exponea = Exponea("test") response = { "errors": {"_global": ["Customer does not exist"]}, "success": False } mocker.patch("requests.request", mock_request(response)) with pytest.raises(APIException) as exception: exponea.customer.get_customer({"registered": "test"}) assert "Customer does not exist" in str(exception.value)
def test_not_authorized_exception(mocker, mock_request): exponea = Exponea("test") response = { "errors": ["not authorized to update specified customer properties"], "success": False } mocker.patch("requests.request", mock_request(response)) with pytest.raises(APIException) as exception: exponea.analyses.get_report("test") assert "not authorized to update specified customer properties" in str(exception.value)
def test_interaction_with_bad_slack_token(mocker, test_app): data = SUGGESTION_CLICKED_EVENT data['token'] = 'bad token' json_data = json.dumps(data) mocker.patch(ROUTING_HANDLER_PATH) response = test_app.post('/user_interaction', data=dict(payload=json_data), follow_redirects=True) assert not ocbot.web.routes_slack.RoutingHandler.called assert response.status_code == 403
def test_no_state(self, client, session, mocker): """Payload missing state throws jsonschema ValidationError.""" mocker.patch('wptdash.blueprints.routes.validate_hmac_signature', return_value=True) payload = deepcopy(github_webhook_payload) payload['pull_request'].pop('state') with pytest.raises(ValidationError): client.post('/api/pull', data=json.dumps(payload), content_type='application/json')
def test_find_tty_err(self, mocker): # noqa: F811 mod = 'nfc.clf.transport' mocker.patch(mod + '.open').return_value = True mocker.patch(mod + '.termios.tcgetattr').side_effect = IOError mocker.patch(mod + '.os.listdir').return_value = ['ttyS0', 'ttyS1'] assert nfc.clf.transport.TTY.find('tty:S') == ([], '', True) with pytest.raises(IOError): assert nfc.clf.transport.TTY.find('tty:S0') with pytest.raises(IOError): assert nfc.clf.transport.TTY.find('tty:S1')
def device(mocker): nameinfo = ('127.0.0.1', '54321') mocker.patch('nfc.clf.udp.select.select').return_value = ([1], [], []) mocker.patch('nfc.clf.udp.socket.getnameinfo').return_value = nameinfo mocker.patch('nfc.clf.udp.socket.socket') device = nfc.clf.udp.Device('localhost', 54321) assert device.addr == ('127.0.0.1', 54321) device._device_name = "IP-Stack" device._chipset_name = "UDP" return device
def test_load_configs(mocker): mocked_os = mocker.patch('os.path') mocked_os.exist.return_value = True mocked_list_images = mocker.patch('imutils.paths.list_images') mocked_list_images.return_value = [] mocked_caffe_net = mocker.patch('cv2.dnn.readNetFromCaffe') mocked_torch_net = mocker.patch('cv2.dnn.readNetFromTorch') ee.load_configs() mocked_caffe_net.assert_called_once() mocked_torch_net.assert_called_once()
def test_create_graphic_fails(mocker, graphic_info, graphic_settings, default_format, expected_error): # Mock the `save` method mocker.patch("PIL.Image.Image.save") with pytest.raises(expected_error): # Create a graphic src.create_graphic( graphic_info, graphic_settings, default_settings_format=default_format )
def test_splice_valid_clips_avi_success(mocker): result_file_name = './result.avi' clips_dir = 'tests/resources/' mocker.patch('clipsplice.ClipSplicer._download_clip') splicer = ClipSplicer(example_clip_list) splicer.splice(result_file_name, clips_dir=clips_dir) result_file = Path(f'{result_file_name}') assert result_file.is_file() result_file.unlink()
def test_invalid_data(mocker): request.body = dict({'name': 'user1', 'password': '******'}) load_result.errors['password'] = '******' mocker.patch('helpers.schemas.UserSchema.load', return_value=load_result) with pytest.raises(BadRequestError): validate_request_body(request, resource='user', action='create', resource_id=1) UserSchema.load.assert_called_once_with(request.body)
def it_calls_the_api(mocker): # noqa: F811 mocker.patch('ldap_tools.user.API.show', return_value=None) mocker.patch( 'ldap_tools.client.Client.prepare_connection', return_value=None) runner.invoke(ldap_tools.user.CLI.user, ['show', '--username', username]) ldap_tools.user.API.show.assert_called_once_with(username)
def it_raises_exception_on_bad_type(mocker): # noqa: F811 mocker.patch('ldap_tools.group.API.create', return_value=None) mocker.patch('ldap_tools.client.Client.prepare_connection', return_value=None) runner.invoke( GroupCli.group, ['create', '--group', group_name, '--type', group_type]) assert pytest.raises(click.BadOptionUsage)
def it_calls_the_api(mocker): # noqa: F811 mocker.patch('ldap_tools.group.API.index', return_value=None) mocker.patch('ldap_tools.client.Client.prepare_connection', return_value=None) group_api = GroupApi(client) group_api.index = MagicMock() runner.invoke(GroupCli.group, ['index']) ldap_tools.group.API.index.assert_called_once_with()
def mocked_submission_participant_app(request, mocker): global dashboardTestMockObjects # Create the flask app app = conftest.create_basic_app() # Create some mock objects and chain the mock calls def mock_all(): return [ mocker.MagicMock(publication_recid=1, invitation_cookie='c00kie1', role='TestRole1'), mocker.MagicMock(publication_recid=2, invitation_cookie='c00kie2', role='TestRole2') ] mockFilter = mocker.Mock(all=mock_all) mockQuery = mocker.Mock(filter=lambda a, b, c, d: mockFilter) mockSubmissionParticipant = mocker.Mock(query=mockQuery) # Patch some methods called from hepdata.modules.dashboard.api so they return mock values dashboardTestMockObjects['submission'] = \ mocker.patch('hepdata.modules.dashboard.api.SubmissionParticipant', mockSubmissionParticipant) mocker.patch('hepdata.modules.dashboard.api.get_record_by_id', lambda x: {'title': 'Test Title 1' if x <= 1 else 'Test Title 2'}) mocker.patch('hepdata.modules.dashboard.api.get_latest_hepsubmission', mocker.Mock(coordinator=101)) mocker.patch('hepdata.modules.dashboard.api.get_user_from_id', mocker.Mock(return_value=dashboardTestMockObjects['user'])) mocker.patch('hepdata.modules.dashboard.api.decode_string', lambda x: "decoded " + str(x)) # Do the rest of the app setup app_generator = conftest.setup_app(app) for app in app_generator: yield app
def test_get_indicators_returns_indicators_successfuly(mocker): data = {'col1': [1, 2, 4, 4], 'col2': [1, 2, 4, 4]} mockDataframe = pd.DataFrame(data) mocker.patch('pandas.read_csv', return_value=mockDataframe) response = indicators_service.get_indicators() assert len(response) == 3
def test_incorrect_ip_addr(self, mocker): mocker.patch('llmnr_sphinx.parse_config_interfaces', return_value=self.config_values['interface']) config_vals_local = self.config_values.copy() config_contents_local = self.config_contents.copy() config_vals_local['dc2'] = '192.168.1.1,192.168.1.1' with pytest.raises(ValueError): llmnr_sphinx.parse_parameters( '\n'.join(config_contents_local).format(**config_vals_local)) pass pass
def test_hyp_hostname_value(self, mocker, x): mocker.patch('llmnr_sphinx.parse_config_interfaces', return_value=self.config_values['interface']) config_vals_local = self.config_values.copy() config_contents_local = self.config_contents.copy() config_vals_local['dc2'] = x with pytest.raises(ValueError): llmnr_sphinx.parse_parameters( '\n'.join(config_contents_local).format(**config_vals_local)) pass pass
def test_no_permission_to_retrieve_attribute(mocker, mock_request): exponea = Exponea("test") response = { 'results': [{'value': 'Lukas', 'success': True}, {'error': 'No permission', 'success': False}, {'value': 'not bought', 'success': True}], 'success': True } mocker.patch("requests.request", mock_request(response)) attributes = exponea.customer.get_customer_attributes({"registered": "test"}, ids=["test"], properties=["name"], expressions=["test"]) assert attributes["ids"]["test"] == None assert attributes["properties"]["name"] == "Lukas" assert attributes["expressions"]["test"] == "not bought"
def device(mocker): nameinfo = ('127.0.0.1', '54321') mocker.patch('nfc.clf.udp.select.select').return_value = ([1], [], []) mocker.patch('nfc.clf.udp.socket.getnameinfo').return_value = nameinfo mocker.patch('nfc.clf.udp.socket.socket') device = nfc.clf.udp.Device('localhost', 54321) assert device.addr == ('127.0.0.1', 54321) device._device_name = "IP-Stack" device._chipset_name = "UDP" yield device device.close()
def it_calls_the_api(mocker): # noqa: F811 mocker.patch('ldap_tools.group.API.delete', return_value=None) mocker.patch('ldap_tools.client.Client.prepare_connection', return_value=None) # We have to force here, otherwise, we get stuck # on an interactive prompt runner.invoke(GroupCli.group, ['delete', '--group', group_name, '--force']) ldap_tools.group.API.delete.assert_called_once_with(group_name)
def it_calls_the_api(mocker): # noqa: F811 mocker.patch('ldap_tools.group.API.create', return_value=None) mocker.patch('ldap_tools.client.Client.prepare_connection', return_value=None) runner.invoke( GroupCli.group, ['create', '--group', group_name, '--type', group_type]) ldap_tools.group.API.create.assert_called_once_with( group_name, group_type)
def test_load_configs(mocker): mocked_os = mocker.patch('os.path') mocked_os.exist.return_value = True mocked_pickle = mocker.patch('pickle.loads') mocked_pickle.return_value = {'names': ['abc']} mocked_open = mocker.patch('builtins.open') mocked_open.return_value = mocker.patch('builtins.open.read') mocked_le = mocker.patch('sklearn.preprocessing.LabelEncoder') mocked_le.fit_transform.return_value = [] train_face_recognizer.load_configs() mocked_open.assert_called_once()
def test_missing_section(self, mocker): mocker.patch('llmnr_sphinx.parse_config_interfaces', return_value=self.config_values['interface']) config_vals_local = self.config_values.copy() config_contents_local = self.config_contents.copy() del (config_contents_local[-2:]) with pytest.raises(ValueError): llmnr_sphinx.parse_parameters( '\n'.join(config_contents_local).format(**config_vals_local)) pass pass
def test_empty_slack_value_token(mocker, test_app): data = NEW_MEMBER data['token'] = None json_data = json.dumps(data) mocker.patch('ocbot.web.routes.RoutingHandler') response = test_app.post('/event_endpoint', data=json_data, content_type='application/json', follow_redirects=True) assert not ocbot.web.routes.RoutingHandler.called assert response.status_code == 403
def test_multiple_int_types(self, mocker): mocker.patch('llmnr_sphinx.parse_config_interfaces', return_value=self.config_values['interface']) config_vals_local = self.config_values.copy() config_contents_local = self.config_contents.copy() config_contents_local.insert(1, "send_interface= {send_interface}") with pytest.raises(ValueError): llmnr_sphinx.parse_parameters( '\n'.join(config_contents_local).format(**config_vals_local)) pass pass
def test_send_request(self, mock_fund_rich_notifier, mocker): with pytest.raises(AssertionError): mock_obj = Fund_Rich_Notifier(None, "password") mock_obj.send_request() mock_obj2 = Fund_Rich_Notifier("A123456789", None) mock_obj2.send_request() with pytest.raises(AssertionError, match="登入失敗!帳號密碼可能輸入錯誤!請重新確認!"): mocker.patch("requests.Session.post", return_value=requests.Response()) mock_fund_rich_notifier.send_request()
def it_adds_a_key(mocker): # noqa: F811 mocker.patch('ldap_tools.key.API.add', return_value=None) mocker.patch('ldap_tools.client.Client.prepare_connection', return_value=None) runner.invoke( KeyCli.key, ['add', '--username', username, '--filename', filename]) ldap_tools.key.API.add.assert_called_once_with( username, mock.ANY, filename)
def test_redis_call_set(mocker): class Redis: def get(self, key="teste"): if key == "julio": return "ops" if key == "patrick": return "dev" mocker.patch("main.StrictRedis", return_value=Redis()) assert main.get_value("julio") == "ops" assert main.get_value("patrick") == "dev"
def test_event_with_bad_slack_token(mocker, test_app): data = NEW_MEMBER data['token'] = 'bad token' json_data = json.dumps(data) mocker.patch(ROUTING_HANDLER_PATH) response = test_app.post('/event_endpoint', data=json_data, content_type='application/json', follow_redirects=True) assert not ocbot.web.routes_slack.RoutingHandler.called assert response.status_code == 403
def test_find_tty_any(self, mocker, path, avail, found): tty_nodes = list(sorted([ 'cu.usbserial-0', 'cu.usbserial-1', 'cu.usbserial-FTSI7O', 'ttyACM0', 'ttyACM1', 'ttyACM10', 'ttyACM2', 'ttyAMA0', 'ttyAMA1', 'ttyAMA10', 'ttyAMA2', 'ttyUSB0', 'ttyUSB1', 'ttyUSB10', 'ttyUSB2', 'ttyS0', 'ttyS1', 'ttyS10', 'ttyS2'], key=lambda d: (len(d), d))) dev_nodes = (['console', 'stderr', 'stdin', 'stdout', 'urandom'] + tty_nodes + ['tty', 'tty0', 'tty1', 'tty10', 'tty2']) mocker.patch('nfc.clf.transport.open').return_value = True mocker.patch('nfc.clf.transport.termios.tcgetattr').side_effect = [ (termios.error, [])[dev in avail] for dev in tty_nodes] mocker.patch('nfc.clf.transport.os.listdir').return_value = dev_nodes assert nfc.clf.transport.TTY.find(path) == found
def test_read_ndef(mocker, tag): # noqa: F811 with pytest.raises(NotImplementedError) as excinfo: tag.ndef assert str(excinfo.value) == \ "_read_ndef_data is not implemented for this tag type" read_ndef_data = mocker.patch("nfc.tag.Tag.NDEF._read_ndef_data") read_ndef_data.return_value = None assert tag.ndef is None read_ndef_data.return_value = HEX('') assert isinstance(tag.ndef, nfc.tag.Tag.NDEF) assert tag.ndef.octets == HEX('') assert tag.ndef.records == [] assert tag.ndef.message == nfc.ndef.Message(nfc.ndef.Record()) read_ndef_data.return_value = HEX('D00000') assert tag.ndef.has_changed is True assert isinstance(tag.ndef, nfc.tag.Tag.NDEF) assert tag.ndef.octets == HEX('D00000') assert tag.ndef.records == [ndef.Record()] assert tag.ndef.message == nfc.ndef.Message(nfc.ndef.Record()) read_ndef_data.return_value = HEX('D50000') assert tag.ndef.has_changed is True assert isinstance(tag.ndef, nfc.tag.Tag.NDEF) assert tag.ndef.octets == HEX('D50000') assert tag.ndef.records == [ndef.Record('unknown')] assert tag.ndef.message == nfc.ndef.Message(nfc.ndef.Record('unknown')) read_ndef_data.return_value = None assert tag.ndef.has_changed is True assert tag.ndef is None
def test_init_linux_stty_set_none(self, mocker, transport): # noqa: F811 mocker.patch('nfc.clf.pn532.Device.__init__').return_value = None mocker.patch('nfc.clf.pn532.open').side_effect = IOError mocker.patch('os.system').return_value = -1 sys.platform = "linux" transport.write.return_value = None transport.read.side_effect = [ ACK(), RSP('03 32010607'), # GetFirmwareVersion ACK(), RSP('15'), # SAMConfiguration ] device = nfc.clf.pn532.init(transport) assert isinstance(device, nfc.clf.pn532.Device) assert transport.write.mock_calls == [call(_) for _ in [ HEX(10 * '00') + CMD('02'), # GetFirmwareVersion HEX(10 * '00') + CMD('14 010000'), # SAMConfiguration ]]
def transport(mocker): mocker.patch('nfc.clf.transport.USB.__init__').return_value = None transport = nfc.clf.transport.USB(1, 1) mocker.patch.object(transport, 'write', autospec=True) mocker.patch.object(transport, 'read', autospec=True) transport._manufacturer_name = "Company" transport._product_name = "Reader" transport.context = None transport.usb_dev = None return transport
def tests_cmd_line_exit(mocker): cmd_args = [] fake_stdout = mocker.patch("sys.stdout", new=StringIO()) fake_inst = mocker.patch.object(instVHDL, "instantiateEntity") with pytest.raises(SystemExit) as exit_raise: instVHDL.command_line_interface(cmd_args) assert "Usage of script" in fake_stdout.getvalue() fake_inst.assert_not_called() mocker.resetall()
def test_connect_tty(mocker, device, found, result_type): sys_platform, sys.platform = sys.platform, 'testing' mocker.patch('nfc.clf.transport.USB') mocker.patch('nfc.clf.transport.USB.find').return_value = None mocker.patch('nfc.clf.transport.TTY') mocker.patch('nfc.clf.transport.TTY.find').return_value = found mocker.patch('nfc.clf.pn532.init').return_value = device device = nfc.clf.device.connect('tty') assert isinstance(device, result_type) sys.platform = sys_platform
def test_build_expands_wildcards(mocker, testing_workdir): build_tree = mocker.patch("conda_build.build.build_tree") config = api.Config() files = ['abc', 'acb'] for f in files: os.makedirs(f) with open(os.path.join(f, 'meta.yaml'), 'w') as fh: fh.write('\n') api.build(["a*"], config=config) output = [os.path.join(os.getcwd(), path, 'meta.yaml') for path in files] build_tree.assert_called_once_with(output, post=None, need_source_download=True, build_only=False, notest=False, config=config)
def test_connect_tty_driver_init_error(mocker): # noqa: F811 found = (['/dev/ttyS0'], 'pn532', True) sys_platform, sys.platform = sys.platform, 'testing' mocker.patch('nfc.clf.transport.USB') mocker.patch('nfc.clf.transport.USB.find').return_value = None mocker.patch('nfc.clf.transport.TTY') mocker.patch('nfc.clf.transport.TTY.find').return_value = found mocker.patch('nfc.clf.pn532.init').side_effect = IOError() assert nfc.clf.device.connect('tty') is None found = (['/dev/ttyS0'], 'pn532', False) mocker.patch('nfc.clf.transport.TTY.find').return_value = found with pytest.raises(IOError): nfc.clf.device.connect('tty') sys.platform = sys_platform
def test_connect_usb_linux_check_access(mocker, device, access): found = [(0x054c, 0x0193, 1, 2)] sys_platform, sys.platform = sys.platform, 'linux' mocker.patch('nfc.clf.transport.USB') mocker.patch('nfc.clf.transport.USB.find').return_value = found mocker.patch('nfc.clf.transport.TTY') mocker.patch('nfc.clf.transport.TTY.find').return_value = None mocker.patch('nfc.clf.pn531.init').return_value = device mocker.patch('os.access').return_value = access device = nfc.clf.device.connect('usb') assert isinstance(device, nfc.clf.device.Device) == access if access is False: with pytest.raises(IOError): nfc.clf.device.connect('usb:001:002') sys.platform = sys_platform
def test_connect_udp(mocker, device): # noqa: F811 mocker.patch('nfc.clf.transport.USB') mocker.patch('nfc.clf.transport.USB.find').return_value = None mocker.patch('nfc.clf.transport.TTY') mocker.patch('nfc.clf.transport.TTY.find').return_value = None mocker.patch('nfc.clf.udp.init').return_value = device device = nfc.clf.device.connect('udp') assert isinstance(device, nfc.clf.device.Device) assert device.path == "udp:localhost:54321" device = nfc.clf.device.connect('udp:remotehost:12345') assert isinstance(device, nfc.clf.device.Device) assert device.path == "udp:remotehost:12345"
def test_connect_usb_driver_init_error(mocker): # noqa: F811 found = [(0x054c, 0x0193, 1, 2)] sys_platform, sys.platform = sys.platform, 'testing' mocker.patch('nfc.clf.transport.USB') mocker.patch('nfc.clf.transport.USB.find').return_value = found mocker.patch('nfc.clf.transport.TTY') mocker.patch('nfc.clf.transport.TTY.find').return_value = None mocker.patch('nfc.clf.pn531.init').side_effect = IOError() assert nfc.clf.device.connect('usb') is None with pytest.raises(IOError): nfc.clf.device.connect('usb:001:002') sys.platform = sys_platform
def test_init_version_rsp_err(self, mocker, transport): # noqa: F811 mocker.patch('nfc.clf.pn532.Device.__init__').return_value = None sys.platform = "" transport.write.return_value = None transport.read.side_effect = [ ACK(), ERR(), # GetFirmwareVersion ] with pytest.raises(IOError) as excinfo: nfc.clf.pn532.init(transport) assert excinfo.value.errno == errno.ENODEV assert transport.write.mock_calls == [call(_) for _ in [ HEX(10 * '00') + CMD('02'), # GetFirmwareVersion ]]
def generate_mocked_results(mocker, target, instances=10, expected=None): """ Generate a list of mocked results with property `prop`. One of the results is set to `expected` and the rest are random values. """ results = [mocker.patch(target) for _ in range(10)] # Set the last Results with the expected value results[9].prop = expected # Initialize the other results with random numbers rs = np.random.uniform(high=5.0, size=9) for (i,), x in np.ndenumerate(rs): setattr(results[i], 'prop', x) return results
def usb_context(self, mocker): libusb = 'nfc.clf.transport.libusb' return mocker.patch(libusb + '.USBContext', autospec=True)
def device(mocker): mocker.patch('nfc.clf.device.Device.__init__').return_value = None return nfc.clf.device.Device()
def test_recv_data_timeout_error(self, mocker, device): # noqa: F811 target = self.test_sense_tta_with_tt1_target_found(device) mocker.patch('nfc.clf.udp.select.select').return_value = ([], [], []) with pytest.raises(nfc.clf.TimeoutError): device.send_cmd_recv_rsp(target, None, 0.001)
def device_connect(self, mocker): return mocker.patch('nfc.clf.device.connect')
def test_find_com_port(self, mocker, path, found): mocker.patch('nfc.clf.transport.serial.tools.list_ports.comports') \ .return_value = [('COM1',), ('COM2',), ('COM3',)] assert nfc.clf.transport.TTY.find(path) == found
def serial(self, mocker): return mocker.patch('nfc.clf.transport.serial.Serial', autospec=True)
def test_activate(mocker, clf, target): # noqa: F811 mocker.patch('nfc.tag.activate_tt3').side_effect = nfc.clf.TimeoutError target._brty_send = '106F' assert nfc.tag.activate(clf, target) is None