def test_remove_bookmark(self): _id = 2 * randrange(1, 500) httpretty.enable() httpretty.allow_net_connect = True # Precisa para a chamada a página funcionar httpretty.register_uri(httpretty.DELETE, 'http://example.com/bookmarks/%d' % _id, body=self.mock_api_content_delete_bookmark) httpretty.register_uri(httpretty.GET, 'http://example.com/bookmarks/', body=self.mock_api_content_get_bookmarks) httpretty.register_uri( httpretty.GET, 'http://example.com/user/', body= '{"id": 35, "name": "Mock User", "email": "*****@*****.**", "isAdmin": false}' ) post_data = { "__operation": "__remove__", "__id": str(_id), "txtTitulo": "Alterado pelo dashboard", "txtUrl": "http://outra.url.com.br/" } response = self.client.post(self.url, post_data) httpretty.disable() httpretty.reset() self.assertEquals(response.context_data['view'].user_message, 'Bookmark removido com sucesso')
def test_create_user_password_does_not_match(self): httpretty.enable() httpretty.allow_net_connect = True # Precisa para a chamada a /login funcionar # mock_api_content_create_bookmark irá retornar sucesso ou erro, dependendo dos parametros httpretty.register_uri(httpretty.POST, 'http://example.com/users/', body=self.mock_api_login_or_create_user) httpretty.register_uri(httpretty.POST, 'http://example.com/auth/', body=self.mock_api_login_or_create_user) # Dados habilitados para sucesso no mock post_data = { "name": "Fulano de Tal", "email": "*****@*****.**", "password": "******", "confirm_password": "******" } response = self.client.post(self.url, post_data) httpretty.disable() httpretty.reset() # Verifica se renderizou a página de login novamente self.assertEquals(response.status_code, 200) self.assertEquals(response.resolver_match.url_name, 'sign-in') self.assertEquals(response.context_data['view'].error_message, 'Senhas não conferem')
def wrapper(*args, **kwargs): httpretty.enable() fun(*args, **kwargs) httpretty.disable() httpretty.reset()
def test_create_new_bookmark(self): httpretty.enable() httpretty.allow_net_connect = True # Precisa para a chamada a página funcionar httpretty.register_uri( httpretty.POST, 'http://example.com/bookmarks/', body=self.mock_api_content_create_or_update_bookmark) httpretty.register_uri(httpretty.GET, 'http://example.com/bookmarks/', body=self.mock_api_content_get_bookmarks) httpretty.register_uri( httpretty.GET, 'http://example.com/user/', body= '{"id": 35, "name": "Mock User", "email": "*****@*****.**", "isAdmin": false}' ) post_data = { "txtTitulo": "Criado pelo dashboard", "txtUrl": "http://outra.url.com.br/" } response = self.client.post(self.url, post_data) httpretty.disable() httpretty.reset() self.assertEquals(response.context_data['view'].user_message, 'Bookmark criado com sucesso')
def test_restores_files(test_repo): organisation = "hmrc-digital" httpretty.enable(allow_net_connect=False) httpretty.reset() with_packages(organisation) with_package_metadata(organisation) with_package_file_metadata(organisation) with_create_packages(organisation) with_file_upload(organisation) restore( username="******", token="hdiasjnhd", organisation=organisation, repositories=[TEST_REPO], ) assert len(package_created_requests(httpretty, organisation)) == 2 assert_package_created( httpretty, organisation, { "name": "fake_package_3", "licenses": ["Apache-2.0"], "vcs_url": "https://github.com/hmrc/fake_package_3", "desc": "a description", "labels": ["something"], "website_url": "example.com", "issue_tracker_url": "example.com", "github_repo": "hmrc/vat-registration", "github_release_notes_file": "README.md", }, ) assert_package_created( httpretty, organisation, { "name": "fake_package_4", "licenses": ["Apache-2.0"], "vcs_url": "https://github.com/hmrc", "desc": None, "labels": None, "website_url": None, "issue_tracker_url": None, "github_repo": None, "github_release_notes_file": None, }, ) uploads = file_uploaded_requests(httpretty) assert len(uploads) == 3 assert (any( x.path == "/api/v1/content/hmrc-digital/repo-to-check/fake_package_4/0.0.1/this/is/my/path/foo.txt?publish=1&override=1" for x in uploads)) assert uploads[0].body == b"this is a test file" assert (any( x.path == "/api/v1/content/hmrc-digital/repo-to-check/fake_package_2/0.0.1/this/is/my/path/foo.txt?publish=1&override=1" for x in uploads)) assert uploads[1].body == b"this is a test file"
def test_get_bookmarks_error(self): httpretty.enable() httpretty.allow_net_connect = False # Mock responderá com erro httpretty.register_uri(httpretty.GET, self.url + '/bookmarks/', status=400) self.assertEquals(self.bookmark_client.get_bookmarks(), []) httpretty.disable() httpretty.reset()
def test_home_status(self): httpretty.enable() httpretty.allow_net_connect = True httpretty.register_uri(httpretty.GET, 'http://example.com/user/', body=self.mock_api_get_user) response = self.client.get(self.url) httpretty.disable() httpretty.reset() self.assertEquals(response.status_code, 200)
def test_home_template(self): httpretty.enable() httpretty.allow_net_connect = True httpretty.register_uri(httpretty.GET, 'http://example.com/user/', body=self.mock_api_get_user) response = self.client.get(self.url) httpretty.disable() httpretty.reset() self.assertEquals(response.template_name, ['home.html'])
def test_login_error(self): httpretty.enable() httpretty.allow_net_connect = False # Mock responderá com erro - falha no login httpretty.register_uri(httpretty.POST, self.url + '/auth/', status=400) self.assertFalse( self.bookmark_client.login(user='******', password='******')) httpretty.disable() httpretty.reset()
def test_redirect_to_home(self): expected_url = reverse('home') httpretty.enable() httpretty.allow_net_connect = True httpretty.register_uri(httpretty.GET, 'http://example.com/user/', body=self.mock_api_get_user) response = self.client.get(self.url) httpretty.disable() httpretty.reset() self.assertRedirects(response, expected_url)
def http_intercept(self, _http_intercept): """ Monkey-patch Python's socket core module to mock all HTTP responses. We will catch calls to H's API and return 200. All other calls will raise an exception, allowing to you see who are are trying to call. """ # We only need to reset once per tests, all other setup can be done # once in `_http_intercept()` yield httpretty.reset()
def test_get_all_bookmarks_error(self): httpretty.enable() httpretty.allow_net_connect = False # Mock responderá com sucesso httpretty.register_uri(httpretty.GET, self.url + '/bookmarks/all/', body=self.mock_api_get_all_bookmarks) self.bookmark_client.token = 'TOKEN_FAKE_NOT_ADMIN' self.assertEquals(self.bookmark_client.get_all_bookmarks(), []) httpretty.disable() httpretty.reset()
def test_login_success(self): httpretty.enable() httpretty.allow_net_connect = False # Mock responderá com token - sucesso no login httpretty.register_uri(httpretty.POST, self.url + '/auth/', body='{"token": "any content"}', content_type="application/json") self.assertTrue( self.bookmark_client.login(user='******', password='******')) httpretty.disable() httpretty.reset()
def test_home_has_bootstrap(self): httpretty.enable() httpretty.allow_net_connect = True httpretty.register_uri(httpretty.GET, 'http://example.com/user/', body=self.mock_api_get_user) response = self.client.get(self.url) httpretty.disable() httpretty.reset() html = response.content.decode('utf-8') self.assertIn('bootstrap.min.css', html) self.assertIn('bootstrap.min.js', html)
def test_delete_bookmark_error(self): _id = 2 * randrange( 1, 500) + 1 # Força número impar - É nossa flag para erro httpretty.enable() httpretty.allow_net_connect = False # mock_api_content_create_bookmark irá retornar sucesso ou erro, dependendo dos parametros httpretty.register_uri(httpretty.DELETE, self.url + '/bookmarks/%d' % _id, body=self.mock_api_content_delete_bookmark) self.assertFalse(self.bookmark_client.delete_bookmark(_id)) httpretty.disable() httpretty.reset()
def test_user_invalid(self): httpretty.enable() httpretty.allow_net_connect = False # Mock responderá com sucesso httpretty.register_uri(httpretty.GET, self.url + '/user/', body=self.mock_api_get_user) self.bookmark_client.token = 'ANOTHER_TOKEN' # Token inválido data = self.bookmark_client.get_user() httpretty.disable() httpretty.reset() self.assertEquals(data, {})
def test_login_session(self): httpretty.enable() httpretty.allow_net_connect = True # Precisa para a chamada a /login funcionar # mock_api_content_create_bookmark irá retornar sucesso ou erro, dependendo dos parametros httpretty.register_uri(httpretty.POST, 'http://example.com/auth/', body=self.mock_api_login_or_create_user) # Dados habilitados para sucesso no mock post_data = {"username": "******", "password": "******"} response = self.client.post(self.url, post_data) httpretty.disable() httpretty.reset() self.assertEquals(self.client.session['user'], 'FAKE_TOKEN')
def test_get_bookmarks(self): mock_content = [] qtd_bookmarks = randrange(2, 10) for _ in range(qtd_bookmarks): mock_content.append(self.get_fake_bookmark()) httpretty.enable() httpretty.allow_net_connect = False # Mock responderá com sucesso httpretty.register_uri(httpretty.GET, self.url + '/bookmarks/', json.dumps(mock_content)) data = self.bookmark_client.get_bookmarks() self.assertEquals(len(data), qtd_bookmarks) httpretty.disable() httpretty.reset()
def test_new_bookmark_error(self): bookmark_title = "" bookmark_url = "" httpretty.enable() httpretty.allow_net_connect = False # mock_api_content_create_bookmark irá retornar sucesso ou erro, dependendo dos parametros httpretty.register_uri( httpretty.POST, self.url + '/bookmarks/', body=self.mock_api_content_create_or_update_bookmark) self.assertFalse( self.bookmark_client.new_bookmark(bookmark_title, bookmark_url)) httpretty.disable() httpretty.reset()
def setUp(self): # configure mocks for nslord def request_callback(r, _, response_headers): try: request = json.loads(r.parsed_body) except JSONDecodeError: request = r.parsed_body return [ 599, response_headers, json.dumps( { 'MockPDNSTestCase': 'This response was generated upon an unexpected request.', 'request': request, 'method': str(r.method), 'requestline': str(r.raw_requestline), 'host': str(r.headers['Host']) if 'Host' in r.headers else None, 'headers': { str(key): str(value) for key, value in r.headers.items() }, }, indent=4) ] super().setUp() httpretty.reset() hr_core.POTENTIAL_HTTP_PORTS.add( 8081) # FIXME should depend on self.expected_requests for method in [ httpretty.GET, httpretty.PUT, httpretty.POST, httpretty.DELETE, httpretty.HEAD, httpretty.PATCH, httpretty.OPTIONS, httpretty.CONNECT ]: for ns in ['LORD', 'MASTER']: httpretty.register_uri( method, self.get_full_pdns_url('.*', ns), body=request_callback, status=599, priority=-100, ) # configure mocks for replication self._mock_replication = mock.patch( 'desecapi.replication.update.delay', return_value=None, wraps=None) self._mock_replication.start()
def test_user(self): httpretty.enable() httpretty.allow_net_connect = False # Mock responderá com sucesso httpretty.register_uri(httpretty.GET, self.url + '/user/', body=self.mock_api_get_user) self.bookmark_client.token = 'TOKEN_FAKE_GET_USER' # Token que o mock retorna sucesso data = self.bookmark_client.get_user() httpretty.disable() httpretty.reset() self.assertIn('id', data) self.assertIn('name', data) self.assertIn('email', data) self.assertIn('isAdmin', data)
def test_login_with_error(self): httpretty.enable() httpretty.allow_net_connect = True # Precisa para a chamada a /login funcionar # mock_api_content_create_bookmark irá retornar sucesso ou erro, dependendo dos parametros httpretty.register_uri(httpretty.POST, 'http://example.com/auth/', body=self.mock_api_login_or_create_user) # Dados habilitados para sucesso no mock post_data = {"username": "******", "password": "******"} response = self.client.post(self.url, post_data) httpretty.disable() httpretty.reset() # Verifica se renderizou a página de login novamente self.assertEquals(response.status_code, 200) self.assertEquals(response.resolver_match.url_name, 'login')
def test_sign_in(self): httpretty.enable() httpretty.allow_net_connect = False # Mock responderá com sucesso httpretty.register_uri(httpretty.POST, self.url + '/users/', body=self.mock_api_login_or_create_user) httpretty.register_uri(httpretty.POST, self.url + '/auth/', body=self.mock_api_login_or_create_user) self.assertTrue( self.bookmark_client.sign_in(name='Foo', email='*****@*****.**', password='******')) httpretty.disable() httpretty.reset()
def test_update_bookmark(self): _id = randrange(1, 1000) bookmark_title = "New Test" bookmark_url = "http://example.com/test" httpretty.enable() httpretty.allow_net_connect = False # mock_api_content_create_bookmark irá retornar sucesso ou erro, dependendo dos parametros httpretty.register_uri( httpretty.PUT, self.url + '/bookmarks/%d' % _id, body=self.mock_api_content_create_or_update_bookmark) self.assertTrue( self.bookmark_client.update_bookmark(_id, bookmark_title, bookmark_url)) httpretty.disable() httpretty.reset()
def setUpTestData(cls): httpretty.enable(allow_net_connect=False) httpretty.reset() hr_core.POTENTIAL_HTTP_PORTS.add( 8081) # FIXME static dependency on settings variable for request in [ cls.request_pdns_zone_create(ns='LORD'), cls.request_pdns_zone_create(ns='MASTER'), cls.request_pdns_zone_axfr(), cls.request_pdns_zone_update(), cls.request_pdns_zone_retrieve_crypto_keys(), cls.request_pdns_zone_retrieve() ]: httpretty.register_uri(**request) cls.setUpTestDataWithPdns() httpretty.reset()
def test_bookmarks(self): httpretty.enable() httpretty.allow_net_connect = True # Precisa para a chamada a página funcionar httpretty.register_uri(httpretty.GET, 'http://example.com/bookmarks/', body=self.mock_api_content_get_bookmarks) httpretty.register_uri( httpretty.GET, 'http://example.com/user/', body= '{"id": 35, "name": "Mock User", "email": "*****@*****.**", "isAdmin": false}' ) response = self.client.get(self.url) httpretty.disable() httpretty.reset() # Verifica se existe bookmarks no contexto enviado para o template self.assertIsNotNone(response.context['bookmarks'])
def test_sign_in_error(self): httpretty.enable() httpretty.allow_net_connect = False httpretty.register_uri(httpretty.POST, self.url + '/users/', body=self.mock_api_login_or_create_user) httpretty.register_uri(httpretty.POST, self.url + '/auth/', body=self.mock_api_login_or_create_user) # Mock responderá com erro self.assertFalse( self.bookmark_client.sign_in(name='Example', email='*****@*****.**', password='******')) httpretty.disable() httpretty.reset()
def do_login(self): httpretty.enable() httpretty.allow_net_connect = True # Precisa para a chamada a /login funcionar # mock_api irá retornar sucesso ou erro, dependendo dos parametros httpretty.register_uri(httpretty.POST, 'http://example.com/auth/', body=self.mock_api_login_or_create_user) httpretty.register_uri( httpretty.GET, 'http://example.com/user/', body= '{"id": 35, "name": "Mock User", "email": "*****@*****.**", "isAdmin": false}' ) # Dados habilitados para sucesso no mock post_data = {"username": "******", "password": "******"} self.client.post(reverse('login'), post_data) httpretty.disable() httpretty.reset()
def test_not_logged(self): httpretty.enable() httpretty.allow_net_connect = True # Mock responderá com sucesso httpretty.register_uri(httpretty.GET, 'http://example.com/user/', body=self.mock_api_get_user) httpretty.register_uri(httpretty.GET, 'http://example.com/bookmarks/all/', body=self.mock_api_get_all_bookmarks) # Salva o token mocado como token do usuário s = self.client.session s["user"] = '' s.save() response = self.client.get(self.url) httpretty.disable() httpretty.reset() self.assertRedirects(response, reverse('login'))
def test_not_admin(self): httpretty.enable() httpretty.allow_net_connect = True # Mock responderá com sucesso httpretty.register_uri(httpretty.GET, 'http://example.com/user/', body=self.mock_api_get_user) httpretty.register_uri(httpretty.GET, 'http://example.com/users/all/', body=self.mock_api_get_all_users) # Salva o token mocado como token do usuário s = self.client.session s["user"] = '******' s.save() response = self.client.get(self.url) httpretty.disable() httpretty.reset() self.assertEquals(response.status_code, 403)
def setUp(self): httpretty.reset() httpretty.enable()
def httpretty(): httpretty_class.reset() httpretty_class.enable() httpretty_class.allow_net_connect = False yield httpretty_class httpretty_class.disable()