Пример #1
0
def api_client(sample_room1, sample_room2, sample_vlan):
    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_room1, sample_room2, sample_vlan)
        yield c
Пример #2
0
def api_client(member1,
               member2,
               wired_device,
               wireless_device):
    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(),
                member1,
                member2,
                wired_device,
                wireless_device)
        yield c
Пример #3
0
def getUser(admin, username):
    """ [API] Get the specified user from the database """
    s = db.get_db().get_session()
    try:
        return dict(Adherent.find(s, username))
    except UserNotFound:
        return NoContent, 404
Пример #4
0
def test_device_put_update_wired_and_wireless_to_wireless(
        api_client,
        wired_device,
        wireless_device_dict):
    '''
    Test if the controller is able to handle the case where the MAC address is
    in the Wireless table _AND_ the Wired table
    Tests the case where we want to move the mac to the wireless table
    '''
    # Add a wireless device that has the same mac as WIRED_DEVICE
    dev_with_same_mac = Portable(
        mac=wired_device.mac,
        adherent_id=1,
    )
    session = db.get_db().get_session()
    session.add(dev_with_same_mac)
    session.commit()

    # Then try to update it...
    r = api_client.put(
        '{}/device/{}'.format(base_url, wired_device.mac),
        data=json.dumps(wireless_device_dict),
        content_type='application/json',
        headers=TEST_HEADERS)
    assert r.status_code == 204
Пример #5
0
def filterSwitch(admin, limit=100, offset=0, terms=None):
    """ [API] Filter the switch list """
    if limit < 0:
        return "Limit must be positive", 400
    q = db.get_db().get_session().query(Switch)
    # Filter by terms
    if terms:
        q = q.filter(
            or_(
                Switch.description.contains(terms),
                Switch.ip.contains(terms),
                Switch.communaute.contains(terms),
            ))
    count = q.count()
    q = q.order_by(Switch.description.asc())
    q = q.offset(offset)
    q = q.limit(limit)  # Limit the number of matches
    q = q.all()

    # Convert the qs into data suited for the API
    q = map(lambda x: {'switchID': x.id, 'switch': dict(x)}, q)
    result = list(q)  # Cast generator as list

    headers = {
        'access-control-expose-headers': 'X-Total-Count',
        'X-Total-Count': str(count)
    }
    return result, 200, headers
Пример #6
0
 def wrapper(*args, user, token_info, **kwargs):
     if current_app.config["TESTING"] \
        or "adh6_user" in token_info["groups"]:
         s = db.get_db().get_session()
         admin = Utilisateur.find_or_create(s, user)
         return f(admin, *args, **kwargs)
     return NoContent, 401
Пример #7
0
def getSwitch(admin, switchID):
    """ [API] Get the specified switch from the database """
    session = db.get_db().get_session()
    try:
        return dict(Switch.find(session, switchID))
    except SwitchNotFound:
        return NoContent, 404
Пример #8
0
def getRoom(admin, roomNumber):
    """ [API] Get the room specified """
    s = db.get_db().get_session()
    try:
        return dict(Chambre.find(s, roomNumber)), 200
    except RoomNotFound:
        return NoContent, 404
Пример #9
0
def filterUser(admin, limit=100, offset=0, terms=None, roomNumber=None):
    """ [API] Filter the list of users from the the database """
    if limit < 0:
        return "Limit must be positive", 400

    s = db.get_db().get_session()

    q = s.query(Adherent)
    if roomNumber:
        try:
            q2 = s.query(Chambre)
            q2 = q2.filter(Chambre.numero == roomNumber)
            result = q2.one()
        except sqlalchemy.orm.exc.NoResultFound:
            return [], 200, {"X-Total-Count": '0'}

        q = q.filter(Adherent.chambre == result)
    if terms:
        q = q.filter((Adherent.nom.contains(terms))
                     | (Adherent.prenom.contains(terms))
                     | (Adherent.mail.contains(terms))
                     | (Adherent.login.contains(terms))
                     | (Adherent.commentaires.contains(terms)))
    count = q.count()
    q = q.order_by(Adherent.login.asc())
    q = q.offset(offset)
    q = q.limit(limit)
    r = q.all()
    headers = {
        "X-Total-Count": str(count),
        'access-control-expose-headers': 'X-Total-Count'
    }
    return list(map(dict, r)), 200, headers
Пример #10
0
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"]
Пример #11
0
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
Пример #12
0
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()
Пример #13
0
def deletePort(admin, switchID, portID):
    """ [API] Delete a port from the database """
    session = db.get_db().get_session()
    try:
        session.delete(Port.find(session, portID))
    except PortNotFound:
        return NoContent, 404
    session.commit()
    return NoContent, 204
Пример #14
0
def deleteRoom(admin, roomNumber):
    """ [API] Delete room from the database """
    s = db.get_db().get_session()
    try:
        s.delete(Chambre.find(s, roomNumber))
    except RoomNotFound:
        return NoContent, 404

    s.commit()
    return NoContent, 204
Пример #15
0
def getPort(admin, switchID, portID):
    """ [API] Get a port from the database """
    s = db.get_db().get_session()
    try:
        result = Port.find(s, portID)
    except PortNotFound:
        return NoContent, 404

    result = dict(result)
    return result, 200
Пример #16
0
def test_user_delete_existant(api_client):
    r = api_client.delete(
        '{}/user/{}'.format(base_url, "dubois_j"),
        headers=TEST_HEADERS
    )
    assert r.status_code == 204

    s = db.get_db().get_session()
    q = s.query(Adherent)
    q = q.filter(Adherent.login == "dubois_j")
    assert not s.query(q.exists()).scalar()
Пример #17
0
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

    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"
Пример #18
0
def deleteSwitch(admin, switchID):
    """ [API] Delete the specified switch from the database """
    session = db.get_db().get_session()

    try:
        switch = Switch.find(session, switchID)
    except SwitchNotFound:
        return NoContent, 404

    session.delete(switch)
    session.commit()

    return NoContent, 204
Пример #19
0
def createSwitch(admin, body):
    """ [API] Create a switch in the database """
    if "id" in body:
        return "You cannot set the id", 400
    session = db.get_db().get_session()
    try:
        switch = Switch.from_dict(session, body)
    except InvalidIPv4:
        return "Invalid IPv4", 400
    session.add(switch)
    session.commit()

    return NoContent, 201, {'Location': '/switch/{}'.format(switch.id)}
Пример #20
0
def deleteDevice(admin, macAddress):
    """ [API] Delete the specified device from the database """
    s = db.get_db().get_session()
    if is_wireless(macAddress, s):
        delete_wireless_device(admin, macAddress, s)
        return NoContent, 204

    elif is_wired(macAddress, s):
        delete_wired_device(admin, macAddress, s)
        return NoContent, 204

    else:
        return NoContent, 404
Пример #21
0
def test_port_put_delete_port(api_client, sample_switch1, sample_port1):

    r = api_client.delete(
        "{}/switch/{}/port/{}".format(base_url,
                                      sample_switch1.id,
                                      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()
Пример #22
0
def assert_user_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"]
    print(r.date_de_depart)
    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"]
Пример #23
0
def test_modification_add_new_user(api_client, sample_member2):
    s = db.get_db().get_session()

    a = sample_member2
    s.add(a)
    s.flush()

    # Build the corresponding modification
    Modification.add_and_commit(s, a, a.get_ruby_modif(),
                                Utilisateur.find_or_create(s, "test"))
    q = s.query(Modification)
    m = q.first()
    assert m.action == (
        '--- !ruby/hash:ActiveSupport::HashWithIndifferentAccess\n'
        'chambre_id:\n'
        '- \n'
        '- 1\n'
        'commentaires:\n'
        '- \n'
        '- Desauthent pour routeur\n'
        'id:\n'
        '- \n'
        '- 2\n'
        'login:\n'
        '- \n'
        '- reignier\n'
        'mail:\n'
        '- \n'
        '- [email protected]\n'
        'mode_association:\n'
        '- \n'
        '- 2011-04-30 17:50:17\n'
        'nom:\n'
        '- \n'
        '- Reignier\n'
        'password:\n'
        '- \n'
        '- a\n'
        'prenom:\n'
        '- \n'
        '- Edouard\n')
    assert m.adherent_id == a.id
    now = datetime.datetime.now()
    one_sec = datetime.timedelta(seconds=1)
    assert now - m.created_at < one_sec
    assert now - m.updated_at < one_sec
    assert m.utilisateur_id == 1
Пример #24
0
def getDevice(admin, macAddress):
    """ [API] Return the device specified by the macAddress """
    s = db.get_db().get_session()
    if is_wireless(macAddress, s):
        q = s.query(models.Portable)
        q = q.filter(models.Portable.mac == macAddress)
        r = q.one()
        return dict(r), 200

    elif is_wired(macAddress, s):
        q = s.query(models.Ordinateur)
        q = q.filter(models.Ordinateur.mac == macAddress)
        r = q.one()
        return dict(r), 200

    else:
        return NoContent, 404
Пример #25
0
def createPort(admin, switchID, body):
    """ [API] Create a port in the database """

    session = db.get_db().get_session()
    try:
        port = Port.from_dict(session, body)
    except SwitchNotFound:
        return "Switch not found", 400
    except RoomNotFound:
        return "Room not found", 400

    session.add(port)
    session.commit()
    headers = {
        'Location': '/switch/{}/port/{}'.format(port.switch_id, port.id)
    }
    return NoContent, 200, headers
Пример #26
0
def test_modification_delete_member(api_client, sample_member):
    s = db.get_db().get_session()
    a = Adherent.find(s, sample_member.login)

    a.start_modif_tracking()
    s.delete(a)
    s.flush()

    # Build the corresponding modification
    Modification.add_and_commit(s, a, a.get_ruby_modif(),
                                Utilisateur.find_or_create(s, "test"))
    q = s.query(Modification)
    m = q.first()
    assert m.action == (
        '--- !ruby/hash:ActiveSupport::HashWithIndifferentAccess\n'
        'chambre_id:\n'
        '- 1\n'
        '- \n'
        'id:\n'
        '- 1\n'
        '- \n'
        'login:\n'
        '- dubois_j\n'
        '- \n'
        'mail:\n'
        '- [email protected]\n'
        '- \n'
        'mode_association:\n'
        '- 2011-04-30 17:50:17\n'
        '- \n'
        'nom:\n'
        '- Dubois\n'
        '- \n'
        'password:\n'
        '- a\n'
        '- \n'
        'prenom:\n'
        '- Jean-Louis\n'
        '- \n')
    assert m.adherent_id == sample_member.id
    now = datetime.datetime.now()
    one_sec = datetime.timedelta(seconds=1)
    assert now - m.created_at < one_sec
    assert now - m.updated_at < one_sec
    assert m.utilisateur_id == 1
Пример #27
0
def test_user_change_password_ok(api_client):
    USERNAME = "******"
    body = {
        "password": "******"#NyL#+k:_xEdJrEDT7",
    }
    result = api_client.put(
        '{}/user/{}/password/'.format(base_url, USERNAME),
        data=json.dumps(body),
        content_type='application/json',
        headers=TEST_HEADERS,
    )
    assert result.status_code == 204

    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"])
    assert_one_modification_created(USERNAME)
Пример #28
0
def updateSwitch(admin, switchID, body):
    """ [API] Update the specified switch from the database """
    if "id" in body:
        return "You cannot update the id", 400

    session = db.get_db().get_session()
    if not switchExists(session, switchID):
        return NoContent, 404

    try:
        switch = Switch.from_dict(session, body)
        switch.id = switchID
    except InvalidIPv4:
        return "Invalid IPv4", 400

    session.merge(switch)
    session.commit()

    return NoContent, 204
Пример #29
0
def updatePort(admin, switchID, portID, body):
    """ [API] Update a port in the database """

    s = db.get_db().get_session()

    try:
        new_port = Port.from_dict(s, body)
    except SwitchNotFound:
        return "Switch not found", 400

    try:
        new_port.id = Port.find(s, portID).id
    except PortNotFound:
        return "Port not found", 404

    s.merge(new_port)
    s.commit()

    return NoContent, 204
Пример #30
0
def putRoom(admin, roomNumber, body):
    """ [API] Update/create a room in the database """
    s = db.get_db().get_session()

    try:
        new_room = Chambre.from_dict(s, body)
    except VlanNotFound:
        return "Vlan not found", 400
    room_exists = roomExists(s, roomNumber)

    if room_exists:
        new_room.id = Chambre.find(s, roomNumber).id

    s.merge(new_room)
    s.commit()

    if room_exists:
        return NoContent, 204
    else:
        return NoContent, 201