Exemple #1
0
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
Exemple #2
0
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'
Exemple #3
0
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()
Exemple #4
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
    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"
Exemple #5
0
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"
Exemple #6
0
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
Exemple #7
0
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":
        "******"
    })
Exemple #8
0
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
Exemple #9
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"]
Exemple #10
0
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
Exemple #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
Exemple #12
0
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())
Exemple #13
0
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())
Exemple #14
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()
Exemple #15
0
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"]
Exemple #16
0
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
Exemple #17
0
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"])
Exemple #18
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()
Exemple #19
0
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
Exemple #20
0
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"]
Exemple #21
0
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
Exemple #22
0
    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()
Exemple #23
0
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)
Exemple #24
0
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()
Exemple #25
0
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
Exemple #26
0
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