def api_client(sample_port1, sample_port2, sample_room1): from ..context import app with app.app.test_client() as c: db.init_db(db_settings, testing=True) prep_db(db.get_db().get_session(), sample_port1, sample_port2, sample_room1) yield c
def test_member_post_add_membership_ok(api_client): body = { "duration": 360, "start": "2000-01-23T04:56:07.000+00:00", "paymentMethod": "card", } result = api_client.post( '{}/member/{}/membership/'.format(base_url, "dubois_j"), data=json.dumps(body), content_type='application/json', headers=TEST_HEADERS, ) assert result.status_code == 200 assert_modification_was_created(db.get_db().get_session()) s = db.get_db().get_session() q = s.query(Adherent) q = q.filter(Adherent.login == "dubois_j") assert q.one().date_de_depart == datetime.date(2001, 1, 17) e: Ecriture = s.query(Ecriture).one() assert 'dubois_j' == e.adherent.login assert 1 == e.compte_id assert 'Internet - 1 an' == e.intitule assert 1 == e.utilisateur_id assert 'card' == e.moyen
def test_device_put_create_wired_without_ip(api_client, wired_device_dict): """ Can create a valid wired device? Create two devices and check the IP """ del wired_device_dict['ipAddress'] del wired_device_dict['ipv6Address'] r = api_client.put('{}/device/{}'.format(base_url, wired_device_dict['mac']), data=json.dumps(wired_device_dict), content_type='application/json', headers=TEST_HEADERS) assert r.status_code == 201 assert_modification_was_created(db.get_db().get_session()) wired_device_dict["mac"] = "AB-CD-EF-01-23-45" r = api_client.put('{}/device/{}'.format(base_url, wired_device_dict['mac']), data=json.dumps(wired_device_dict), content_type='application/json', headers=TEST_HEADERS) assert r.status_code == 201 assert_modification_was_created(db.get_db().get_session()) s = db.get_db().get_session() q = s.query(Ordinateur) q = q.filter(Ordinateur.mac == wired_device_dict["mac"]) dev = q.one() assert dev.ip == "192.168.42.3" assert dev.ipv6 == 'fe80::3'
def api_client(wired_device, wireless_device, sample_member3): from ..context import app with app.app.test_client() as c: db.init_db(DATABASE, testing=True) prep_db(db.get_db().get_session(), wired_device, wireless_device, sample_member3) yield c
def test_member_delete_existant(api_client): r = api_client.delete('{}/member/{}'.format(base_url, "dubois_j"), headers=TEST_HEADERS) assert r.status_code == 204 assert_modification_was_created(db.get_db().get_session()) s = db.get_db().get_session() q = s.query(Adherent) q = q.filter(Adherent.login == "dubois_j") assert not s.query(q.exists()).scalar()
def api_client(sample_naina, sample_naina_expired): with app.app.test_client() as c: db.init_db(db_settings, testing=True) s = db.get_db().get_session() s.add(sample_naina_expired) s.add(sample_naina) s.commit() yield c
def test_device_delete_wireless(api_client, wireless_device): mac = wireless_device.mac r = api_client.delete( '{}/device/{}'.format(base_url, mac), headers=TEST_HEADERS, ) assert r.status_code == 204 assert_modification_was_created(db.get_db().get_session()) s = db.get_db().get_session() q = s.query(Portable) q = q.filter(Portable.mac == mac) assert not s.query(q.exists()).scalar(), "Object not actually deleted"
def test_device_put_create_wired(api_client, wired_device_dict): ''' Can create a valid wired device ? ''' r = api_client.put('{}/device/{}'.format(base_url, wired_device_dict['mac']), data=json.dumps(wired_device_dict), content_type='application/json', headers=TEST_HEADERS) assert r.status_code == 201 assert_modification_was_created(db.get_db().get_session()) s = db.get_db().get_session() q = s.query(Ordinateur) q = q.filter(Ordinateur.mac == wired_device_dict["mac"]) dev = q.one() assert dev.ip == "127.0.0.1"
def test_member_patch_firstname(api_client): body = { "firstName": "TEST", } res = api_client.patch('{}/member/{}'.format(base_url, "dubois_j"), data=json.dumps(body), content_type='application/json', headers=TEST_HEADERS) assert res.status_code == 204 assert_modification_was_created(db.get_db().get_session()) assert_member_in_db({ "firstName": "TEST", "lastName": "Dubois", "roomNumber": 5110, "comment": None, "departureDate": str(datetime.datetime(2005, 7, 14, 12, 30)), "associationMode": "2011-04-30T17:50:17", "email": "*****@*****.**", "username": "******" })
def api_client(sample_member1, sample_member2, sample_member13, wired_device, wireless_device, sample_room1, sample_room2, sample_vlan): from .context import app with app.app.test_client() as c: db.init_db(DATABASE, testing=True) prep_db(db.get_db().get_session(), sample_member1, sample_member2, sample_member13, wired_device, wireless_device, sample_room1, sample_room2, sample_vlan) yield c
def assert_switch_in_db(body): s = db.get_db().get_session() q = s.query(Switch) q = q.filter(Switch.ip == body["ip"]) sw = q.one() assert sw.ip == body["ip"] assert sw.communaute == body["community"] assert sw.description == body["description"]
def assert_port_in_db(body): s = db.get_db().get_session() q = s.query(Port) q = q.filter(Port.numero == body["portNumber"]) p = q.one() assert body["portNumber"] == p.numero assert body["roomNumber"] == p.chambre.numero assert body["switchID"] == p.switch.id
def assert_room_in_db(body): s = db.get_db().get_session() q = s.query(Chambre) q = q.filter(body["roomNumber"] == Chambre.numero) c = q.one() assert body["vlan"] == c.vlan.numero assert str(body["phone"]) == c.telephone assert body["description"] == c.description
def test_device_put_update_wired(api_client, wired_device, wired_device_dict): ''' Can update a valid wired device ? ''' r = api_client.put( '{}/device/{}'.format(base_url, wired_device.mac), data=json.dumps(wired_device_dict), content_type='application/json', headers=TEST_HEADERS) assert r.status_code == 204 assert_modification_was_created(db.get_db().get_session())
def test_switch_delete_existant_switch(api_client): r = api_client.delete("{}/switch/{}".format(base_url, 1), headers=TEST_HEADERS) assert r.status_code == 204 s = db.get_db().get_session() q = s.query(Switch) q = q.filter(Switch.id == 1) assert not s.query(q.exists()).scalar()
def test_device_put_create_wireless(api_client, wireless_device_dict): """ Can create a valid wireless device ? """ addr = '{}/device/{}'.format(base_url, wireless_device_dict['mac']) r = api_client.put(addr, data=json.dumps(wireless_device_dict), content_type='application/json', headers=TEST_HEADERS) assert r.status_code == 201 assert_modification_was_created(db.get_db().get_session())
def assert_transaction_in_db(body): s = db.get_db().get_session() q = s.query(Transaction) q = q.filter(Transaction.name == body["name"]) sw = q.one() assert sw.name == body["name"] assert sw.src == body["srcID"] assert sw.dst == body["dstID"] assert sw.value == body["value"]
def test_member_change_password_ok(api_client): USERNAME = "******" body = { "password": "******"#NyL#+k:_xEdJrEDT7", } result = api_client.put( '{}/member/{}/password/'.format(base_url, USERNAME), data=json.dumps(body), content_type='application/json', headers=TEST_HEADERS, ) assert result.status_code == 204 assert_modification_was_created(db.get_db().get_session()) s = db.get_db().get_session() q = s.query(Adherent) q = q.filter(Adherent.login == USERNAME) r = q.one() assert r.password == ntlm_hash(body["password"])
def test_room_delete_existant_room(api_client): r = api_client.delete( "{}/room/{}".format(base_url, 5110), headers=TEST_HEADERS, ) assert r.status_code == 204 s = db.get_db().get_session() q = s.query(Chambre) q = q.filter(Chambre.numero == 5110) assert q.count() == 0
def test_port_delete_port(api_client, sample_switch1, sample_port1): r = api_client.delete( "{}/port/{}".format(base_url, sample_port1.id), headers=TEST_HEADERS, ) assert r.status_code == 204 s = db.get_db().get_session() q = s.query(Port) q = q.filter(Port.id == sample_port1.id) assert not s.query(q.exists()).scalar()
def assert_member_in_db(body): # Actually check that the object was inserted s = db.get_db().get_session() q = s.query(Adherent) q = q.filter(Adherent.login == body["username"]) r = q.one() assert r.nom == body["lastName"] assert r.prenom == body["firstName"] assert r.mail == body["email"] assert r.date_de_depart == parser.parse(body["departureDate"]).date() asso_time = parser.parse(body["associationMode"]).replace(tzinfo=None) assert r.mode_association == asso_time assert r.chambre.numero == body["roomNumber"] assert r.commentaires == body["comment"] assert r.login == body["username"]
def wrapper(cls, ctx, *args, **kwds): """ Wrap http_api function. """ # TODO: Remove dep from SQLAlchemy? if ctx.get(CTX_SQL_SESSION): return f(cls, ctx, *args, **kwds) s = Db.get_db().get_session() ctx = build_context(session=s, ctx=ctx) try: result = f(cls, ctx, *args, **kwds) # It makes things clearer and less error-prone. assert isinstance( result, tuple), "Please always pass the result AND the HTTP code." assert len( result) > 1, "Please always pass the result AND the HTTP code." status_code = result[1] msg = result[0] if result[0] == NoContent: msg = None if status_code and 200 <= status_code <= 299: s.commit() else: LOG.info("rollback_sql_transaction_non_200_http_code", extra=log_extra(ctx, code=status_code, message=msg)) s.rollback() return result except Exception as e: LOG.error("rollback_sql_transaction_exception_caught", extra=log_extra(ctx, exception=str(e), traceback=traceback.format_exc())) s.rollback() raise finally: # When running unit tests, we don't close the session so tests can actually perform some work on that # session. if not ctx.get(CTX_TESTING): s.close()
def test_member_put_member_update(api_client): body = { "firstName": "Jean-Louis", "lastName": "Dubois", "roomNumber": 4592, "comment": "comment", "departureDate": "2000-01-23T04:56:07.000+00:00", "associationMode": "2000-01-23T04:56:07.000+00:00", "email": "*****@*****.**", "username": "******" } res = api_client.put('{}/member/{}'.format(base_url, body["username"]), data=json.dumps(body), content_type='application/json', headers=TEST_HEADERS) assert res.status_code == 204 assert_modification_was_created(db.get_db().get_session()) assert_member_in_db(body)
def authenticate_temp_account(access_token): s = Db.get_db().get_session() q = s.query(NainA) q = q.filter(NainA.access_token == access_token) try: naina = q.one() now = datetime.datetime.now() if naina.expiration_time > now > naina.start_time: # Make sure the token is still valid. return { "uid": f"TEMP_ACCOUNT({naina.id})[{naina.first_name} {naina.last_name}]", "scope": ["profile"], "groups": [ADH6_USER] } else: return None # Expired token. except NoResultFound: return None # No token found. finally: s.close()
def test_device_filter_hit_limit(api_client, sample_member1): s = db.get_db().get_session() LIMIT = 10 # Create a lot of devices for i in range(LIMIT * 2): suffix = "{0:04X}".format(i) dev = Portable( adherent=sample_member1, mac='00-00-00-00-' + suffix[:2] + "-" + suffix[2:] ) s.add(dev) s.commit() r = api_client.get( '{}/device/?limit={}'.format(base_url, LIMIT), headers=TEST_HEADERS, ) assert r.status_code == 200 response = json.loads(r.data.decode('utf-8')) assert len(response) == LIMIT
def init(testing=True): """ Initialize and wire together the dependency of the application. """ if testing: configuration = TEST_CONFIGURATION else: configuration = CONFIGURATION Database.init_db(configuration.DATABASE, testing=testing) # Repositories: ping_repository = PingSQLRepository() member_sql_repository = MemberSQLRepository() network_object_sql_repository = NetworkObjectSQLRepository() device_sql_repository = DeviceSQLRepository() room_sql_repository = RoomSQLRepository() elk_repository = ElasticSearchRepository(configuration) money_repository = MoneySQLRepository() switch_network_manager = SwitchSNMPNetworkManager() account_sql_repository = AccountSQLRepository() product_sql_repository = ProductSQLRepository() payment_method_sql_repository = PaymentMethodSQLRepository() transaction_sql_repository = TransactionSQLRepository() account_type_sql_repository = AccountTypeSQLRepository() # Managers health_manager = HealthManager(ping_repository) switch_manager = SwitchManager( switch_repository=network_object_sql_repository, ) port_manager = PortManager(port_repository=network_object_sql_repository, ) device_manager = DeviceManager( device_repository=device_sql_repository, member_repository=member_sql_repository, room_repository=room_sql_repository, vlan_repository=network_object_sql_repository, ip_allocator=device_sql_repository, ) member_manager = MemberManager( member_repository=member_sql_repository, money_repository=money_repository, membership_repository=member_sql_repository, logs_repository=elk_repository, configuration=configuration, ) room_manager = RoomManager(room_repository=room_sql_repository, ) account_manager = AccountManager( account_repository=account_sql_repository, member_repository=member_sql_repository, ) product_manager = ProductManager( product_repository=product_sql_repository, ) payment_method_manager = PaymentMethodManager( payment_method_repository=payment_method_sql_repository) transaction_manager = TransactionManager( transaction_repository=transaction_sql_repository, ) account_type_manager = AccountTypeManager( account_type_repository=account_type_sql_repository) # HTTP Handlers: health_handler = HealthHandler(health_manager) transaction_handler = TransactionHandler(transaction_manager) member_handler = MemberHandler(member_manager) device_handler = DeviceHandler(device_manager) room_handler = RoomHandler(room_manager) switch_handler = SwitchHandler(switch_manager) port_handler = PortHandler(port_manager, switch_manager, switch_network_manager) temporary_account_handler = TemporaryAccountHandler() account_type_handler = AccountTypeHandler(account_type_manager) payment_method_handler = PaymentMethodHandler(payment_method_manager) account_handler = AccountHandler(account_manager) product_handler = ProductHandler(product_manager) # Connexion will use this function to authenticate and fetch the information of the user. if os.environ.get('TOKENINFO_FUNC') is None: os.environ[ 'TOKENINFO_FUNC'] = 'src.interface_adapter.http_api.auth.token_info' app = connexion.FlaskApp(__name__, specification_dir='openapi') app.add_api( 'swagger.yaml', # resolver=RestyResolver('src.interface_adapter.http_api'), resolver=ADHResolver({ 'health': health_handler, 'transaction': transaction_handler, 'member': member_handler, 'device': device_handler, 'room': room_handler, 'switch': switch_handler, 'port': port_handler, 'temporary_account': temporary_account_handler, 'account_type': account_type_handler, 'payment_method': payment_method_handler, 'account': account_handler, 'product': product_handler, }), validate_responses=True, strict_validation=True, pythonic_params=True, auth_all_paths=True, ) app.app.config.update(configuration.API_CONF) return app
def api_client(sample_transaction): from .context import app with app.app.test_client() as c: db.init_db(db_settings, testing=True) prep_db(db.get_db().get_session(), sample_transaction) yield c