def test_submit_cancel_request(self):
        '''
        Large test:
        - Do we make our HTTP request with the expected values?
        - Do we get back the proper response type
        - Does the response contain the data we think it should?
        '''
        with patch('veritranspay.veritrans.requests.post') as mock_post:

            order_id = ''.join([fake.random_letter() for _ in range(25)])

            # mock out our approval request
            req = MagicMock(spec=request.CancelRequest)
            req.order_id = order_id
            # req.attach_mock(MagicMock(return_value=order_id), 'order_id')
            req.attach_mock(MagicMock(return_value=None), 'validate_all')

            # mock out our HTTP post
            mock_resp = MagicMock()
            mock_resp.attach_mock(
                MagicMock(return_value=fixtures.CANCEL_RESPONSE), 'json')
            mock_post.return_value = mock_resp

            # get a response from the gateway
            gateway = veritrans.VTDirect(self.server_key)
            resp = gateway.submit_cancel_request(req)

            # did we make our HTTP request properly?
            mock_post.assert_called_once_with(
                'https://api.midtrans.com/v2/'
                '{order_id}/cancel'.format(order_id=order_id),
                auth=(self.server_key, ''),
                headers={'accept': 'application/json'})

            # was it the correct type?
            self.assertIsInstance(resp, response.CancelResponse)

            # last, take our expected return values and do a little
            # massaging out to account for modifications performed
            # by response object
            exp = deepcopy(fixtures.CANCEL_RESPONSE)
            exp['status_code'] = int(exp['status_code'])
            exp['transaction_time'] = \
                helpers.parse_veritrans_datetime(exp['transaction_time'])
            exp['gross_amount'] = \
                helpers.parse_veritrans_amount(exp['gross_amount'])

            # does it have our expected attributes?
            self.assertEqual(resp.status_code, int(exp['status_code']))
            self.assertEqual(resp.status_message, exp['status_message'])
            self.assertEqual(resp.transaction_id, exp['transaction_id'])
            self.assertEqual(resp.masked_card, exp['masked_card'])
            self.assertEqual(resp.order_id, exp['order_id'])
            self.assertEqual(resp.payment_type, exp['payment_type'])
            self.assertEqual(resp.transaction_time, exp['transaction_time'])
            self.assertEqual(resp.transaction_status,
                             exp['transaction_status'])
            self.assertEqual(resp.fraud_status, exp['fraud_status'])
            self.assertEqual(resp.bank, exp['bank'])
            self.assertEqual(resp.gross_amount, exp['gross_amount'])
Example #2
0
File: helpers.py Project: alex/exam
def track(**mocks):
    tracker = MagicMock()

    for name, mocker in mocks.items():
        tracker.attach_mock(mocker, name)

    return tracker
    def test_mapper_args_value(self, db, bridge, mocker):
        """
        Test checks:
        1) that 'FeedItem' class is instantiated once with correct arguments
        2) that 'self.mapper' method is called once with correct arguments,
        Actually, with the item yielded by 'get_tenders' function.
        3) that 'self.mapper' was called AFTER 'FeedItem' class instantiated.
        """
        mock_feed_item = mocker.patch.object(databridge_module, 'FeedItem',
                                             side_effect=FeedItem,
                                             autospec=True)

        manager = MagicMock()

        mock_mapper = MagicMock()
        bridge['bridge'].mapper = mock_mapper

        manager.attach_mock(mock_mapper, 'mock_mapper')
        manager.attach_mock(mock_feed_item, 'mock_feed_item')

        bridge['bridge_thread'].join(0.1)

        manager.assert_has_calls(
            [call.mock_feed_item(bridge['tenders'][0]),
             call.mock_mapper(mock_feed_item(bridge['tenders'][0]))]
        )
Example #4
0
    def test_serialize_returns_expected(self):

        obj_with_ser = MagicMock(spec=object)
        mock_serialize = MagicMock(return_value={'a': 'b'})
        obj_with_ser.attach_mock(mock_serialize, 'serialize')

        obj_without_ser = MagicMock(spec=object)

        class ICanSerialize(mixins.SerializableMixin):
            def __init__(self):
                self.attr1 = obj_with_ser
                self.attr2 = obj_without_ser

        serialize_me = ICanSerialize()

        actual = serialize_me.serialize()

        expected = {
            'attr1': {
                'a': 'b',
            },
            'attr2': obj_without_ser,
        }

        self.assertEqual(actual, expected)
        mock_serialize.assert_any_call()
    def test_mapper_args_value(self, db, bridge, mocker):
        """
        Test checks:
        1) that 'FeedItem' class is instantiated once with correct arguments
        2) that 'self.mapper' method is called once with correct arguments,
        Actually, with the item yielded by 'get_tenders' function.
        3) that 'self.mapper' was called AFTER 'FeedItem' class instantiated.
        """
        mock_feed_item = mocker.patch.object(databridge_module,
                                             'FeedItem',
                                             side_effect=FeedItem,
                                             autospec=True)

        manager = MagicMock()

        mock_mapper = MagicMock()
        bridge['bridge'].mapper = mock_mapper

        manager.attach_mock(mock_mapper, 'mock_mapper')
        manager.attach_mock(mock_feed_item, 'mock_feed_item')

        bridge['bridge_thread'].join(0.1)

        manager.assert_has_calls([
            call.mock_feed_item(bridge['tenders'][0]),
            call.mock_mapper(mock_feed_item(bridge['tenders'][0]))
        ])
Example #6
0
def test_session_is_cached():

    manager = MagicMock()

    httpretty.register_uri(
        httpretty.POST,
        FAKE_EXCHANGE_URL,
        status=200,
        body="",
    )

    with patch('requests.Session') as MockSession:

        manager.attach_mock(MockSession, 'MockSession')

        connection = ExchangeNTLMAuthConnection(
            url=FAKE_EXCHANGE_URL,
            username=FAKE_EXCHANGE_USERNAME,
            password=FAKE_EXCHANGE_PASSWORD)

        connection.send("test")
        connection.send("test again")

        # assert we only get called once, after that it's cached
        manager.MockSession.assert_called_once_with()
Example #7
0
def track(**mocks):
    tracker = MagicMock()

    for name, mocker in mocks.items():
        tracker.attach_mock(mocker, name)

    return tracker
Example #8
0
    def test_set_eval_mode(self, mock_eval, mock_call):
        """ Make sure that evaluation is done in evaluation mode. """
        mock_mgr = MagicMock()
        mock_mgr.attach_mock(mock_eval, 'eval')
        mock_mgr.attach_mock(mock_call, 'call')

        evaluator = Evaluator(batch_size=64)
Example #9
0
class WhenTestingStoragePersistence(unittest.TestCase):
    def setUp(self):
        self.message = {
            "processid": "3071",
            "appname": "dhcpcd",
            "timestamp": "2013-04-05T15:51:18.607457-05:00",
            "hostname": "tohru",
            "priority": "30",
            "version": "1",
            "messageid": "-",
            "message": "wlan0: leased 10.6.173.172 for 3600 seconds\n",
            "sd": {
                "origin": {
                    "software": "rsyslogd",
                    "swVersion": "7.2.5",
                    "x-pid": "24592",
                    "x-info": "http://www.rsyslog.com"
                }
            }
        }
        self.sink = MagicMock()
        self.sink.attach_mock(MagicMock(), 'put')
        self.db_handler = MagicMock(return_value=self.sink)

    def test_persist_message_calls_db_put(self):
        with patch('meniscus.api.storage.persistence.db_handler',
                   self.db_handler):
            persist_message(self.message)
            self.sink.put.assert_called_once_with('logs', self.message)
 def test_with_pointer_location(self, mock_get):
     mock_region = MagicMock()
     mock_contains = MagicMock(return_value=self.CONTAINS)
     mock_region.attach_mock(mock_contains, 'contains')
     self.pointer_window.region = mock_region
     self.pointer_window.contains_pointer(self.PROVIDED_MOUSE_POS)
     self.assertEquals(mock_get.call_count, 0)
     mock_contains.assert_called_once_with(self.PROVIDED_MOUSE_POS)
 def test_without_pointer_location(self, mock_get):
     mock_region = MagicMock()
     mock_contains = MagicMock(return_value=self.CONTAINS)
     mock_region.attach_mock(mock_contains, 'contains')
     self.pointer_window.region = mock_region
     self.pointer_window.contains_pointer()
     mock_get.assert_called_once_with()
     mock_contains.assert_called_once_with(self.GENERATED_MOUSE_POS)
 def test_move_then_validate(self):
     """Ensures the validate method is called"""
     mock_holder = MagicMock()
     self.patch_ctor_methods()
     mock_holder.attach_mock(self.mock_move, 'move')
     mock_holder.attach_mock(self.mock_validate, 'validate')
     self.construct_options()
     self.schedule_ctor_patch_cleanup()
     mock_holder.assert_has_calls([call.move(), call.validate()])
 def test_runner_method(self):
     mock_container = MagicMock()
     mock_container.attach_mock(self.mock_lexer, 'lexer')
     mock_container.attach_mock(self.mock_formatter, 'formatter')
     mock_container.attach_mock(self.mock_highlight, 'highlight')
     self.block_highlighter.attach_and_highlight()
     mock_container.assert_has_calls(
         [call.lexer(), call.formatter(),
          call.highlight()])
class ValidatableMixin_UnitTests(unittest.TestCase):

    def setUp(self):
        self.name = ''.join([fake.random_letter() for _ in range(20)])
        self.value = ''.join([fake.random_letter() for _ in range(20)])
        self.mock_validator = MagicMock()
        self.mock_validate_method = MagicMock()
        self.mock_validator.attach_mock(self.mock_validate_method,
                                        'validate')

    def test_validate_attr_calls_validate_as_expected(self):
        mixin = mixins.ValidatableMixin()
        mixin.validate_attr(self.name, self.value, self.mock_validator)

        self.mock_validate_method.assert_called_once_with(self.value)

    def test_validate_attr_raises_validation_error(self):
        mixin = mixins.ValidatableMixin()

        self.mock_validate_method.side_effect = validators.ValidationError()

        self.assertRaises(validators.ValidationError,
                          lambda: mixin.validate_attr(
                              self.name,
                              self.value,
                              self.mock_validator))

    def test_validate_attr_validation_error_message_format(self):
        mixin = mixins.ValidatableMixin()

        self.mock_validate_method.side_effect = \
            validators.ValidationError("I'm a little tea pot")

        try:
            mixin.validate_attr(
                self.name,
                self.value,
                self.mock_validator)
        except validators.ValidationError as e:
            self.assertEqual(e.message,
                             "{name} failed validation: {msg}".format(
                                 name=self.name,
                                 msg="I'm a little tea pot"))

    def test_validate_attr_raises_other_errors(self):
        mixin = mixins.ValidatableMixin()

        self.mock_validate_method.side_effect = TypeError()

        self.assertRaises(TypeError,
                          lambda: mixin.validate_attr(
                              self.name,
                              self.value,
                              self.mock_validator))

    def test_validate_all_hits_all_validators(self):
        self.skipTest("Not implemented")
 def test_root_discovery(self, mock_root, mock_screen):
     mock_manager = MagicMock()
     mock_manager.attach_mock(mock_root, 'XRootWindow')
     mock_manager.attach_mock(mock_screen, 'XDefaultScreen')
     self.pointer_window.display = self.DEFAULT_DISPLAY
     self.pointer_window.discover_root_window()
     mock_manager.assert_has_calls([
         call.XDefaultScreen(self.DEFAULT_DISPLAY),
         call.XRootWindow(self.DEFAULT_DISPLAY, self.DEFAULT_SCREEN)
     ])
    def test_invalid_bin_request_raises_ValidationError(self):
        gateway = veritrans.VTDirect(server_key=self.server_key)

        bins_req = MagicMock(spec=request.BinsRequest)
        mock_validate = MagicMock(side_effect=validators.ValidationError)
        bins_req.attach_mock(mock_validate, 'validate_all')

        self.assertRaises(validators.ValidationError,
                          lambda: gateway.bin_request(bins_req))

        self.assertEqual(mock_validate.call_count, 1)
Example #17
0
 def test_calls(self):
     mock_holder = MagicMock()
     mock_holder.attach_mock(
         self.QUERY_POINTER,
         'QueryPointer'
     )
     self.window.get_mouse_windows(self.PRIMARY, self.ROOT_WINDOW)
     mock_holder.assert_has_calls([
         call.QueryPointer(self.ROOT_WINDOW),
         call.QueryPointer().reply()
     ])
    def test_invalid_status_request_raises_ValidationError(self):
        gateway = veritrans.VTDirect(server_key=self.server_key)

        status_req = MagicMock(spec=request.StatusRequest)
        mock_validate = MagicMock(side_effect=validators.ValidationError)
        status_req.attach_mock(mock_validate, 'validate_all')

        self.assertRaises(validators.ValidationError,
                          lambda: gateway.submit_status_request(status_req))

        self.assertEqual(mock_validate.call_count, 1)
Example #19
0
    def test_set_eval_mode(self, mock_eval, mock_call):
        """ Make sure that evaluation is done in evaluation mode. """
        mock_mgr = MagicMock()
        mock_mgr.attach_mock(mock_eval, 'eval')
        mock_mgr.attach_mock(mock_call, 'call')

        evaluator = Evaluator()
        evaluator.evaluate(self.seq2seq, self.dataset)

        expected_calls = [call.eval()] + \
            self.dataset.num_batches(evaluator.batch_size) * [call.call(ANY, ANY, volatile=ANY)]
        self.assertEquals(expected_calls, mock_mgr.mock_calls)
Example #20
0
 def test_write(self, mock_nonnumeric):
     mock_writerow = MagicMock()
     mock_dict = MagicMock()
     mock_dict.attach_mock(mock_writerow, 'writerow')
     self.mock_dict_writer.return_value = mock_dict
     self.result_writer.write_result_row(self.ENTRY)
     self.mock_dict_writer.assert_has_calls([
         call(self.mock_dict_writer.mock_calls[0][1][0],
              fieldnames=WritesResults.FIELDS,
              quoting=mock_nonnumeric),
         call().writerow(self.ENTRY)
     ])
Example #21
0
 def test_order(self):
     manager = MagicMock()
     with patch(REQUEST_MODULE) as Request:
         with patch(RESPONSE_MODULE) as Response:
             manager.attach_mock(Request, 'Request')
             manager.attach_mock(Response, 'Response')
             self.client.get('/')
             # Ugly method, but couldn't find a better one
             first = manager.mock_calls[0].__str__()
             last = manager.mock_calls[-1].__str__()
             self.assertTrue(first.startswith('call.Request'))
             self.assertTrue(last.startswith('call.Response'))
Example #22
0
 def test_order(self):
     manager = MagicMock()
     with patch(REQUEST_MODULE) as Request:
         with patch(RESPONSE_MODULE) as Response:
             manager.attach_mock(Request, 'Request')
             manager.attach_mock(Response, 'Response')
             self.client.get('/')
             # Ugly method, but couldn't find a better one
             first = manager.mock_calls[0].__str__()
             last = manager.mock_calls[-1].__str__()
             self.assertTrue(first.startswith('call.Request'))
             self.assertTrue(last.startswith('call.Response'))
Example #23
0
 def test_logger_set(self, mock_get):
     mock_handler = MagicMock()
     mock_level = MagicMock()
     mock_logging = MagicMock()
     mock_logging.attach_mock(mock_handler, 'addHandler')
     mock_logging.attach_mock(mock_level, 'setLevel')
     mock_get.return_value = mock_logging
     HasLogger()
     mock_get.assert_has_calls([
         call(mock_get.mock_calls[0][1][0]),
         call().addHandler(mock_get.mock_calls[1][1][0]),
         call().setLevel(mock_get.mock_calls[2][1][0])
     ])
    def test_submit_credit_card_charge(self):
        '''
        Large test for submitting credit card charge.
        - Do we make our HTTP Request with the expected values
        - Do we get the correct response type back?
        - Does the response contain the data that it should?
        '''
        with patch('veritranspay.veritrans.requests.post') as mock_post:

            # create a fake key and request payload
            payload = {
                'charge_type': 'I am a little tea cup',
            }

            gateway = veritrans.VTDirect(server_key=self.server_key)

            req = MagicMock()
            req.charge_type = MagicMock(spec=payment_types.CreditCard)
            req.attach_mock(MagicMock(return_value=payload), 'serialize')

            # mock the response data
            # so thta the JSON method returns a documented response
            # value
            mock_resp = MagicMock()
            mock_post.return_value = mock_resp
            mock_resp.attach_mock(
                MagicMock(return_value=fixtures.CC_CHARGE_RESPONSE_SUCCESS),
                'json')

            resp = gateway.submit_charge_request(req)

            # make sure requests library was called in the expected way.
            mock_post.assert_called_once_with(
                'https://api.midtrans.com/v2/charge',
                auth=(self.server_key, ''),
                headers={
                    'content-type': 'application/json',
                    'accept': 'application/json'
                },
                data=json.dumps(payload))

            # did we get the expected response type?
            self.assertIsInstance(resp, response.CreditCardChargeResponse)

            # did it look like we expected
            expected_response_format = response.CreditCardChargeResponse(
                **fixtures.CC_CHARGE_RESPONSE_SUCCESS)

            # need to compare their dictionary formats
            self.assertEqual(expected_response_format.__dict__, resp.__dict__)
    def test_invalid_approval_request_raises_ValidationError(self):
        '''
        Validation error should be bubbled-up to the calling client code.
        '''
        gateway = veritrans.VTDirect(server_key=self.server_key)

        approval_req = MagicMock(spec=request.ApprovalRequest)
        mock_validate = MagicMock(side_effect=validators.ValidationError)
        approval_req.attach_mock(mock_validate, 'validate_all')

        self.assertRaises(validators.ValidationError,
                          lambda: gateway.submit_status_request(approval_req))

        self.assertEqual(mock_validate.call_count, 1)
    def test_set_eval_mode(self, mock_eval, mock_call):
        """ Make sure that evaluation.txt is done in evaluation.txt mode. """
        mock_mgr = MagicMock()
        mock_mgr.attach_mock(mock_eval, 'eval')
        mock_mgr.attach_mock(mock_call, 'call')

        evaluator = Evaluator(batch_size=64)
        with patch('seq2seq.evaluator.evaluator.torch.stack', return_value=None), \
                patch('seq2seq.loss.NLLLoss.eval_batch', return_value=None):
            evaluator.evaluate(self.seq2seq, self.dataset)

        num_batches = int(math.ceil(len(self.dataset) / evaluator.batch_size))
        expected_calls = [call.eval()] + num_batches * [call.call(ANY, ANY, ANY)]
        self.assertEquals(expected_calls, mock_mgr.mock_calls)
    def test_invalid_approval_request_raises_ValidationError(self):
        '''
        Validation error should be bubbled-up to the calling client code.
        '''
        gateway = veritrans.VTDirect(server_key=self.server_key)

        approval_req = MagicMock(spec=request.ApprovalRequest)
        mock_validate = MagicMock(side_effect=validators.ValidationError)
        approval_req.attach_mock(mock_validate, 'validate_all')

        self.assertRaises(validators.ValidationError,
                          lambda: gateway.submit_status_request(approval_req))

        self.assertEqual(mock_validate.call_count, 1)
    def test_submit_credit_card_charge(self):
        '''
        Large test for submitting credit card charge.
        - Do we make our HTTP Request with the expected values
        - Do we get the correct response type back?
        - Does the response contain the data that it should?
        '''
        with patch('veritranspay.veritrans.requests.post') as mock_post:

            # create a fake key and request payload
            payload = {'charge_type': 'I am a little tea cup',
                       }

            gateway = veritrans.VTDirect(server_key=self.server_key)

            req = MagicMock()
            req.charge_type = MagicMock(spec=payment_types.CreditCard)
            req.attach_mock(MagicMock(return_value=payload),
                            'serialize')

            # mock the response data
            # so thta the JSON method returns a documented response
            # value
            mock_resp = MagicMock()
            mock_post.return_value = mock_resp
            mock_resp.attach_mock(
                MagicMock(return_value=fixtures.CC_CHARGE_RESPONSE_SUCCESS),
                'json')

            resp = gateway.submit_charge_request(req)

            # make sure requests library was called in the expected way.
            mock_post.assert_called_once_with(
                'https://api.veritrans.co.id/v2/charge',
                auth=(self.server_key, ''),
                headers={'content-type': 'application/json',
                         'accept': 'application/json'},
                data=json.dumps(payload))

            # did we get the expected response type?
            self.assertIsInstance(resp, response.CreditCardChargeResponse)

            # did it look like we expected
            expected_response_format = response.CreditCardChargeResponse(
                **fixtures.CC_CHARGE_RESPONSE_SUCCESS)

            # need to compare their dictionary formats
            self.assertEqual(expected_response_format.__dict__,
                             resp.__dict__)
Example #29
0
    def test_close_idle_connection_not_pooled(self):
        """Tests that the setting to close an idle connection in a client propagates to the connection
        for an unpooled connection
        """
        mock = MagicMock(spec=Connection(), autospec=True)
        function_mock = Mock(name="close_idle_connections_mock")
        mock.attach_mock(function_mock, "close_idle_connections")
        session = Factory.create_session_from_file(
            configuration_file_name=PROPERTIES_URI, connection=mock,
            api_key_id=API_KEY_ID, secret_api_key=SECRET_API_KEY)
        client = Factory.create_client_from_session(session)

        client.close_idle_connections(timedelta(seconds=5))  # seconds

        function_mock.assert_not_called()
Example #30
0
    def test_close_expired_connections_pooled(self):
        """Tests that the setting to close an expired connection in a client propagates to the connection
        for a pooled connection
        """
        pooled_mock = MagicMock(spec=PooledConnection(), autospec=True)
        function_mock = Mock(name="close_expired_connections_mock")
        pooled_mock.attach_mock(function_mock, "close_expired_connections")
        session = Factory.create_session_from_file(
            configuration_file_name=PROPERTIES_URI, connection=pooled_mock,
            api_key_id=API_KEY_ID, secret_api_key=SECRET_API_KEY)
        client = Factory.create_client_from_session(session)

        client.close_expired_connections()

        function_mock.assert_called_once()
    def test_invalid_charge_request_raises_ValidationError(self):
        '''
        Make sure that if any of the sub-entities raise a ValidationError
        that it is bubbled out to calling code.
        '''
        gateway = veritrans.VTDirect(server_key=self.server_key)

        charge_req = MagicMock(spec=request.ChargeRequest)
        mock_validate = MagicMock(side_effect=validators.ValidationError)
        charge_req.attach_mock(mock_validate, 'validate_all')

        self.assertRaises(validators.ValidationError,
                          lambda: gateway.submit_charge_request(charge_req))

        self.assertEqual(mock_validate.call_count, 1)
    def test_invalid_charge_request_raises_ValidationError(self):
        '''
        Make sure that if any of the sub-entities raise a ValidationError
        that it is bubbled out to calling code.
        '''
        gateway = veritrans.VTDirect(server_key=self.server_key)

        charge_req = MagicMock(spec=request.ChargeRequest)
        mock_validate = MagicMock(side_effect=validators.ValidationError)
        charge_req.attach_mock(mock_validate, 'validate_all')

        self.assertRaises(validators.ValidationError,
                          lambda: gateway.submit_charge_request(charge_req))

        self.assertEqual(mock_validate.call_count, 1)
    def test_validate_all_called_on_value(self):
        '''
        When passed a scalar, passthrough validator should call validate_all
        on the scalar.
        '''
        v = validators.PassthroughValidator()

        mock = MagicMock()
        # mocks are iterable .. we don't want that here
        mock.attach_mock(MagicMock(side_effect=TypeError), '__iter__')
        validate_mock = MagicMock()
        mock.attach_mock(validate_mock, 'validate_all')

        v.validate(mock)

        validate_mock.assert_called_once_with()
Example #34
0
    def test_validate_all_called_on_value(self):
        '''
        When passed a scalar, passthrough validator should call validate_all
        on the scalar.
        '''
        v = validators.PassthroughValidator()

        mock = MagicMock()
        # mocks are iterable .. we don't want that here
        mock.attach_mock(MagicMock(side_effect=TypeError), '__iter__')
        validate_mock = MagicMock()
        mock.attach_mock(validate_mock, 'validate_all')

        v.validate(mock)

        validate_mock.assert_called_once_with()
 def test_full_warp(self, mock_move, mock_choose):
     mock_holder = MagicMock()
     mock_holder.attach_mock(
         mock_choose,
         'choose_a_random_window'
     )
     mock_holder.attach_mock(
         mock_move,
         'move_to_random_position_in_window'
     )
     connection = MagicMock()
     self.mover.warp_to_random_window(connection, self.ROOT_WINDOW)
     mock_holder.assert_has_calls([
         call.choose_a_random_window(connection, self.ROOT_WINDOW),
         call.move_to_random_position_in_window(connection, self.WINDOW)
     ])
Example #36
0
    def test_lock_released(self):
        b = Block()
        b.name = "blockname"
        b.lock.acquire = MagicMock(wrap=b.lock.acquire)
        b.lock.release = MagicMock(wrap=b.lock.release)
        lock_methods = MagicMock()
        lock_methods.attach_mock(b.lock.acquire, "acquire")
        lock_methods.attach_mock(b.lock.release, "release")

        with b.lock:
            with b.lock_released():
                pass

        self.assertEquals(
            [call.acquire(), call.release(), call.acquire(), call.release()],
            lock_methods.method_calls)
Example #37
0
    def test_close_expired_connections_not_pooled(self):
        """
        Tests that the setting to close an expired connection in a client does not propagate to the connection for an unpooled connection
        """
        mock = MagicMock(spec=Connection(), autospec=True)
        function_mock = Mock(name="close_expired_connections_mock")
        mock.attach_mock(function_mock, "close_expired_connections")
        client = Factory.create_client_from_file(
            configuration_file_name=PROPERTIES_URI,
            api_key_id=API_KEY_ID,
            secret_api_key=SECRET_API_KEY,
            connection=mock)

        client.close_expired_connections()

        function_mock.assert_not_called()
Example #38
0
class ValidatableMixin_UnitTests(unittest.TestCase):
    def setUp(self):
        self.name = ''.join([fake.random_letter() for _ in range(20)])
        self.value = ''.join([fake.random_letter() for _ in range(20)])
        self.mock_validator = MagicMock()
        self.mock_validate_method = MagicMock()
        self.mock_validator.attach_mock(self.mock_validate_method, 'validate')

    def test_validate_attr_calls_validate_as_expected(self):
        mixin = mixins.ValidatableMixin()
        mixin.validate_attr(self.name, self.value, self.mock_validator)

        self.mock_validate_method.assert_called_once_with(self.value)

    def test_validate_attr_raises_validation_error(self):
        mixin = mixins.ValidatableMixin()

        self.mock_validate_method.side_effect = validators.ValidationError()

        self.assertRaises(
            validators.ValidationError, lambda: mixin.validate_attr(
                self.name, self.value, self.mock_validator))

    def test_validate_attr_validation_error_message_format(self):
        mixin = mixins.ValidatableMixin()

        self.mock_validate_method.side_effect = \
            validators.ValidationError("I'm a little tea pot")

        try:
            mixin.validate_attr(self.name, self.value, self.mock_validator)
        except validators.ValidationError as e:
            self.assertEqual(
                e.message, "{name} failed validation: {msg}".format(
                    name=self.name, msg="I'm a little tea pot"))

    def test_validate_attr_raises_other_errors(self):
        mixin = mixins.ValidatableMixin()

        self.mock_validate_method.side_effect = TypeError()

        self.assertRaises(
            TypeError, lambda: mixin.validate_attr(self.name, self.value, self.
                                                   mock_validator))

    def test_validate_all_hits_all_validators(self):
        self.skipTest("Not implemented")
    def test_submit_virtualaccountmandiri_charge(self):
        with patch('veritranspay.veritrans.requests.post') as mock_post:
            # create a fake key and request payload
            payload = {
                'charge_type': 'I am a little tea cup',
            }

            gateway = veritrans.VTDirect(server_key=self.server_key)

            req = MagicMock()
            req.charge_type = MagicMock(
                spec=payment_types.VirtualAccountMandiri)
            req.attach_mock(MagicMock(return_value=payload), 'serialize')

            # mock the response data
            # so thta the JSON method returns a documented response
            # value
            mock_resp = MagicMock()
            mock_post.return_value = mock_resp
            mock_resp.attach_mock(
                MagicMock(return_value=fixtures.
                          VIRTUALACCOUNTMANDIRI_CHARGE_RESPONSE_SUCCESS),
                'json')

            resp = gateway.submit_charge_request(req)

            # make sure requests library was called in the expected way.
            mock_post.assert_called_once_with(
                'https://api.midtrans.com/v2/charge',
                auth=(self.server_key, ''),
                headers={
                    'content-type': 'application/json',
                    'accept': 'application/json'
                },
                data=json.dumps(payload))

            # did we get the expected response type?
            self.assertIsInstance(resp,
                                  response.VirtualAccountMandiriChargeResponse)

            # did it look like we expected
            expected_response_format = response.VirtualAccountMandiriChargeResponse(
                **fixtures.VIRTUALACCOUNTMANDIRI_CHARGE_RESPONSE_SUCCESS)

            # need to compare their dictionary formats
            self.assertEqual(expected_response_format.__dict__, resp.__dict__)
    def test_bin_request(self):
        '''
        Large test:
        - Do we make our HTTP request with the expected values?
        - Do we get back the proper response type
        - Does the response contain the data we think it should?
        '''
        with patch('veritranspay.veritrans.requests.get') as mock_get:

            bin_number = fixtures.BIN_RESPONSE.get('data').get('bin')

            # mock out our approval request
            req = MagicMock(spec=request.BinsRequest)
            req.bin_number = bin_number
            # req.attach_mock(MagicMock(return_value=order_id), 'order_id')
            req.attach_mock(MagicMock(return_value=None), 'validate_all')

            # mock out our HTTP post
            mock_resp = MagicMock()
            type(mock_resp).status_code = PropertyMock(return_value=200)
            mock_resp.json.return_value = fixtures.BIN_RESPONSE
            mock_resp.return_value.status_message = ''
            mock_get.return_value = mock_resp

            # get a response from the gateway
            gateway = veritrans.VTDirect(self.server_key)
            resp = gateway.bin_request(req)

            # did we make our HTTP request properly?
            mock_get.assert_called_once_with(
                'https://api.midtrans.com/v1/bins/'
                '{bin_number}'.format(bin_number=bin_number),
                auth=(self.server_key, ''),
                headers={'accept': 'application/json'})

            # was it the correct type?
            self.assertIsInstance(resp, response.BinResponse)

            # last, take our expected return values and do a little
            # massaging out to account for modifications performed
            # by response object
            exp = deepcopy(fixtures.BIN_RESPONSE)
            exp['status_code'] = 200
            self.assertEqual(resp.status_code, int(exp['status_code']))
            self.assertEqual(resp.status_message, exp['status_message'])
            self.assertEqual(bin_number, exp.get('data').get('bin'))
Example #41
0
    def test_lock_released(self):
        b = Block()
        b.name = "blockname"
        b.lock.acquire = MagicMock(wrap=b.lock.acquire)
        b.lock.release = MagicMock(wrap=b.lock.release)
        lock_methods = MagicMock()
        lock_methods.attach_mock(b.lock.acquire, "acquire")
        lock_methods.attach_mock(b.lock.release, "release")

        with b.lock:
            with b.lock_released():
                pass

        self.assertEquals(
            [call.acquire(),
             call.release(),
             call.acquire(),
             call.release()], lock_methods.method_calls)
    def test_submit_virtualaccountmandiri_charge(self):
        with patch('veritranspay.veritrans.requests.post') as mock_post:
            # create a fake key and request payload
            payload = {'charge_type': 'I am a little tea cup',
                       }

            gateway = veritrans.VTDirect(server_key=self.server_key)

            req = MagicMock()
            req.charge_type = MagicMock(spec=payment_types.VirtualAccountMandiri)
            req.attach_mock(MagicMock(return_value=payload), 'serialize')

            # mock the response data
            # so thta the JSON method returns a documented response
            # value
            mock_resp = MagicMock()
            mock_post.return_value = mock_resp
            mock_resp.attach_mock(
                MagicMock(return_value=fixtures.VIRTUALACCOUNTMANDIRI_CHARGE_RESPONSE_SUCCESS),
                'json')

            resp = gateway.submit_charge_request(req)

            # make sure requests library was called in the expected way.
            mock_post.assert_called_once_with(
                'https://api.midtrans.com/v2/charge',
                auth=(self.server_key, ''),
                headers={'content-type': 'application/json',
                         'accept': 'application/json'},
                data=json.dumps(payload))

            # did we get the expected response type?
            self.assertIsInstance(resp, response.VirtualAccountMandiriChargeResponse)

            # did it look like we expected
            expected_response_format = response.VirtualAccountMandiriChargeResponse(
                **fixtures.VIRTUALACCOUNTMANDIRI_CHARGE_RESPONSE_SUCCESS)

            # need to compare their dictionary formats
            self.assertEqual(expected_response_format.__dict__,
                             resp.__dict__)
Example #43
0
def test_connection_is_cached_basic_auth():

  httpretty.register_uri(httpretty.POST, FAKE_EXCHANGE_URL,
                           status=200,
                           body="", )

  manager = MagicMock()

  with patch('pyexchange.connection.HTTPBasicAuth') as MockHttpBasicAuth:

    manager.attach_mock(MockHttpBasicAuth, 'MockHttpBasicAuth')

    connection = ExchangeBasicAuthConnection(url=FAKE_EXCHANGE_URL,
                                                username=FAKE_EXCHANGE_USERNAME_BASIC_AUTH,
                                                password=FAKE_EXCHANGE_PASSWORD)

    connection.send("test")
    connection.send("test again")

    # assert we only get called once, after that it's cached
    manager.MockHttpBasicAuth.assert_called_once_with(FAKE_EXCHANGE_USERNAME_BASIC_AUTH, FAKE_EXCHANGE_PASSWORD)
Example #44
0
def test_session_is_cached():

  manager = MagicMock()

  httpretty.register_uri(httpretty.POST, FAKE_EXCHANGE_URL,
                           status=200,
                           body="", )

  with patch('requests.Session') as MockSession:

    manager.attach_mock(MockSession, 'MockSession')

    connection = ExchangeNTLMAuthConnection(url=FAKE_EXCHANGE_URL,
                                                username=FAKE_EXCHANGE_USERNAME,
                                                password=FAKE_EXCHANGE_PASSWORD)

    connection.send("test")
    connection.send("test again")

    # assert we only get called once, after that it's cached
    manager.MockSession.assert_called_once_with()
    def test_validate_all_called_on_iterable_elements(self):
        '''
        When passed an iterable, validate_all should be called on the elements
        of the iterable.
        '''
        v = validators.PassthroughValidator()

        # note: doesn't matter here whether the mocks are iterable or not
        mock1 = MagicMock()
        validate_mock1 = MagicMock()
        mock1.attach_mock(validate_mock1, 'validate_all')

        mock2 = MagicMock()
        validate_mock2 = MagicMock()
        mock2.attach_mock(validate_mock2, 'validate_all')

        mocks = [mock1, mock2]

        v.validate(mocks)

        validate_mock1.assert_called_once_with()
        validate_mock2.assert_called_once_with()
    def test_serialize_returns_expected(self):

        obj_with_ser = MagicMock(spec=object)
        mock_serialize = MagicMock(return_value={'a': 'b'})
        obj_with_ser.attach_mock(mock_serialize, 'serialize')

        obj_without_ser = MagicMock(spec=object)

        class ICanSerialize(mixins.SerializableMixin):
            def __init__(self):
                self.attr1 = obj_with_ser
                self.attr2 = obj_without_ser

        serialize_me = ICanSerialize()

        actual = serialize_me.serialize()

        expected = {'attr1': {'a': 'b', },
                    'attr2': obj_without_ser,
                    }

        self.assertEqual(actual, expected)
        mock_serialize.assert_any_call()
    def test_proxy_path_event_source(self, mock_auctions_server,
                                     patch_response):

        manager = MagicMock()
        manager.attach_mock(mock_auctions_server['patch_PySse'],
                            'patch_PySse')
        manager.attach_mock(mock_auctions_server['patch_add_message'],
                            'patch_add_message')
        manager.attach_mock(patch_response['patch_resp'], 'patch_resp')

        output = auctions_proxy(AUCTION_DOC_ID, 'event_source')

        # assertion block
        expected_calls = [call.patch_PySse(),
                          call.patch_add_message('Close', 'Disable'),
                          call.patch_resp(
                              mock_auctions_server['patch_PySse'].return_value,
                              mimetype='text/event-stream',
                              content_type='text/event-stream'
                          )]
        assert manager.mock_calls == expected_calls
        assert output == patch_response['result']
Example #48
0
class TestBus(object):

    def setup(self):
        self.patcher1 = patch('implib2.imp_bus.Device')
        self.patcher2 = patch('implib2.imp_bus.Command')
        self.patcher3 = patch('implib2.imp_bus.Responce')

        mock_dev = self.patcher1.start()
        mock_cmd = self.patcher2.start()
        mock_res = self.patcher3.start()

        self.dev = mock_dev()
        self.cmd = mock_cmd()
        self.res = mock_res()

        self.manager = MagicMock()
        self.manager.attach_mock(self.dev, 'dev')
        self.manager.attach_mock(self.cmd, 'cmd')
        self.manager.attach_mock(self.res, 'res')

        self.bus = Bus()

    def teardown(self):
        self.patcher1.stop()
        self.patcher2.stop()
        self.patcher3.stop()

    def test_wakeup(self):
        address = 16777215
        table = 'ACTION_PARAMETER_TABLE'
        param = 'EnterSleep'
        value = 0
        ad_param = 0
        package = a2b('fd1504fffffffe05000035')

        expected_calls = [
            call.dev.open_device(),
            call.cmd.set_parameter(address, table, param, [value], ad_param),
            call.dev.write_pkg(package),
        ]

        self.cmd.set_parameter.return_value = package
        self.dev.write_pkg.return_value = True

        assert self.bus.wakeup()
        assert self.manager.mock_calls == expected_calls

    def test_sync(self):
        address = 16777215
        table = 'SYSTEM_PARAMETER_TABLE'
        param = 'Baudrate'
        baudrate = 9600
        value = baudrate/100
        ad_param = 0
        package = a2b('fd0b05ffffffaf0400600054')

        expected_calls = [
            call.dev.open_device(),
            call.cmd.set_parameter(address, table, param, [value], ad_param),
            call.dev.close_device(),

            call.dev.open_device(baudrate=1200),
            call.dev.write_pkg(package),
            call.dev.close_device(),

            call.dev.open_device(baudrate=2400),
            call.dev.write_pkg(package),
            call.dev.close_device(),

            call.dev.open_device(baudrate=4800),
            call.dev.write_pkg(package),
            call.dev.close_device(),

            call.dev.open_device(baudrate=9600),
            call.dev.write_pkg(package),
            call.dev.close_device(),

            call.dev.open_device(baudrate=baudrate)
        ]

        self.cmd.set_parameter.return_value = package
        self.dev.write_pkg.return_value = True

        self.bus.sync(baudrate=baudrate)
        assert self.bus.bus_synced
        assert self.manager.mock_calls == expected_calls

    def test_sync_WithWrongBaudrate(self):
        with pytest.raises(BusError) as e:
            self.bus.sync(baudrate=6666)
        assert e.value.message == "Unknown baudrate!"

    def test_scan_AndFindEverything(self):
        minserial = 0b0001  # 01
        maxserial = 0b1010  # 10

        self.bus.probe_range = MagicMock()
        self.bus.probe_range.return_value = True

        self.bus.probe_module_short = MagicMock()
        self.bus.probe_module_short.return_value = True

        range_list = [
            call(0b1000),  # 08
            call(0b1100),  # 12
            call(0b1110),  # 14
            call(0b1111),  # 15
            call(0b1101),  # 13
            call(0b1010),  # 10
            call(0b1011),  # 11
            call(0b1001),  # 09
            call(0b0100),  # 04
            call(0b0110),  # 06
            call(0b0111),  # 07
            call(0b0101),  # 05
            call(0b0010),  # 02
            call(0b0011),  # 03
            call(0b0001)   # 01
        ]

        modules_list = [
            call(0b1111),  # 15
            call(0b1110),  # 14
            call(0b1101),  # 13
            call(0b1100),  # 12
            call(0b1011),  # 11
            call(0b1010),  # 10
            call(0b1001),  # 09
            call(0b1000),  # 08
            call(0b0111),  # 07
            call(0b0110),  # 06
            call(0b0101),  # 05
            call(0b0100),  # 04
            call(0b0011),  # 03
            call(0b0010),  # 02
            call(0b0001),  # 01
            call(0b0000)   # 00
        ]

        results = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, )

        assert self.bus.scan(minserial, maxserial) == results
        assert self.bus.probe_range.call_args_list == range_list
        assert self.bus.probe_module_short.call_args_list == modules_list

    def test_scan_bus_ButNothingFound(self):
        minserial = 0b0001  # 01
        maxserial = 0b1010  # 10

        self.bus.probe_range = MagicMock()
        self.bus.probe_range.return_value = False

        assert self.bus.scan(minserial, maxserial) is tuple()
        self.bus.probe_range.assert_called_once_with(0b1000)

    @pytest.mark.parametrize("probe", range(33000, 34001))
    def test_scan_AndFindOne(self, probe):
        minserial = 33000
        maxserial = 34000

        def check_range(bcast):
            serno = probe
            while not bcast & 1:
                bcast = bcast >> 1
                serno = serno >> 1
            return (bcast >> 1) == (serno >> 1)

        def check_serno(serno):
            return serno == probe

        self.bus.probe_range = MagicMock()
        self.bus.probe_range.side_effect = check_range

        self.bus.probe_module_short = MagicMock()
        self.bus.probe_module_short.side_effect = check_serno

        assert self.bus.scan(minserial, maxserial) == (probe,)

    def test_find_single_module(self):
        serno = 31002
        package = a2b('fd0800ffffff60')
        bytes_recv = a2b('000805ffffffd91a79000042')

        expected_calls = [
            call.dev.open_device(),
            call.cmd.get_negative_ack(),
            call.dev.write_pkg(package),
            call.dev.read_pkg(),
            call.res.get_negative_ack(bytes_recv)
        ]

        self.cmd.get_negative_ack.return_value = package
        self.dev.read_pkg.return_value = bytes_recv
        self.res.get_negative_ack.return_value = serno

        assert self.bus.find_single_module() == serno
        assert self.manager.mock_calls == expected_calls

    def test_find_single_module_FindNothing(self):
        package = a2b('fd0800ffffff60')
        bytes_recv = DeviceError('Timeout reading header!')

        expected_calls = [
            call.dev.open_device(),
            call.cmd.get_negative_ack(),
            call.dev.write_pkg(package),
            call.dev.read_pkg()
        ]

        self.cmd.get_negative_ack.return_value = package
        self.dev.write_pkg.return_value = True
        self.dev.read_pkg.side_effect = bytes_recv

        assert not self.bus.find_single_module()
        assert self.manager.mock_calls == expected_calls

    def test_probe_module_long(self):
        serno = 31002
        package = a2b('fd02001a79009f')
        bytes_recv = a2b('0002001a7900a7')

        expected_calls = [
            call.dev.open_device(),
            call.cmd.get_long_ack(serno),
            call.dev.write_pkg(package),
            call.dev.read_pkg(),
            call.res.get_long_ack(bytes_recv, serno)
        ]

        self.cmd.get_long_ack.return_value = package
        self.dev.write_pkg.return_value = True
        self.dev.read_pkg.return_value = bytes_recv
        self.res.get_long_ack.return_value = True

        assert self.bus.probe_module_long(serno)
        assert self.manager.mock_calls == expected_calls

    def test_probe_module_long_ButGetDeviceError(self):
        serno = 31002
        package = a2b('fd02001a79009f')
        bytes_recv = DeviceError('Timeout reading header!')

        expected_calls = [
            call.dev.open_device(),
            call.cmd.get_long_ack(serno),
            call.dev.write_pkg(package),
            call.dev.read_pkg(),
        ]

        self.cmd.get_long_ack.return_value = package
        self.dev.write_pkg.return_value = True
        self.dev.read_pkg.side_effect = bytes_recv

        assert not self.bus.probe_module_long(serno)
        assert self.manager.mock_calls == expected_calls

    def test_probe_module_short(self):
        serno = 31002
        package = a2b('fd04001a790003')
        bytes_recv = a2b('24')

        expected_calls = [
            call.dev.open_device(),
            call.cmd.get_short_ack(serno),
            call.dev.write_pkg(package),
            call.dev.read_bytes(1),
            call.res.get_short_ack(bytes_recv, serno)
        ]

        self.cmd.get_short_ack.return_value = package
        self.dev.write_pkg.return_value = True
        self.dev.read_bytes.return_value = bytes_recv
        self.res.get_short_ack.return_value = True

        assert self.bus.probe_module_short(serno)
        assert self.manager.mock_calls == expected_calls

    def test_probe_module_short_ButGetDeviceError(self):
        serno = 31002
        package = a2b('fd04001a790003')
        bytes_recv = DeviceError('Timeout reading header!')

        expected_calls = [
            call.dev.open_device(),
            call.cmd.get_short_ack(serno),
            call.dev.write_pkg(package),
            call.dev.read_bytes(1)
        ]

        self.cmd.get_short_ack.return_value = package
        self.dev.write_pkg.return_value = True
        self.dev.read_bytes.side_effect = bytes_recv

        assert not self.bus.probe_module_short(serno)
        assert self.manager.mock_calls == expected_calls

    def test_probe_range(self):
        broadcast = 0b111100000000000000000000
        package = a2b('fd06000000f0d0')
        bytes_recv = a2b('ff')

        expected_calls = [
            call.dev.open_device(),
            call.cmd.get_range_ack(broadcast),
            call.dev.write_pkg(package),
            call.dev.read(),
            call.res.get_range_ack(bytes_recv)
        ]

        self.cmd.get_range_ack.return_value = package
        self.dev.write_pkg.return_value = True
        self.dev.read.return_value = bytes_recv
        self.res.get_range_ack.return_value = True

        assert self.bus.probe_range(broadcast)
        assert self.manager.mock_calls == expected_calls

    def test_probe_range_AndFindNothing(self):
        broadcast = 0b111100000000000000000000
        package = a2b('fd06000000f0d0')
        bytes_recv = str()

        expected_calls = [
            call.dev.open_device(),
            call.cmd.get_range_ack(broadcast),
            call.dev.write_pkg(package),
            call.dev.read(),
            call.res.get_range_ack(bytes_recv)
        ]

        self.cmd.get_range_ack.return_value = package
        self.dev.write_pkg.return_value = True
        self.dev.read.return_value = bytes_recv
        self.res.get_range_ack.return_value = False

        assert not self.bus.probe_range(broadcast)
        assert self.manager.mock_calls == expected_calls

    def test_get(self):
        serno = 31002
        table = 'SYSTEM_PARAMETER_TABLE'
        param = 'SerialNum'
        package = a2b('fd0a031a7900290100c4')
        bytes_recv = a2b('000a051a7900181a79000042')

        expected_calls = [
            call.dev.open_device(),
            call.cmd.get_parameter(serno, table, param),
            call.dev.write_pkg(package),
            call.dev.read_pkg(),
            call.res.get_parameter(bytes_recv, table, param)
        ]

        self.cmd.get_parameter.return_value = package
        self.dev.write_pkg.return_value = True
        self.dev.read_pkg.return_value = bytes_recv
        self.res.get_parameter.return_value = (31002,)

        assert self.bus.get(serno, table, param) == (serno,)
        assert self.manager.mock_calls == expected_calls

    def test_set(self):
        serno = 31002
        table = 'PROBE_CONFIGURATION_PARAMETER_TABLE'
        param = 'DeviceSerialNum'
        value = [31003]
        ad_param = 0
        package = a2b('fd11071a79002b0c001b790000b0')
        bytes_recv = a2b('0011001a790095')

        expected_calls = [
            call.dev.open_device(),
            call.cmd.set_parameter(serno, table, param, value, ad_param),
            call.dev.write_pkg(package),
            call.dev.read_pkg(),
            call.res.set_parameter(bytes_recv, table, serno)
        ]

        self.cmd.set_parameter.return_value = package
        self.dev.write_pkg.return_value = True
        self.dev.read_pkg.return_value = bytes_recv
        self.res.set_parameter.return_value = True

        assert self.bus.set(serno, table, param, value)
        assert self.manager.mock_calls == expected_calls

    def test_get_eeprom_page(self):
        serno = 30001
        page_nr = 0
        page = [17, 47, 196, 78, 55, 2, 243, 231, 251, 61]
        package = a2b('fd3c0331750029ff0081')
        bytes_recv = a2b('003c0b1a790015112fc44e3702f3e7fb3dc5')

        expected_calls = [
            call.dev.open_device(),
            call.cmd.get_epr_page(serno, page_nr),
            call.dev.write_pkg(package),
            call.dev.read_pkg(),
            call.res.get_epr_page(bytes_recv)
        ]

        self.cmd.get_epr_page.return_value = package
        self.dev.write_pkg.return_value = True
        self.dev.read_pkg.return_value = bytes_recv
        self.res.get_epr_page.return_value = page

        assert self.bus.get_eeprom_page(serno, page_nr) == page
        assert self.manager.mock_calls == expected_calls

    def test_set_eeprom_page(self):
        serno = 30001
        page_nr = 7
        page = [0, 0, 0, 0, 0, 0, 0, 0, 35, 255, 255, 0]
        package = a2b('fd3d0f317500f6ff07000000000000000023ffff007b')
        bytes_recv = a2b('003d001a79004c')

        expected_calls = [
            call.dev.open_device(),
            call.cmd.set_epr_page(serno, page_nr, page),
            call.dev.write_pkg(package),
            call.dev.read_pkg(),
            call.res.set_epr_page(bytes_recv)
        ]

        self.cmd.set_epr_page.return_value = package
        self.dev.write_pkg.return_value = True
        self.dev.read_pkg.return_value = bytes_recv
        self.res.set_epr_page.return_value = True

        assert self.bus.set_eeprom_page(serno, page_nr, page)
        assert self.manager.mock_calls == expected_calls
  def _SetUpMocksForClusterStart(self):
    """Sets up mocks for cluster start tests.

    Returns:
      Parent mock that enables calls of other mocks.
    """
    # Patch functions.
    mock_gce_api_class = mock.patch('gce_cluster.GceApi').start()
    mock_tarfile_open = mock.patch('tarfile.open').start()
    mock_subprocess_call = mock.patch('subprocess.call', return_value=0).start()
    mock_popen = mock.patch('subprocess.Popen').start()
    mock_popen.return_value.returncode = None
    mock_popen.return_value.poll.return_value = 0
    mock_builtin_open = mock.patch('__builtin__.open').start()
    mock_sleep = mock.patch('time.sleep').start()

    # Create parent mock and attach other mocks to it, so that we can
    # track call order of all mocks.
    parent_mock = MagicMock()
    parent_mock.attach_mock(mock_gce_api_class, 'GceApi')
    parent_mock.attach_mock(
        mock_gce_api_class.return_value.CreateInstance,
        'CreateInstance')
    parent_mock.attach_mock(
        mock_gce_api_class.return_value.ListInstances,
        'ListInstances')
    parent_mock.attach_mock(mock_tarfile_open, 'tarfile_open')
    parent_mock.attach_mock(mock_subprocess_call, 'subprocess_call')
    parent_mock.attach_mock(mock_popen, 'Popen')
    parent_mock.attach_mock(mock_popen.return_value.poll, 'poll')
    parent_mock.attach_mock(mock_builtin_open, 'open')
    parent_mock.attach_mock(mock_sleep, 'sleep')

    mock_gce_api_class.return_value.ListInstances.return_value = [
        {'name': 'hm', 'status': 'RUNNING'},
        {'name': 'hw-000', 'status': 'RUNNING'},
        {'name': 'hw-001', 'status': 'RUNNING'},
    ]

    return parent_mock
    def test_submit_status_request(self):
        '''
        Large test:
        - Do we make our HTTP request with the expected values?
        - Do we get back the proper response type
        - Does the response contain the data we think it should?
        '''
        with patch('veritranspay.veritrans.requests.post') as mock_post:

            order_id = ''.join([fake.random_letter() for _ in range(25)])

            # mock out our approval request
            req = MagicMock(spec=request.ApprovalRequest)
            req.order_id = order_id
            # req.attach_mock(MagicMock(return_value=order_id), 'order_id')
            req.attach_mock(MagicMock(return_value=None), 'validate_all')

            # mock out our HTTP post
            mock_resp = MagicMock()
            mock_resp.attach_mock(
                MagicMock(return_value=fixtures.STATUS_RESPONSE),
                'json')
            mock_post.return_value = mock_resp

            # get a response from the gateway
            gateway = veritrans.VTDirect(self.server_key)
            resp = gateway.submit_approval_request(req)

            # did we make our HTTP request properly?
            mock_post.assert_called_once_with(
                'https://api.veritrans.co.id/v2/'
                '{order_id}/approve'.format(order_id=order_id),
                auth=(self.server_key, ''),
                headers={'accept': 'application/json'}
            )

            # was it the correct type?
            self.assertIsInstance(resp, response.ApproveResponse)

            # last, take our expected return values and do a little
            # massaging out to account for modifications performed
            # by response object
            exp = deepcopy(fixtures.STATUS_RESPONSE)
            exp['status_code'] = int(exp['status_code'])
            exp['transaction_time'] = \
                helpers.parse_veritrans_datetime(exp['transaction_time'])
            exp['gross_amount'] = \
                helpers.parse_veritrans_amount(exp['gross_amount'])

            # does it have our expected attributes?
            self.assertEqual(resp.status_code,
                             int(exp['status_code']))
            self.assertEqual(resp.status_message, exp['status_message'])
            self.assertEqual(resp.transaction_id, exp['transaction_id'])
            self.assertEqual(resp.masked_card, exp['masked_card'])
            self.assertEqual(resp.order_id, exp['order_id'])
            self.assertEqual(resp.payment_type, exp['payment_type'])
            self.assertEqual(resp.transaction_time, exp['transaction_time'])
            self.assertEqual(resp.transaction_status,
                             exp['transaction_status'])
            self.assertEqual(resp.fraud_status, exp['fraud_status'])
            self.assertEqual(resp.approval_code, exp['approval_code'])
            self.assertEqual(resp.signature_key, exp['signature_key'])
            self.assertEqual(resp.bank, exp['bank'])
            self.assertEqual(resp.gross_amount, exp['gross_amount'])