Ejemplo n.º 1
0
def test_get_close_db(app):
    with app.app_context():
        db = get_db()
        assert db is get_db()

    with pytest.raises(sqlite3.ProgrammingError) as e:
        db.execute('SELECT 1')

    assert 'closed' in str(e.value)
Ejemplo n.º 2
0
def test_user_cannot_be_in_risk_if_it_is_infected(app, client, auth):

    access_headers = get_access_headers(auth.login())
    client.post('/checkin', headers=access_headers, json={'location_id': 1})
    access_headers_other = get_access_headers(
        client.post('/auth/login',
                    json={
                        'username': '******',
                        'password': '******'
                    }))
    client.post('/checkin',
                headers=access_headers_other,
                json={'location_id': 1})
    access_headers = get_access_headers(auth.login())
    client.post('/checkin', headers=access_headers, json={'location_id': 1})
    client.post('/checkout', headers=access_headers, json={'location_id': 1})
    client.post('/inform/infection',
                headers=access_headers,
                json={'date': date.today()})
    client.post('/checkout',
                headers=access_headers_other,
                json={'location_id': 1})
    client.post('/inform/infection',
                headers=access_headers_other,
                json={'date': date.today()})
    with app.app_context():
        db = get_db()
        users_data = db.execute('SELECT * FROM user').fetchall()

        assert users_data[0]['being_in_risk_since'] is None
        assert users_data[0]['is_infected']
        assert users_data[2]['being_in_risk_since'] is None
        assert users_data[2]['is_infected']
Ejemplo n.º 3
0
def test_user_is_not_in_risk_if_does_not_share_space_with_infected(
        app, client, auth):
    # enter location with another user
    access_headers_other = get_access_headers(
        client.post('/auth/login',
                    json={
                        'username': '******',
                        'password': '******'
                    }))
    client.post('/checkin',
                headers=access_headers_other,
                json={'location_id': 1})
    client.post('/checkout',
                headers=access_headers_other,
                json={'location_id': 1})
    sleep(1.0)
    access_headers = get_access_headers(auth.login())
    client.post('/checkin', headers=access_headers, json={'location_id': 1})
    client.post('/checkout', headers=access_headers, json={'location_id': 1})
    client.post('/inform/infection',
                headers=access_headers,
                json={'date': date.today()})
    with app.app_context():
        db = get_db()
        being_in_risk_since = db.execute(
            'SELECT being_in_risk_since FROM user'
            ' WHERE id = 3').fetchone()['being_in_risk_since']
        assert being_in_risk_since is None
Ejemplo n.º 4
0
def test_cannot_checkin_to_maxed_location(app, client, auth):
    # enter location with another user
    access_headers_other = get_access_headers(
        client.post('/auth/login',
                    json={
                        'username': '******',
                        'password': '******'
                    }))
    client.post('/checkin',
                headers=access_headers_other,
                json={'location_id': 7})
    access_headers = get_access_headers(auth.login())

    response = client.post('/checkin',
                           headers=access_headers,
                           json={'location_id': 7})
    response_json = response.get_json()
    assert response.status_code == 200
    assert response_json['message'] == "Cannot enter, location is full."
    assert not response_json['success']
    with app.app_context():
        db = get_db()
        current_location = db.execute(
            'SELECT current_location FROM user'
            ' WHERE id = 1').fetchone()['current_location']
        assert current_location is None
        checks_data = db.execute('SELECT * FROM checks').fetchall()
        assert len(checks_data) == 1
        assert checks_data[0]['author_id'] == 3
Ejemplo n.º 5
0
def test_checkout(app, client, auth):
    access_headers = get_access_headers(auth.login())

    client.post('/checkin', headers=access_headers, json={'location_id': 1})
    response = client.post('/checkout',
                           headers=access_headers,
                           json={'location_id': 1})
    response_json = response.get_json()
    assert response.status_code == 200
    assert response_json['message'] == "Checkout successful."
    assert response_json['success']

    with app.app_context():
        db = get_db()
        user_data = db.execute('SELECT * FROM user' ' WHERE id = 1').fetchone()
        assert user_data['current_location'] is None
        people_inside_location = db.execute(
            'SELECT people_inside FROM location'
            ' WHERE id = 1').fetchone()['people_inside']
        assert people_inside_location == 0
        check_data = db.execute('SELECT * FROM checks'
                                ' WHERE author_id = 1').fetchone()
        assert check_data['location_id'] == 1
        assert check_data['check_in_time'] is not None
        assert check_data['check_out_time'] is not None
Ejemplo n.º 6
0
def app():
    db_fd, db_path = tempfile.mkstemp()

    app = create_app({
        'TESTING': True,
        'DATABASE': db_path,
    })

    with app.app_context():
        init_db()
        get_db().executescript(_data_sql)

    yield app

    os.close(db_fd)
    os.unlink(db_path)
Ejemplo n.º 7
0
def get_all(table_name):
    """Get all rows from table of database and
    convert it to array of dictionaries.
    """
    c = get_db().cursor()
    c.execute('SELECT * FROM {}'.format(table_name))

    return [dict(row) for row in c]
Ejemplo n.º 8
0
def add_user(username, password, email, is_admin):
    """Insert user to database.
    """
    db = get_db()
    db.execute(
            'INSERT INTO user (username, password, email, is_admin) VALUES (?, ?, ?, ?)',
            (username, password, email, is_admin)
        )
    db.commit()
Ejemplo n.º 9
0
def test_user_gets_risk_from_most_recent_contact_with_infected(
        app, client, auth):

    access_headers = get_access_headers(auth.login())
    access_headers_other = get_access_headers(
        client.post('/auth/login',
                    json={
                        'username': '******',
                        'password': '******'
                    }))
    access_headers_another = get_access_headers(
        client.post('/auth/login',
                    json={
                        'username': '******',
                        'password': '******'
                    }))
    client.post('/checkin',
                headers=access_headers_another,
                json={'location_id': 2})
    client.post('/checkin',
                headers=access_headers_other,
                json={'location_id': 2})
    client.post('/checkout',
                headers=access_headers_other,
                json={'location_id': 2})
    client.post('/checkout',
                headers=access_headers_another,
                json={'location_id': 2})
    client.post('/checkin', headers=access_headers, json={'location_id': 1})
    client.post('/checkin',
                headers=access_headers_other,
                json={'location_id': 1})
    client.post('/checkout',
                headers=access_headers_other,
                json={'location_id': 1})
    before = datetime.now()
    sleep(1.0)
    client.post('/checkin',
                headers=access_headers_other,
                json={'location_id': 1})
    client.post('/checkout',
                headers=access_headers_other,
                json={'location_id': 1})
    client.post('/checkout', headers=access_headers, json={'location_id': 1})
    client.post('/inform/infection',
                headers=access_headers,
                json={'date': date.today()})
    client.post('/inform/infection',
                headers=access_headers_another,
                json={'date': date.today()})
    with app.app_context():
        db = get_db()
        being_in_risk_since = db.execute(
            'SELECT being_in_risk_since FROM user'
            ' WHERE id = 3').fetchone()['being_in_risk_since']
        assert string_to_datetime(being_in_risk_since) > before
Ejemplo n.º 10
0
def get_user(identifier, value):
    """Get user from database using
    the identifier and value.
    """
    user = get_db().execute(
        'SELECT * FROM user WHERE {} = ?'.format(identifier),
        (value,)
    ).fetchone()

    return user
Ejemplo n.º 11
0
def remove_infection(user_id):
    """Update tables with discharge.
    """
    db = get_db()
    db.execute(
        'UPDATE user SET is_infected = 0'
        ' WHERE id = ?',
        (user_id,)
    )
    db.commit()
Ejemplo n.º 12
0
def add_location(name, maximum_capacity, latitude, longitude, author_id):
    """Insert location to database.
    """
    db = get_db()
    db.execute(
        'INSERT INTO location (name, maximum_capacity, latitude, longitude, author_id)'
        ' VALUES (?, ?, ?, ?, ?)',
        (name, maximum_capacity, latitude, longitude, author_id)
    )
    db.commit()
Ejemplo n.º 13
0
def test_author_not_required(client, auth, app):
    # change the location author to another user
    with app.app_context():
        db = get_db()
        db.execute('UPDATE location SET author_id = 2 WHERE id = 1')
        db.commit()

    access_headers = get_access_headers(auth.login())
    # current user can get other user's location
    assert client.get('/location/1', headers=access_headers).status_code == 200
Ejemplo n.º 14
0
def add_infection(user_id):
    """Update tables with infection,
    set users in risk that correspond
    and return those users.
    """
    users_reached = {}
    db = get_db()
    c = db.cursor()
    c.execute('SELECT * FROM checks'
        ' WHERE author_id = ?',
        (user_id,)
    )

    for row_c in c:
        d = db.cursor()
        d.execute('SELECT * FROM checks'
            ' WHERE NOT author_id = ? AND location_id = ? AND check_in_time <= ? AND (check_out_time IS NULL OR ? <= check_out_time)',
            (user_id, row_c['location_id'], row_c['check_out_time'], row_c['check_in_time'])
        )
        
        c_check_in_time = string_to_datetime(row_c['check_in_time'])
        c_check_out_time = string_to_datetime(row_c['check_out_time'])

        for row_d in d:
            d_check_in_time = string_to_datetime(row_d['check_in_time'])
            if row_d['check_out_time'] is None:
                d_check_out_time = c_check_out_time
            else:
                d_check_out_time = string_to_datetime(row_d['check_out_time'])
    
            in_risk_since = min(c_check_out_time, d_check_out_time)
            if row_d['author_id'] not in users_reached.keys():
                users_reached[row_d['author_id']] = in_risk_since
            else:
                users_reached[row_d['author_id']] = max(in_risk_since, users_reached[row_d['author_id']])

    informed_users = []
    informed_users_id = []
    c = db.cursor()
    c.execute('SELECT * FROM user WHERE id IN (%s) AND is_infected = 0' % placeholders(len(users_reached)),
        list(users_reached.keys()))
    for row_c in c:
        if row_c['being_in_risk_since'] is None or string_to_datetime(row_c['being_in_risk_since']) < users_reached[row_c['id']]:
            informed_users.append(dict(row_c))
            informed_users_id.append(row_c['id'])
            db.execute('UPDATE user SET being_in_risk_since = ? WHERE id = ?',
                (datetime_to_string(users_reached[row_c['id']]), row_c['id'])
            )
    db.execute(
        'UPDATE user SET is_infected = 1, being_in_risk_since = NULL'
        ' WHERE id = ?',
        (user_id,)
    )
    db.commit()
    return informed_users
Ejemplo n.º 15
0
def test_infection(app, client, auth):
    access_headers = get_access_headers(auth.login())

    assert client.post('/inform/infection',
                       headers=access_headers,
                       json={
                           'date': date.today()
                       }).status_code == 200
    with app.app_context():
        db = get_db()
        is_infected = db.execute('SELECT is_infected FROM user'
                                 ' WHERE id = 1').fetchone()['is_infected']
        assert is_infected
Ejemplo n.º 16
0
def test_cannot_discharge_if_user_is_not_infected(app, client, auth):
    access_headers = get_access_headers(auth.login())

    response = client.post('/inform/discharge',
                           headers=access_headers,
                           json={'date': date.today()})
    assert response.status_code == 200
    assert response.get_json()['message'] == 'User is not infected'
    with app.app_context():
        db = get_db()
        is_infected = db.execute('SELECT is_infected FROM user'
                                 ' WHERE id = 1').fetchone()['is_infected']
        assert not is_infected
Ejemplo n.º 17
0
def exit_user_from_location(user_id, location_id, time):
    """Update tables with checkout.
    """
    db = get_db()

    db.execute("UPDATE location SET people_inside = people_inside -1 WHERE id = ?", (location_id,))
    db.execute("UPDATE user SET current_location = NULL WHERE id = ?", (user_id,))

    db.execute(
        'UPDATE checks SET check_out_time = ?'
        ' WHERE author_id = ? AND check_out_time IS NULL',
        (time, user_id)
    )
    
    db.commit()
Ejemplo n.º 18
0
def test_create(client, auth, app):
    access_headers = get_access_headers(auth.login())
    assert client.post('/location/create',
                       headers=access_headers,
                       json={
                           'name': 'created',
                           'maximum_capacity': 10,
                           'latitude': 5.0,
                           'longitude': 10.0
                       }).status_code == 201

    with app.app_context():
        db = get_db()
        count = db.execute('SELECT COUNT(id) FROM location').fetchone()[0]
        assert count == 8
Ejemplo n.º 19
0
def test_register_does_not_duplicate_user(client, app):
    response = client.post('/auth/register',
                           json={
                               'username': '******',
                               'password': '******',
                               'email': '*****@*****.**'
                           })
    response_data = response.get_json()
    assert response_data['message'] == 'User usertest is already registered.'
    assert not response_data['created']
    assert response.status_code == 200

    with app.app_context():
        assert get_db().execute(
            "select COUNT(id) from user where username = '******'",
        ).fetchone()[0] == 1
Ejemplo n.º 20
0
def test_register(client, app):

    response = client.post('/auth/register',
                           json={
                               'username': '******',
                               'password': '******',
                               'email': '*****@*****.**'
                           })
    assert response.status_code == 201
    response_data = response.get_json()
    assert response_data['message'] == 'User registered succesfully.'
    assert response_data['created']

    with app.app_context():
        assert get_db().execute(
            "select * from user where username = '******'", ).fetchone() is not None
Ejemplo n.º 21
0
def get_location(id, check_author=True):
    """Get location from database and check
    user is author if desired.
    """
    location = get_db().execute(
        'SELECT * FROM location WHERE id = ?',
        (id,)
    ).fetchone()

    if location is None:
        abort(404, "Location id {0} doesn't exist.".format(id))

    if check_author and location['author_id'] != get_jwt_identity():
        abort(403)

    return location
Ejemplo n.º 22
0
def test_cannot_checkin_to_location_that_does_not_exist(app, client, auth):
    access_headers = get_access_headers(auth.login())

    response = client.post('/checkin',
                           headers=access_headers,
                           json={'location_id': 8})
    assert response.status_code == 404
    assert b"Location id 8 doesn't exist." in response.data

    with app.app_context():
        db = get_db()
        current_location = db.execute(
            'SELECT current_location FROM user'
            ' WHERE id = 1').fetchone()['current_location']
        assert current_location is None
        checks_amount = db.execute(
            'SELECT COUNT(id) FROM checks').fetchone()[0]
        assert checks_amount == 0
Ejemplo n.º 23
0
def test_cannot_checkout_if_user_is_not_in_location(app, client, auth):
    access_headers = get_access_headers(auth.login())

    response = client.post('/checkout',
                           headers=access_headers,
                           json={'location_id': 1})
    response_json = response.get_json()
    assert response.status_code == 200
    assert response_json['message'] == "Not current location."
    assert not response_json['success']
    with app.app_context():
        db = get_db()
        current_location = db.execute(
            'SELECT current_location FROM user'
            ' WHERE id = 1').fetchone()['current_location']
        assert current_location is None
        checks_amount = db.execute(
            'SELECT COUNT(id) FROM checks').fetchone()[0]
        assert checks_amount == 0
Ejemplo n.º 24
0
def enter_user_to_location(user_id, location_id, time):
    """Update tables with checkin.
    """
    db = get_db()

    db.execute(
        f"UPDATE location SET people_inside = people_inside + 1 WHERE id = {location_id}"
    )
    
    db.execute(
        f"UPDATE user SET current_location = {location_id}  WHERE id = {user_id}"
    )

    db.execute(
        'INSERT INTO checks (author_id, location_id, check_in_time)'
        ' VALUES (?, ?, ?)',
        (user_id, location_id, time)
    )

    db.commit()