def setUp(self): AsyncHTTPTestCase.setUp(self) # get sid response = self.fetch('/') self.sid = str(response.headers['Set-Cookie'].split(';')[0].split('=')[1].replace('"',''))
def setUp(self): # NB: this is only required when mixing several DBAPIs in one app import dbapiext dbapiext._query_cache.clear() self.http_client = AsyncHTTPClient() AsyncHTTPTestCase.setUp(self)
def stop(self, *args, **kwargs): # A stop() method more permissive about the number of its positional # arguments than AsyncHTTPTestCase.stop if len(args) == 1: AsyncHTTPTestCase.stop(self, args[0], **kwargs) else: AsyncHTTPTestCase.stop(self, args, **kwargs)
def setUp(self): try: self._verbose_logger(self.debug) AsyncHTTPTestCase.setUp(self) except Exception as exc: traceback.print_tb(exc.__traceback__) print("Exception", str(exc)) exit(1)
def tearDown(self): lp = asyncio.get_event_loop() # STOP GINO APP # stop gino app to release db connections # excecutors and file descriptors lp.run_until_complete(self._app.db.pop_bind().close()) # delete server and connections AsyncHTTPTestCase.tearDown(self)
def test_hostgroup_request(self, m_get, m_delete): m_get.return_value = MockResponse( '{\ "name": "Testgroup", \ "id": 999\ }', 200) self._host_dn = "cn=Testgroup,ou=groups,dc=example,dc=net" payload_data = { "event": "after_create", "object": "Testgroup", "data": { "hostgroup": { "hostgroup": { "id": 999, "name": "Testgroup" } } } } headers, payload = self._create_request(payload_data) AsyncHTTPTestCase.fetch(self, "/hooks/", method="POST", headers=headers, body=payload) # check if the host has been updated device = ObjectProxy(self._host_dn) assert device.cn == "Testgroup" assert device.foremanGroupId == "999" # delete the host payload_data = { "event": "after_destroy", "object": "Testgroup", "data": { "hostgroup": { "hostgroup": { "id": 999, "name": "Testgroup" } } } } headers, payload = self._create_request(payload_data) AsyncHTTPTestCase.fetch(self, "/hooks/", method="POST", headers=headers, body=payload) with pytest.raises(ProxyException): ObjectProxy(self._host_dn) self._host_dn = None
def setUp(self): AsyncHTTPTestCase.setUp(self) self.tt_token = {'uid': '1', 'mobile': '18682212241'} token = create_signed_value( configs['cookie_secret'], 'token', token_encode(self.tt_token) ) self.tt_headers = {'Cookie': 'token=' + token} dbc = hqlh.db.get_conn('fitter') dbc.execute('TRUNCATE user')
def setUp(self): """Setup test""" context.GLOBAL.cell = 'test' context.GLOBAL.zk.url = 'zookeeper://xxx@yyy:123' zkclient_mock = mock.Mock() zkclient_mock.get_children = mock.MagicMock(return_value=ALL_NODES) context.ZkContext.conn = zkclient_mock AsyncHTTPTestCase.setUp(self)
def test_request(self, m_get): m_get.return_value = MockResponse( '{\ "status": 0,\ "status_label": "Build"\ }', 200) token = bytes(self.token, 'ascii') payload = bytes( dumps({ "action": "create", "hostname": "new-foreman-host", "parameters": {} }), 'utf-8') signature_hash = hmac.new(token, msg=payload, digestmod="sha512") signature = 'sha1=' + signature_hash.hexdigest() headers = { 'Content-Type': 'application/vnd.foreman.hostevent+json', 'HTTP_X_HUB_SENDER': 'test-webhook', 'HTTP_X_HUB_SIGNATURE': signature } response = AsyncHTTPTestCase.fetch(self, "/hooks/", method="POST", headers=headers, body=payload) otp_response = loads(response.body.decode("utf-8")) assert "randompassword" in otp_response assert otp_response["randompassword"] is not None # check if the host has been created device = ObjectProxy( "cn=new-foreman-host,ou=incoming,dc=example,dc=net") assert device.cn == "new-foreman-host" # delete the host payload = bytes( dumps({ "action": "delete", "hostname": "new-foreman-host", "parameters": {} }), 'utf-8') signature_hash = hmac.new(token, msg=payload, digestmod="sha512") signature = 'sha1=' + signature_hash.hexdigest() headers['HTTP_X_HUB_SIGNATURE'] = signature AsyncHTTPTestCase.fetch(self, "/hooks/", method="POST", headers=headers, body=payload) with pytest.raises(ProxyException): ObjectProxy("cn=new-foreman-host,ou=incoming,dc=example,dc=net")
def setUp(self): self.old_os_env = remove_os_env_temporarily() setup_mock_web_api_server(self) web_client = WebClient(token=valid_token, base_url=mock_api_server_base_url,) self.app = App(client=web_client, signing_secret=signing_secret,) self.app.event("app_mention")(event_handler) self.app.shortcut("test-shortcut")(shortcut_handler) self.app.command("/hello-world")(command_handler) AsyncHTTPTestCase.setUp(self)
def fetch(self, *args, **kwargs): assert ' ' not in args[0], 'Unescaped space in URL' # having to manually open and close a db connection when writing tests would be a pain # but the controllers manage their own connection and they're called from the same process # so we go through the trouble of overwriting this method to manage the connection automatically model.peewee_db.close() # network_interface gets passed through and eventually mapped directly to remote_ip on the request object # but there are also some fallback headers that would achieve the same thing, e.g. X-Forwarded-For headers = kwargs.pop('headers', HEADERS.copy()) if hasattr(self, 'cookies'): headers['Cookie'] = '; '.join( [key + '=' + value for key, value in self.cookies.items()]) kwargs['headers'] = headers # split up redirects here to capture the cookie after the first one response = AsyncHTTPTestCase.fetch(self, *args, network_interface='127.0.0.1', follow_redirects=False, **kwargs) self.setCookie(response) redirect = response.headers.get('Location') if redirect: # cookie might have been updated since last request in setCookie call above if hasattr(self, 'cookies'): headers['Cookie'] = '; '.join( [key + '=' + value for key, value in self.cookies.items()]) kwargs['headers'] = headers # never POSTing twice in a row kwargs['method'] = 'GET' kwargs['body'] = None response = AsyncHTTPTestCase.fetch(self, redirect, network_interface='127.0.0.1', follow_redirects=True, **kwargs) model.peewee_db.connect() response.body_string = response.body.decode() # for convenience return response
def test_registering(self): registry = PluginRegistry.getInstance("WebhookRegistry") hook = TestWebhook() registry.register_handler("application/vnd.gosa.test+plain", hook) url, token = registry.registerWebhook("admin", "test-webhook", "application/vnd.gosa.test+plain") token = bytes(token, 'ascii') signature_hash = hmac.new(token, msg=b"Test", digestmod="sha512") signature = 'sha1=' + signature_hash.hexdigest() headers = { 'Content-Type': 'application/vnd.gosa.test+plain', 'HTTP_X_HUB_SENDER': 'test-webhook', 'HTTP_X_HUB_SIGNATURE': signature } with mock.patch.object(hook, "content") as m_content: AsyncHTTPTestCase.fetch(self, "/hooks/", method="POST", headers=headers, body=b"Test") m_content.assert_called_with(b"Test") m_content.reset_mock() registry.unregisterWebhook("admin", "test-webhook", "application/vnd.gosa.test+plain") AsyncHTTPTestCase.fetch(self, url, method="POST", headers=headers, body=b"Test") assert not m_content.called
def fetch(self, url, **kw): headers = kw.pop('headers', {}) if self.__cookies != '': headers['Cookie'] = self.__cookies if self._xsrf: headers['X-XSRFToken'] = self._xsrf if len(headers['Cookie'])>0 and '_xsrf' not in headers['Cookie']: headers['Cookie'] = "%s;%s=%s" % (headers['Cookie'], '_xsrf', self._xsrf) # if 'body' in kw: # print("URL: {}, Body: {}, Headers: {}".format(url, kw['body'] , headers)) # else: # print("URL: {}, Headers: {}".format(url, headers)) resp = AsyncHTTPTestCase.fetch(self, url, headers=headers, **kw) self._update_cookies(resp.headers) return resp
def fetch(self, url, **kw): headers = kw.pop('headers', {}) if self.__cookies != '': headers['Cookie'] = self.__cookies if self._xsrf: headers['X-XSRFToken'] = self._xsrf if len(headers['Cookie']) > 0 and '_xsrf' not in headers['Cookie']: headers['Cookie'] = "%s;%s=%s" % (headers['Cookie'], '_xsrf', self._xsrf) # if 'body' in kw: # print("URL: {}, Body: {}, Headers: {}".format(url, kw['body'] , headers)) # else: # print("URL: {}, Headers: {}".format(url, headers)) resp = AsyncHTTPTestCase.fetch(self, url, headers=headers, **kw) self._update_cookies(resp.headers) return resp
def test_post(self): # create webhook post e = EventMaker() update = e.Event( e.BackendChange( e.DN("cn=Test,ou=people,dc=example,dc=net"), e.ModificationTime(datetime.now().strftime("%Y%m%d%H%M%SZ")), e.ChangeType("update") ) ) payload = etree.tostring(update) token = bytes(Environment.getInstance().config.get("webhooks.ldap_monitor_token"), 'ascii') signature_hash = hmac.new(token, msg=payload, digestmod="sha512") signature = 'sha1=' + signature_hash.hexdigest() headers = { 'Content-Type': 'application/vnd.gosa.event+xml', 'HTTP_X_HUB_SENDER': 'backend-monitor', 'HTTP_X_HUB_SIGNATURE': signature } with mock.patch("gosa.backend.plugins.webhook.registry.zope.event.notify") as m_notify: AsyncHTTPTestCase.fetch(self, "/hooks/", method="POST", headers=headers, body=payload) assert m_notify.called m_notify.reset_mock() # unregistered sender headers['HTTP_X_HUB_SENDER'] = 'unknown' resp = AsyncHTTPTestCase.fetch(self, "/hooks/", method="POST", headers=headers, body=payload) assert resp.code == 401 assert not m_notify.called # wrong signature headers['HTTP_X_HUB_SENDER'] = 'backend-monitor' headers['HTTP_X_HUB_SIGNATURE'] = 'sha1=823rjadfkjlasasddfdgasdfgasd' resp = AsyncHTTPTestCase.fetch(self, "/hooks/", method="POST", headers=headers, body=payload) assert resp.code == 401 assert not m_notify.called # no signature del headers['HTTP_X_HUB_SIGNATURE'] resp = AsyncHTTPTestCase.fetch(self, "/hooks/", method="POST", headers=headers, body=payload) assert resp.code == 401 assert not m_notify.called # no handler for content type headers['HTTP_X_HUB_SIGNATURE'] = signature headers['Content-Type'] = 'application/vnd.gosa.unknown+xml' resp = AsyncHTTPTestCase.fetch(self, "/hooks/", method="POST", headers=headers, body=payload) assert resp.code == 401 assert not m_notify.called
def setUp(self): self._publisher = PikaPublisher("fake_params", "fake_exchange", "fake_exchange_type", "fake_queue", "fake_routing_key") AsyncHTTPTestCase.setUp(self)
def teardown_async_test_case(self): AsyncHTTPTestCase.tearDown(self)
def setUp(self): self._registration_handler = mock() self._wakeup_handler = mock() self._wakeup_handler._tornado_facade = mock() AsyncHTTPTestCase.setUp(self)
def setUp(self): AsyncHTTPTestCase.setUp(self) self.db = mock.Mock() self.callback = mock.Mock() self.listdata = wordlist.WordListData('', self.db)
def setUp(self): AsyncHTTPTestCase.setUp(self)
def fetch(self, path, **kwargs): response = AsyncHTTPTestCase.fetch(self, path, **kwargs) if response.body is not None: response.value = response.body.decode('utf-8') return response
def tearDown(self): AsyncHTTPTestCase.tearDown(self) cleanup_mock_web_api_server(self) restore_os_env(self.old_os_env)
def setUp(self): AsyncHTTPTestCase.setUp(self) self.db = mock.Mock() self.callback = mock.Mock() self.accountdata = account.AccountData('', self.db)
def setUp(self): AsyncHTTPTestCase.setUp(self) dbc = bkmfc.db.get_conn('bkmfc') dbc.execute("TRUNCATE user")
def setUp(self): AsyncHTTPTestCase.setUp(self) # Wait for the app to start up properly (for good luck). time.sleep(0.5)
def setUp(self): AsyncHTTPTestCase.setUp(self) dbc = hqlh.db.get_conn('fitter') dbc.execute("TRUNCATE user")
def __init__(self, *args, **kwargs): TestCase.__init__(self, *args, **kwargs) AsyncHTTPTestCase.__init__(self, *args, **kwargs)
def __init__(self, *args, **kwargs): AsyncHTTPTestCase.__init__(self, *args, **kwargs) self.maxDiff=None
def tearDown(self): AsyncHTTPTestCase.tearDown(self) controller.shutdown()
def setUp(self): BaseTestCase.setUp(self) AsyncHTTPTestCase.setUp(self) # this must be imported after the above setup in order for the stubs to work self.controller_base = controller_base
def setup_async_test_case(self): AsyncHTTPTestCase.setUp(self)
def setUp(self): AsyncHTTPTestCase.setUp(self) Novel.objects.all().delete() Chapter.objects.all().delete()
def setUp(self): AsyncHTTPTestCase.setUp(self) reload(controller) controller.initialize(recreate=True)
def __init__(self, *args, **kwargs): AsyncHTTPTestCase.__init__(self, *args, **kwargs) self.maxDiff = None self._app = None
async def test_provision_host(self, m_get, m_del, m_put, m_post): """ convert a discovered host to a 'real' host """ self._test_dn = GosaTestCase.create_test_data() container = ObjectProxy(self._test_dn, "IncomingDeviceContainer") container.commit() mocked_foreman = MockForeman() m_get.side_effect = mocked_foreman.get m_del.side_effect = mocked_foreman.delete m_put.side_effect = mocked_foreman.put m_post.side_effect = mocked_foreman.post # create the discovered host + foremanHostgroup d_host = ObjectProxy(container.dn, "Device") d_host.cn = "mac00262df16a2c" d_host.extend("ForemanHost") d_host.status = "discovered" d_host.extend("ieee802Device") d_host.macAddress = "00:26:2d:f1:6a:2c" d_host.extend("IpHost") d_host.ipHostNumber = "192.168.0.1" d_host.commit() hostgroup = ObjectProxy("%s" % self._test_dn, "GroupOfNames") hostgroup.extend("ForemanHostGroup") hostgroup.cn = "Test" hostgroup.foremanGroupId = "4" hostgroup.commit() # add host to group logging.getLogger("test.foreman-integration").info("########### START: Add Host to group ############# %s" % AsyncHTTPTestCase.get_url(self, "/hooks/")) d_host = ObjectProxy("cn=mac00262df16a2c,%s" % container.dn) def check(): logging.getLogger("test.foreman-integration").info("check condition: %s, %s" % (d_host.cn, d_host.status)) return d_host.cn == "mac00262df16a2c" and d_host.status == "discovered" def check2(): logging.getLogger("test.foreman-integration").info("check2 condition: %s" % d_host.cn) return d_host.cn == "Testhost" base_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "data") with open(os.path.join(base_dir, "discovered_hosts", "mac00262df16a2c.json")) as f: mocked_foreman.register_conditional_response("http://localhost:8000/api/v2/discovered_hosts/mac00262df16a2c", "get", check, f.read()) with open(os.path.join(base_dir, "conditional", "Testhost.json")) as f: mocked_foreman.register_conditional_response("http://localhost:8000/api/v2/hosts/Testhost", "get", check2, f.read()) def activate(**kwargs): return True mocked_foreman.register_trigger("http://localhost:8000/api/v2/discovered_hosts/mac00262df16a2c", "put", activate, self.execute) with make_session() as session: assert session.query(ObjectInfoIndex.dn)\ .join(ObjectInfoIndex.properties)\ .filter(and_(KeyValueIndex.key == "cn", KeyValueIndex.value == "Testhost"))\ .count() == 0 d_host.cn = "Testhost" d_host.groupMembership = hostgroup.dn d_host.commit() logging.getLogger("test.foreman-integration").info("waiting for 2 seconds") await asyncio.sleep(2) logging.getLogger("test.foreman-integration").info("########### END: Add Host to group #############") # now move the host to the final destination d_host = ObjectProxy("cn=Testhost,ou=incoming,%s" % self._test_dn) assert d_host.status != "discovered" assert d_host.name == "Testhost" assert d_host.hostgroup_id == "4" assert d_host.is_extended_by("RegisteredDevice") is True assert len(d_host.userPassword[0]) > 0 assert d_host.deviceUUID is not None with make_session() as session: assert session.query(ObjectInfoIndex.dn) \ .join(ObjectInfoIndex.properties) \ .filter(and_(KeyValueIndex.key == "cn", KeyValueIndex.value == "Testhost")) \ .count() == 1 logging.getLogger("test.foreman-integration").info("########### START: moving host #############") d_host.move("%s" % self._test_dn) logging.getLogger("test.foreman-integration").info("########### END: moving host #############") # lets check if everything is fine in the database d_host = ObjectProxy("cn=Testhost,ou=devices,%s" % self._test_dn, read_only=True) assert d_host is not None assert d_host.status == "unknown" assert d_host.groupMembership == hostgroup.dn
def setUp(self): """Setup test""" self.root = tempfile.mkdtemp() self.pubsub = websocket.DirWatchPubSub(self.root) AsyncHTTPTestCase.setUp(self)
def setUp(self): AsyncHTTPTestCase.setUp(self) TempDbMixin.setUp(self)
def setUp(self): AsyncHTTPTestCase.setUp(self) self.old_os_env = remove_os_env_temporarily()
def setUp(self): config.DB_NAME = "weather_test" AsyncHTTPTestCase.setUp(self)
def setUp(self): self.db = tempfile.NamedTemporaryFile(delete=False) self.home = tempfile.mkdtemp() self.scanningdir = tempfile.mkdtemp() AsyncHTTPTestCase.setUp(self)
def setUp(self): AsyncHTTPTestCase.setUp(self) self.app = webtest.TestApp(WSGIAdapter(self.get_app()), cookiejar=CookieJar())
def tearDown(self): TempDbMixin.tearDown(self) AsyncHTTPTestCase.tearDown(self)
def tearDown(self): AsyncHTTPTestCase.tearDown(self) if self.root and os.path.isdir(self.root): shutil.rmtree(self.root)
def tearDown(self): AsyncHTTPTestCase.tearDown(self) restore_os_env(self.old_os_env)
def tearDown(self): TestCase.tearDown(self) AsyncHTTPTestCase.tearDown(self)
def tearDown(self): AsyncHTTPTestCase.tearDown(self)
def setUp(self): AsyncTestCase.setUp(self) AsyncHTTPTestCase.setUp(self) # Wait for the app to start up properly (for good luck). time.sleep(0.5)
def get_url(self, path): path = BiothingsWebTest.get_url(self, path) return AsyncHTTPTestCase.get_url(self, path)