Ejemplo n.º 1
0
 def mock_request(self, username, task):
     """
     Patch get_object_or_404 to return given task.
     Yield Mock request as context variable.
     """
     patch("scores.views.get_object_or_404", Mock(side_effect=lambda *a, **k: task)).start()
     yield Mock(user=self.users[username], method="GET", is_ajax=lambda: True, GET={"task_id": 1})
     patch.stopall()
Ejemplo n.º 2
0
def teardown_scenario(scenario):
    """
    Empty the temporary directory and restore the working directory.
    """
    # remove the scenario variables
    del world.scenario

    # Remove the fixtures directory
    shutil.rmtree(world.fixtures_dir)

    # Restore the current working directory
    os.chdir(world.old_cwd)

    # Uninstall all mocks
    patch.stopall()
Ejemplo n.º 3
0
        def _patched(*args, **kwargs):
            try:
                for patch in patches:
                    mock = patch.start()
                    if isinstance(mock.kwargs_field, str):
                        kwargs[mock.kwargs_field] = mock

                # Merge additional fields into kwargs with kwargs taking precedence
                kwargs = dict(additional_fields.items() + kwargs.items())

                retval = func(*args, **kwargs)
            finally:
                Patch.stopall()

            return retval
Ejemplo n.º 4
0
    def test__method(self):
        """ Test Api._method rest submission """
        ret = {'test': 'val'}
        ret_val = RequestRet(content=json_dumps(ret).encode('utf-8'),
                             status_code=200)
        post = patch('requests.post', return_value=ret_val).start()
        delete = patch('requests.delete', return_value=ret_val).start()
        get = patch('requests.get', return_value=ret_val).start()

        # pylint:disable=protected-access
        _auth = Mock()

        # call get
        ret = rest.Api._method(self._url)
        get.assert_called_with(self._url, auth=None)
        self.assertEquals(ret, ret)
        ret = rest.Api._method(self._url, method='GET', auth=_auth)
        get.assert_called_with(self._url, auth=_auth)
        self.assertEquals(ret, ret)

        # call delete
        ret = rest.Api._method(self._url, method='DELETE')
        delete.assert_called_with(self._url, auth=None)
        self.assertEquals(ret, ret)

        # call post
        ret = rest.Api._method(self._url, method='POST', data={})
        post.assert_called_with(
            self._url, data='{}'.encode('utf-8'),
            headers={'content-type': 'application/json'},
            auth=None)
        self.assertEquals(ret, ret)

        # call multipart
        _files = {'entry': '{}'}
        ret = rest.Api._method(self._url, method='MULTIPART', data=_files)
        post.assert_called_with(self._url, files=_files, auth=None)
        self.assertEquals(ret, ret)
        patch.stopall()
Ejemplo n.º 5
0
 def tearDown(self):
     super(FakeFSTest, self).tearDown()
     patch.stopall()
Ejemplo n.º 6
0
 def tearDown(self):
     cache.clear()
     patch.stopall()
Ejemplo n.º 7
0
 def tearDown(self):
     super(TestBasicAuthPolicy, self).tearDown()
     patch.stopall()
Ejemplo n.º 8
0
 def tearDown(self):
     """
     Undo all patches.
     """
     patch.stopall()
Ejemplo n.º 9
0
 def tearDown(self):
     super(TestAuth, self).tearDown()
     patch.stopall()
Ejemplo n.º 10
0
def teardown_module(module):
    """Stop patches and enable logging output"""
    patch.stopall()
    logging.disable(logging.NOTSET)
Ejemplo n.º 11
0
    def tearDown(self):
        """Tear down of test cases."""

        patch.stopall()
Ejemplo n.º 12
0
 def tearDown(self):
     cache.clear()
     db.drop_all()
     patch.stopall()
Ejemplo n.º 13
0
 def tearDown(self):
     try:
         os.remove(TEST_RC_FILE)
     except OSError:
         pass
     patch.stopall()
Ejemplo n.º 14
0
 def tearDown(self):
   patch.stopall()
   if path.exists(TEST_WORKSPACE):
     shutil.rmtree(TEST_WORKSPACE)
Ejemplo n.º 15
0
 def tearDown(self):
     unittest.TestCase.tearDown(self)
     patch.stopall()
Ejemplo n.º 16
0
 def kill_patches(
 ):  # Create a cleanup callback that undoes our patches
     patch.stopall()  # Stops all patches started with start()
     imp.reload(
         implement
     )  # Reload our UUT module which restores the original decorator
Ejemplo n.º 17
0
def tearDownModule():
    patch.stopall()
Ejemplo n.º 18
0
 def tearDown(self):
     super(TestGoogleCloudStorage, self).tearDown()
     patch.stopall()
Ejemplo n.º 19
0
 def tearDown(self):
     db.drop_all()
     patch.stopall()
Ejemplo n.º 20
0
 def tearDown(self):
     # to destroy patch of a structure
     patch.stopall()
Ejemplo n.º 21
0
    def teardown(self):
        super(BaseDealerTest, self).teardown()
        patch.stopall()

        # Reset dealer instance.
        self.dealer = None
Ejemplo n.º 22
0
 def tearDown(self):
     super(TestGoogleCloudStorage, self).tearDown()
     patch.stopall()
 def tearDown(self):
     patch.stopall()
     sys.stderr = sys.__stderr__
Ejemplo n.º 24
0
 def tearDown(self):
     """
     Undo patches.
     """
     super(TestCoachDashboard, self).tearDown()
     patch.stopall()
Ejemplo n.º 25
0
 def tearDown(self):
     self.client._connected = False
     self.client.destroy()
     patch.stopall()
Ejemplo n.º 26
0
 def tearDown(self):
     """
     Undo all patches and reset the cwd
     """
     patch.stopall()
     os.chdir(self._old_cwd)
Ejemplo n.º 27
0
 def kill_patches():
     patch.stopall()
     imp.reload(repository_module)
Ejemplo n.º 28
0
 def tearDown(self):
     super(TestBasicAuthPolicy, self).tearDown()
     patch.stopall()
Ejemplo n.º 29
0
 def tearDownClass(cls):
     patch.stopall()
Ejemplo n.º 30
0
def teardown_module():
    patch.stopall()
Ejemplo n.º 31
0
 def tearDown(self):
     """
     Test teardowns: clean up test-wide patches.
     """
     patch.stopall()
Ejemplo n.º 32
0
 def tearDown(self):
     """
     Undo patches.
     """
     super(TestCoachDashboard, self).tearDown()
     patch.stopall()
Ejemplo n.º 33
0
def test_solve_captcha(app):

    m = 'controllers.solve'
    check_request = _patch("%s.check_request" % m)
    decaptcher_response = _patch("%s.decaptcher_response" % m)
    solvers = _patch("%s.solvers" % m)
    check_solver = _patch("%s.check_solver" % m)
    storage = _patch("%s.RedisStorage" % m)()

    solve = MagicMock()
    solvers.get_highest_notblocked.return_value.__getitem__.return_value\
            = solvers.get_by_name.return_value.__getitem__.return_value\
            = solvers.get_next.return_value.__getitem__.return_value\
            = solve

    pict = Upload('captcha.png', 'picture_binary_data')
    some_data = {'pict': pict}

    # моделирование запроса с невалидными POST-данными
    check_request.return_value = "error description"
    decaptcher_response.return_value = "error"
    app.post('/', some_data)
    #
    assert check_request.called
    assert decaptcher_response.called
    assert not solve.called
    reset_mocks(locals())

    # моделирование запроса с валидными POST-данными
    # без явного указания сервиса-расшифровщика
    check_request.return_value = None
    check_solver.side_effect = ["errcode", None]
    solve.side_effect = [SolverError, "captchacode1"]
    decaptcher_response.return_value = "resp1"
    app.post('/', some_data)
    #
    assert solvers.get_highest_notblocked.call_count == 2
    assert not solvers.get_by_name.called
    assert check_solver.call_count == 2
    assert storage.block.call_count == 1
    assert storage.incr_uses.call_count == 2
    assert solve.call_count == 2
    assert storage.incr_fails.call_count == 1
    assert solvers.get_next.call_count == 1
    assert decaptcher_response.called
    reset_mocks(locals())
    check_solver.side_effect = None

    # моделирование запроса с валидными POST-данными
    # с явным указанием сервиса-расшифровщика
    check_request.return_value = None
    decaptcher_response.return_value = "resp2"
    solve.side_effect = ["captchacode2"]
    app.post('/?upstream_service=captchabot', some_data)
    #
    assert solvers.get_by_name.called
    assert not solvers.get_highest_notblocked.called
    assert not check_solver.called
    assert storage.incr_uses.call_count == 1
    assert solve.call_count == 1
    assert not storage.incr_fails.called
    assert not solvers.get_next.called
    assert decaptcher_response.called
    reset_mocks(locals())
    check_solver.side_effect = None

    # моделирование случая, при котором число попыток
    # расшифровать капчу превышает допустимое
    check_request.return_value = None
    check_solver.return_value = None
    solve.side_effect = SolverError
    decaptcher_response.return_value = "resp1"
    app.post('/', some_data)
    #
    assert storage.incr_uses.call_count\
            == storage.incr_fails.call_count\
            == solve.call_count\
            == solvers.get_next.call_count\
            == settings.MAX_ATTEMPTS_TO_SOLVE
    assert decaptcher_response.called
    reset_mocks(locals())

    # проверяем, что параметры "pict_type" и "pict" передаются в расшифровщик
    some_data = {'pict': pict, 'pict_type': 'some_type'}
    check_request.return_value = None
    check_solver.return_value = None
    solve.side_effect = None
    decaptcher_response.return_value = "resp1"
    app.post('/', some_data)
    #
    assert solve.call_args[1]['pict_type'] == some_data['pict_type']
    reset_mocks(locals())

    patch.stopall()
 def tearDown(self):
     patch.stopall()
     self.testbed.deactivate()
Ejemplo n.º 35
0
 def tearDown(self):
     patch.stopall()
Ejemplo n.º 36
0
 def tearDown(self):
     super(TestS3Storage, self).tearDown()
     patch.stopall()
     self.s3_mock.stop()
Ejemplo n.º 37
0
 def tearDown(self):
     super(TestGoogleCloudStorage, self).tearDown()
     patch.stopall()
     os.remove(self._config_file)
Ejemplo n.º 38
0
 def tearDown(self):
     """
     Undo all patches and reset the cwd
     """
     patch.stopall()
     os.chdir(self._old_cwd)
Ejemplo n.º 39
0
 def remove_patches():
     patch.stopall()
     # Reload module again after removing patch.
     imp.reload(module)
Ejemplo n.º 40
0
 def tearDown(self):
     HelperMixin.tearDown(self)
     patch.stopall()
     shutil.rmtree(self.symbol_dir)
Ejemplo n.º 41
0
 def tearDown(self):
     patch.stopall()
     self.controller = None
Ejemplo n.º 42
0
 def tearDown(self):
     super(TestS3Storage, self).tearDown()
     patch.stopall()
     self.s3_mock.stop()
Ejemplo n.º 43
0
def api_mock_stop():
    """ Stop all patches started by api_mock.
    Actually it stops everything but not a problem """
    patch.stopall()
Ejemplo n.º 44
0
 def tearDownClass(cls):
     patch.stopall()
Ejemplo n.º 45
0
 def tearDown(self):
     api_mock_stop()
     patch.stopall()
Ejemplo n.º 46
0
 def tearDown(self):
     """
     Undo all patches.
     """
     patch.stopall()
 def tearDown(self):
     os.remove(self.node.TTY)
     patch.stopall()
 def tearDown(self):
     patch.stopall()
     sys.stderr = sys.__stderr__
Ejemplo n.º 49
0
 def remove_patches():
   patch.stopall()
   # Reload module again after removing patch.
   imp.reload(module)
Ejemplo n.º 50
0
 def tearDown(self):
     db.drop_all()
     patch.stopall()
def tearDownModule():
    patch.stopall()
Ejemplo n.º 52
0
 def tearDown(self):
     HelperMixin.tearDown(self)
     patch.stopall()
     shutil.rmtree(self.symbol_dir)
Ejemplo n.º 53
0
 def tearDown(self):
     super(TestBaseBackend, self).tearDown()
     patch.stopall()
Ejemplo n.º 54
0
 def tearDown(self):
     self.smtp_server_thread.stop()
     patch.stopall()
Ejemplo n.º 55
0
 def tearDown(self) -> None:
     patch.stopall()
Ejemplo n.º 56
0
 def tearDown(self):
     patch.stopall()
Ejemplo n.º 57
0
 def tearDown(self):
     super().tearDown()
     patch.stopall()