def test_multipart_encoding_in_body(self): from coreapi.utils import File client = CoreAPIClient() schema = client.get('http://api.example.com/') example = { 'foo': File(name='example.txt', content='123'), 'bar': 'abc' } data = client.action(schema, ['encoding', 'multipart-body'], params={'example': example}) expected = { 'method': 'POST', 'content_type': 'multipart/form-data', 'query_params': {}, 'data': { 'bar': 'abc' }, 'files': { 'foo': { 'name': 'example.txt', 'content': '123' } } } assert data == expected
def test_query_params(self): client = CoreAPIClient() schema = client.get('http://api.example.com/') data = client.action(schema, ['location', 'query'], params={'example': 123}) expected = {'method': 'GET', 'query_params': {'example': '123'}} assert data == expected
def test_multipart_encoding(self): client = CoreAPIClient() schema = client.get('http://api.example.com/') with tempfile.NamedTemporaryFile() as temp: temp.write(b'example file content') temp.flush() temp.seek(0) name = os.path.basename(temp.name) data = client.action(schema, ['encoding', 'multipart'], params={'example': temp}) expected = { 'method': 'POST', 'content_type': 'multipart/form-data', 'query_params': {}, 'data': {}, 'files': { 'example': { 'name': name, 'content': 'example file content' } } } assert data == expected
def test_download_response(self): client = CoreAPIClient() schema = client.get('http://api.example.com/') data = client.action(schema, ['response', 'download']) assert data.basename == 'download.png' assert data.read() == b'some file content'
def test_text_response(self): client = CoreAPIClient() schema = client.get('http://api.example.com/') data = client.action(schema, ['response', 'text']) expected = '123' assert data == expected
def test_query_params_with_multiple_values(self): client = CoreAPIClient() schema = client.get('http://api.example.com/') data = client.action(schema, ['location', 'query'], params={'example': [1, 2, 3]}) expected = { 'method': 'GET', 'query_params': {'example': ['1', '2', '3']} } assert data == expected
def test_query_params(self): client = CoreAPIClient() schema = client.get('http://api.example.com/') data = client.action(schema, ['location', 'query'], params={'example': 123}) expected = { 'method': 'GET', 'query_params': {'example': '123'} } assert data == expected
def test_api_client(self): client = CoreAPIClient() schema = client.get('http://api.example.com/') assert schema.title == 'Example API' assert schema.url == 'https://api.example.com/' assert schema['simple_link'].description == 'example link' assert schema['location']['query'].fields[ 0].schema.description == 'example field' data = client.action(schema, ['simple_link']) expected = {'method': 'GET', 'query_params': {}} assert data == expected
def test_urlencoded_encoding_in_body(self): client = CoreAPIClient() schema = client.get('http://api.example.com/') data = client.action(schema, ['encoding', 'urlencoded-body'], params={'example': {'foo': 123, 'bar': True}}) expected = { 'method': 'POST', 'content_type': 'application/x-www-form-urlencoded', 'query_params': {}, 'data': {'foo': '123', 'bar': 'true'}, 'files': {} } assert data == expected
def test_urlencoded_encoding_multiple_values(self): client = CoreAPIClient() schema = client.get('http://api.example.com/') data = client.action(schema, ['encoding', 'urlencoded'], params={'example': [1, 2, 3]}) expected = { 'method': 'POST', 'content_type': 'application/x-www-form-urlencoded', 'query_params': {}, 'data': {'example': ['1', '2', '3']}, 'files': {} } assert data == expected
def test_body_params(self): client = CoreAPIClient() schema = client.get('http://api.example.com/') data = client.action(schema, ['location', 'body'], params={'example': 123}) expected = { 'method': 'POST', 'content_type': 'application/json', 'query_params': {}, 'data': 123, 'files': {} } assert data == expected
def test_api_client(self): client = CoreAPIClient() schema = client.get('http://api.example.com/') assert schema.title == 'Example API' assert schema.url == 'https://api.example.com/' assert schema['simple_link'].description == 'example link' assert schema['location']['query'].fields[0].schema.description == 'example field' data = client.action(schema, ['simple_link']) expected = { 'method': 'GET', 'query_params': {} } assert data == expected
def test_coreapi(self): client = CoreAPIClient() client.session.auth = HTTPBasicAuth(self.user.data['username'], self.user.data['password']) client.session.headers.update({'x-test': 'true'}) schema = client.get('http://testserver/api/v1/schema/') result = client.action(schema, ['user', 'list']) self.assertEqual(result['count'], 1) create_data = dict(username='******', password='******', password2='123') result = client.action(schema, ['user', 'add'], create_data) self.assertEqual(result['username'], create_data['username']) self.assertFalse(result['is_staff']) self.assertTrue(result['is_active'])
def test_raw_upload_explicit_content_type(self): from coreapi.utils import File client = CoreAPIClient() schema = client.get('http://api.example.com/') example = File('example.txt', '123', 'text/html') data = client.action(schema, ['encoding', 'raw_upload'], params={'example': example}) expected = { 'method': 'POST', 'files': {'file': {'name': 'example.txt', 'content': '123'}}, 'content_type': 'text/html' } assert data == expected
def test_multipart_encoding_no_file(self): # When no file is included, multipart encoding should still be used. client = CoreAPIClient() schema = client.get('http://api.example.com/') data = client.action(schema, ['encoding', 'multipart'], params={'example': 123}) expected = { 'method': 'POST', 'content_type': 'multipart/form-data', 'query_params': {}, 'data': {'example': '123'}, 'files': {} } assert data == expected
def setUp(self): # create one dummy teacher self.teacher = Teacher.objects.create( user = User.objects.create_user( username = "******", email = "*****@*****.**" ) ) # create one dummy student self.student = Student.objects.create( user = User.objects.create_user( username = "******", email = "*****@*****.**" ) ) # create courses self.courses = [ Course.objects.create( name = "Croozers Logic Course", teacher_id = self.teacher.user.id, description = "Keep Kroozin!", deadline = datetime.datetime.now(), student_count = 5, price = 0 ), Course.objects.create( name = "Mathematik", teacher_id = self.teacher.user.id, description = "Mein Mathe", deadline = datetime.datetime.now(), student_count = 5, price = 20 ) ] # assign student to course self.student.courses.add(self.courses[0]) # create tokens for each user self.student_token = createToken(self.student.user) self.teacher_token = createToken(self.teacher.user) self.student_client = CoreAPIClient() self.student_client.session.headers.update({"Authentication": "JWT " + self.student_token})
def test_multipart_encoding_in_body(self): from coreapi.utils import File client = CoreAPIClient() schema = client.get('http://api.example.com/') example = {'foo': File(name='example.txt', content='123'), 'bar': 'abc'} data = client.action(schema, ['encoding', 'multipart-body'], params={'example': example}) expected = { 'method': 'POST', 'content_type': 'multipart/form-data', 'query_params': {}, 'data': {'bar': 'abc'}, 'files': {'foo': {'name': 'example.txt', 'content': '123'}} } assert data == expected
def test_raw_upload(self): client = CoreAPIClient() schema = client.get('http://api.example.com/') with tempfile.NamedTemporaryFile(delete=False) as temp: temp.write(b'example file content') temp.flush() temp.seek(0) name = os.path.basename(temp.name) data = client.action(schema, ['encoding', 'raw_upload'], params={'example': temp}) expected = { 'method': 'POST', 'files': {'file': {'name': name, 'content': 'example file content'}}, 'content_type': 'application/octet-stream' } assert data == expected
def test_multipart_encoding_string_file_content(self): # Test for `coreapi.utils.File` support. from coreapi.utils import File client = CoreAPIClient() schema = client.get('http://api.example.com/') example = File(name='example.txt', content='123') data = client.action(schema, ['encoding', 'multipart'], params={'example': example}) expected = { 'method': 'POST', 'content_type': 'multipart/form-data', 'query_params': {}, 'data': {}, 'files': {'example': {'name': 'example.txt', 'content': '123'}} } assert data == expected
class CourseTests(APITestCase): def setUp(self): # create one dummy teacher self.teacher = Teacher.objects.create( user = User.objects.create_user( username = "******", email = "*****@*****.**" ) ) # create one dummy student self.student = Student.objects.create( user = User.objects.create_user( username = "******", email = "*****@*****.**" ) ) # create courses self.courses = [ Course.objects.create( name = "Croozers Logic Course", teacher_id = self.teacher.user.id, description = "Keep Kroozin!", deadline = datetime.datetime.now(), student_count = 5, price = 0 ), Course.objects.create( name = "Mathematik", teacher_id = self.teacher.user.id, description = "Mein Mathe", deadline = datetime.datetime.now(), student_count = 5, price = 20 ) ] # assign student to course self.student.courses.add(self.courses[0]) # create tokens for each user self.student_token = createToken(self.student.user) self.teacher_token = createToken(self.teacher.user) self.student_client = CoreAPIClient() self.student_client.session.headers.update({"Authentication": "JWT " + self.student_token}) def test_get_student_courses(self): url = reverse("course-list") response = self.student_client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK, url) print(response.data) self.assertEqual(response.data, {"id": 5})
def test_multipart_encoding(self): client = CoreAPIClient() schema = client.get('http://api.example.com/') with tempfile.NamedTemporaryFile() as temp: temp.write(b'example file content') temp.flush() temp.seek(0) name = os.path.basename(temp.name) data = client.action(schema, ['encoding', 'multipart'], params={'example': temp}) expected = { 'method': 'POST', 'content_type': 'multipart/form-data', 'query_params': {}, 'data': {}, 'files': {'example': {'name': name, 'content': 'example file content'}} } assert data == expected
class ParametroNodoMenuAPITest(APITestCase): LOCAL_HOST = '' #"http://127.0.0.11:8000" staging_server = "" setup_done = False base_url = reverse('nodo_menu_list') client = CoreAPIClient() #base_url = '/api/parametros/nodo_menu/' #reverse('menu-list') def setUp(self): #import ipdb;ipdb.set_trace() if self.setup_done: return self.utilt = UtileriasParametroTest() #self.client = APIClient() self.menu = MenuFactory() #Menu.objects.create(nombre="Menu1") get_next_value('nodosMenu', initial_value=0) #self.staging_server = os.environ.get('STAGING_SERVER') #if not self.staging_server: # self.staging_server = self.LOCAL_HOST self.base_url = f'{self.staging_server}{self.base_url}' def test_ruta(self): ruta = '/api/parametros/nodo_menu/' self.assertEqual(self.base_url,f'{self.staging_server}{ruta}') #response = self.client.get(self.base_url) #self.assertEqual(200, response.status_code) def test_POSTing_nuevos_nodomenu(self): data = {'id': '0',' menu': 1, 'nodo_padre': None, 'etiqueta':'Nodo Menu1','orden': 0} response = self.client.post(self.base_url, data) self.assertEqual(response.status_code, 201) menu_guardado = NodoMenu.objects.get(id= 1) self.assertEqual(menu_guardado.etiqueta, "Nodo Menu1") def test_POSTing_nuevos_nodomenu_con_id_consecutivo(self): data1 = {'id': '0',' menu': 1, 'nodo_padre': None, 'etiqueta':'Nodo Menu1','orden': 0} response1 = self.client.post(self.base_url, data1) self.assertEqual(response1.status_code, 201) menu_guardado = NodoMenu.objects.get(id= 1) self.assertEqual(menu_guardado.etiqueta, "Nodo Menu1") data2 = {'id': '0',' menu': 1, 'nodo_padre': None, 'etiqueta':'Nodo Menu1','orden': 0, 'etiqueta': 'Nodo Menu2'} response2 = self.client.post(self.base_url, data2) self.assertEqual(response2.status_code, 201) menu_guardado = NodoMenu.objects.get(id= 2) self.assertEqual(menu_guardado.etiqueta, "Nodo Menu2") def test_POSTing_nuevos_nodomenu_con_padre_que_no_exite(self): data = {'id': '0',' menu': 1, 'nodo_padre': 1, 'etiqueta':'Nodo Menu1','orden': 0} response = self.client.post(self.base_url, data) self.assertEqual(response.status_code, 400) self.assertEqual(response.data,'El nodo padre con el id 1 no existe') def test_POSTing_nodomenu_con_etiqueta_mayor_a_su_longitud_permitida(self): etiqueta ='a' * 100 data = {'id': '0',' menu': 1, 'nodo_padre': None, 'etiqueta':etiqueta,'orden': 0} response = self.client.post(self.base_url, data) self.assertEqual(response.status_code, 400) self.assertEqual( response.data['etiqueta'][0][0:] ,'La longitud ' 'maxima es de 60 caracteres (tiene 100)') def test_PUT_modificar_nodomenu(self): data = {'id': '0',' menu': 1, 'nodo_padre': None, 'etiqueta':'Etiqueta','orden': 0} response = self.client.post(self.base_url, data) self.assertEqual(response.data['id'],1) pk = response.data['id'] base_url_update = reverse('nodo_menu_update', kwargs={'pk': pk}) data_update = {'etiqueta': 'Etiqueta modificada'} response_update = self.client.put(base_url_update, data_update) self.assertEqual(response_update.status_code, 200) self.assertEqual( response_update.data['etiqueta'] ,'Etiqueta modificada') def test_PUT_modificar_etiqueta_mayor_a_su_longitud_permitida(self): data = {'id': '0',' menu': 1, 'nodo_padre': None, 'etiqueta':'Etiqueta','orden': 0} response = self.client.post(self.base_url, data) self.assertEqual(response.data['id'],1) pk = response.data['id'] etiqueta ='a' * 100 base_url_update = reverse('nodo_menu_update', kwargs={'pk': pk}) data_update = {'etiqueta': etiqueta} response_update = self.client.put(base_url_update, data_update) self.assertEqual(response_update.status_code, 400) self.assertEqual( response_update.data['etiqueta'][0][0:] ,'La longitud maxima es de 60 caracteres (tiene 100)') def test_PUT_mover_orden_del_nodo(self): nodo_padre1 = NodoMenuFactoryUtils.crear_nodo_menu(id=None, nodo_padre=None, menu=self.menu) NodoMenuFactoryUtils.crear_multiples_nodos_menu(5, self.menu, nodo_padre1) cantidad_nodos = NodoMenu.objects.get_cantidad_nodos_hijos(nodo_padre1.id) nodos_hijo = NodoMenu.objects.get_nodos_hijos(nodo_padre1.id) self.utilt.comparar_orden(nodo_padre1, [2, 3, 4, 5, 6]) base_url_orden = reverse('nodo_menu_orden', kwargs={'pk': 6, 'orden':1}) response_update = self.client.put(base_url_orden) self.assertEqual(response_update.status_code, 200) self.utilt.comparar_orden(nodo_padre1, [6, 2, 3, 4, 5]) def test_PUT_mover_orden_de_nodo_raiz(self): nodo_padre1 = NodoMenuFactoryUtils.crear_nodo_menu(id=None, nodo_padre=None, menu=self.menu) nodo_padre2 = NodoMenuFactoryUtils.crear_nodo_menu(id=None, nodo_padre=None, menu=self.menu) nodo_padre3 = NodoMenuFactoryUtils.crear_nodo_menu(id=None, nodo_padre=None, menu=self.menu) self.utilt.comparar_orden(None, [1, 2, 3]) base_url_orden = reverse('nodo_menu_orden', kwargs={'pk': 3, 'orden':1}) response_update = self.client.put(base_url_orden) self.assertEqual(response_update.status_code, 200) self.utilt.comparar_orden(None, [3, 1, 2]) def test_PUT_mover_orden_que_no_existe(self): nodo_padre1 = NodoMenuFactoryUtils.crear_nodo_menu(id=None, nodo_padre=None, menu=self.menu) NodoMenuFactoryUtils.crear_multiples_nodos_menu(2,self.menu, nodo_padre1) cantidad_nodos = NodoMenu.objects.get_cantidad_nodos_hijos(nodo_padre1.id) base_url_orden = reverse('nodo_menu_orden', kwargs={'pk': 2, 'orden':3}) response_update = self.client.put(base_url_orden) self.assertEqual(response_update.status_code, 400) self.assertEqual(response_update.data,'No se puede mover a un orden ' 'mayor al numero de elementos') def test_PUT_cambiar_nodo_de_padre_de_menu_diferente(self): menu2 = MenuFactory() nodo_padre1 = NodoMenuFactoryUtils.crear_nodo_menu(id=None, nodo_padre=None, menu=menu2) nodo_padre2 = NodoMenuFactoryUtils.crear_nodo_menu(id=None, nodo_padre=None, menu=self.menu) self.assertEquals(nodo_padre1.id,1) self.assertEquals(nodo_padre2.id,2) base_url_orden = reverse('nodo_menu_padre', kwargs={'pk': 2, 'padre_id':1}) response_update = self.client.put(base_url_orden) self.assertEqual(response_update.status_code, 400) self.assertEqual(response_update.data,'No se puede mover a un ' 'padre con menu diferente') def test_PUT_cambiar_nodo_de_padre(self): nodo_padre1 = NodoMenuFactoryUtils.crear_nodo_menu(id=None, nodo_padre=None, menu=self.menu) nodo_padre2 = NodoMenuFactoryUtils.crear_nodo_menu(id=None, nodo_padre=None, menu=self.menu) NodoMenuFactoryUtils.crear_multiples_nodos_menu(3,self.menu, nodo_padre1) NodoMenuFactoryUtils.crear_multiples_nodos_menu(4,self.menu, nodo_padre2) nodos_hijo1 = NodoMenu.objects.get_nodos_hijos(nodo_padre1.id) nodos_hijo2 = NodoMenu.objects.get_nodos_hijos(nodo_padre2.id) self.assertEquals(nodos_hijo1.count(),3) self.assertEquals(nodos_hijo2.count(),4) self.assertEqual(nodos_hijo2[1].id,7) base_url_orden = reverse('nodo_menu_padre', kwargs={'pk': 7, 'padre_id':1}) response_update = self.client.put(base_url_orden) self.assertEqual(response_update.status_code, 200) self.assertEqual(response_update.data['id'],7) self.assertEqual(response_update.data['nodo_padre'],1) def test_DELETE_nodo(self): nodo_padre1 = NodoMenuFactoryUtils.crear_nodo_menu(id=None, nodo_padre=None, menu=self.menu) NodoMenuFactoryUtils.crear_multiples_nodos_menu(5,self.menu, nodo_padre1) nodos_hijo1 = NodoMenu.objects.get_nodos_hijos(nodo_padre1.id) self.utilt.comparar_orden(nodo_padre1, [2, 3, 4, 5, 6]) base_url_update = reverse('nodo_menu_update', kwargs={'pk': 4}) response_delete = self.client.delete(base_url_update) self.assertEqual(response_delete.status_code, 200) self.assertEquals(response_delete.data,1) nodos_hijo1 = NodoMenu.objects.get_nodos_hijos(nodo_padre1.id) self.utilt.comparar_orden(nodo_padre1, [2, 3, 5, 6]) def test_GET_arbol_menu(self): NodoMenuFactoryUtils.crear_nodo_con_hijos(self.menu,'India',['AP','MP','KAR']) NodoMenuFactoryUtils.crear_nodo_con_hijos(self.menu,'UK',[]) NodoMenuFactoryUtils.crear_nodo_con_hijos(self.menu,'Mexico',['Guadalajara','Sinaloa']) NodoMenuFactoryUtils.crear_nodo_con_hijos(self.menu,'KAR',['BAGDAG','MALGA']) NodoMenu.objects.cambiarOrden(6,1) #Ponemos a Mexico al Inicio del orden id_menu = 1 base_url_arbol = reverse('nodo_arbol_menu', kwargs={'id_menu': id_menu}) response = self.client.get(base_url_arbol, format='json') nodo_menu = json.loads(response.data) self.assertEqual(response['content-type'], 'application/json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(nodo_menu),3) self.assertEqual(nodo_menu[0]['etiqueta'],'Mexico') self.assertEqual(len(nodo_menu[0]['sub_menu']),2) self.assertEqual(nodo_menu[1]['etiqueta'],'India') self.assertEqual(len(nodo_menu[1]['sub_menu']),3) self.assertEqual(len(nodo_menu[1]['sub_menu'][2]['sub_menu']),2) self.assertEqual(nodo_menu[2]['etiqueta'],'UK') self.assertEqual(len(nodo_menu[2]['sub_menu']),0) id_menu = 3 base_url_arbol = reverse('nodo_arbol_menu', kwargs={'id_menu': id_menu}) response = self.client.get(base_url_arbol, format='json') self.assertEquals(response.data,'[]') def test_probandoError(self): self.assertEqual(3,3)
def setUp(self): """setUp""" self.training_data = {} self.pre_proc = {} self.post_proc = {} self.meta_data = {} self.test_username = "******" self.test_password = "******" self.test_user = User.objects.create_user(self.test_username, "*****@*****.**", self.test_password) self.test_ml_job = MLJob(user=self.test_user, title="MLJob test", desc="ML Job Desc", ds_name="test dataset", algo_name="test algo", ml_type="classification", status="initial", control_state="active", predict_feature="label_value", training_data=self.training_data, pre_proc=self.pre_proc, post_proc=self.post_proc, meta_data=self.meta_data, tracking_id="job test", version=1) self.predict_manifest = { "job_id": self.test_ml_job.id, "result_id": None, "ml_type": "classification", "test_size": 0.2, "epochs": 1, "batch_size": 1, "num_splits": 1, "loss": "binary_crossentropy", "metrics": ["accuracy"], "optimizer": "adam", "histories": ["val_loss", "val_acc", "loss", "acc"], "seed": 9, "training_data": {}, "csv_file": ("drf_network_pipeline/tests/datasets/" "cleaned_attack_scans.csv"), "meta_file": ("drf_network_pipeline/tests/datasets/" "cleaned_metadata.json"), "predict_feature": "label_value", "features_to_process": [ "eth_type", "idx", "ip_ihl", "ip_len", "ip_tos", "ip_version", "label_value", "tcp_dport", "tcp_fields_options", "MSS", "tcp_fields_options", "Timestamp", "tcp_fields_options", "WScale", "tcp_seq", "tcp_sport" ], "ignore_features": None, "label_rules": None, "post_proc_rules": None, "model_weights_file": None, "verbose": 1, "version": 1 } self.test_ml_job.predict_manifest = self.predict_manifest self.client = CoreAPIClient() # URL for creating an account. self.factory = APIRequestFactory() self.auth_url = "/api-token-auth/" self.token = None self.ml_run_url = "/ml/" self.ml_get_url = "/ml/" self.ml_get_result_url = "/mlresults/" self.ml_prep_url = "/ml_prepare/" self.jwt_auth = None """ make sure to clone the dataset repo locally to test with them: git clone https://github.com/jay-johnson/antinex-datasets.git \ /opt/antinex-datasets export TEST_ANTINEX=1 By default the tests use the included, slim dataset versions """ self.use_antinex = bool(os.getenv("TEST_ANTINEX", "0") == "1") self.antinex_path = ("/opt/antinex-datasets/v1/webapps/" "django/training-ready") # disable worker publishing hook for tests settings.ANTINEX_WORKER_ENABLED = False
def test_session_headers(self): client = CoreAPIClient() client.session.headers.update({'X-Custom-Header': 'foo'}) schema = client.get('http://api.example.com/') data = client.action(schema, ['headers']) assert data['headers']['X-CUSTOM-HEADER'] == 'foo'