Example #1
0
def get_reqeusts(valid_data: Dict, user: User) -> Result[List[Dict], HttpError]:
    if not valid_data:
        return Ok([request_converter.to_dict(r) for r in Request.objects.filter(customer=user)])

    radius = valid_data.get('radius')
    lat = valid_data.get('lat')
    long = valid_data.get('long')
    finished = valid_data.get('finished')
    assigned = valid_data.get('assigned')
    starts_after = valid_data.get('starts_after')
    if starts_after is not None:
        starts_after = datetime.fromtimestamp(starts_after)

    filters = dict_filter({
        'finished': finished,
        'start_time__gte': starts_after,
    })
    if assigned is not None:
        filters['assigned_to__isnull'] = not assigned

    request_query = Request.objects.filter(**filters)
    if radius is None or lat is None or long is None:
        return Ok([request_converter.to_dict(r) for r in request_query])
    return Ok([
        request_converter.to_dict(r) for r in request_query if
        haversine((lat, long), (r.latitude, r.longitude)) <= radius
    ])
Example #2
0
def find_job(valid_data: Dict, user: User):
    data = {key + 'itude' if key in ('lat', 'long') else key: val for key, val in
            valid_data.items()}
    job = Request.objects.find_job(user, **data)
    if job:
        return Ok(request_converter.to_dict(job.value))
    return Ok(None)
Example #3
0
def test_to_dict(has_start, has_assign, create_full_user, response_count,
                 finished):
    request = fake_request(has_start)
    request.finished = finished

    worker, _ = create_full_user
    if has_assign:
        request.assigned_to = worker
    responses = [fake_response(request) for _ in range(response_count)]

    request.save()

    request_dict = request_converter.to_dict(request)
    assert request_dict['request_id'] == request.id
    assert request_dict['customer'] == user_converter.to_dict(request.customer)
    if has_start:
        assert request_dict['start_time'] == int(
            request.start_time.timestamp())
    else:
        assert request_dict['start_time'] is None

    assert request_dict['duration'] == int(request.duration.total_seconds())
    assert abs(request_dict['latitude'] - float(request.latitude)) < 0.0001
    assert abs(request_dict['longitude'] - float(request.longitude)) < 0.0001
    assert request_dict['finished'] == request.finished
    assert request_dict['description'] == request.description
    if has_assign:
        assert request_dict['assigned_to'] == user_converter.to_dict(worker)
    else:
        assert request_dict['assigned_to'] is None
    assert len(request_dict['responses']) == len(responses)
    for response_dict in (response_converter.to_dict(resp)
                          for resp in responses):
        assert response_dict in request_dict['responses']
Example #4
0
def test_no_query(create_full_user, client):
    user, password = create_full_user
    reqeusts = [
        fake_request(random.choice([True, False]), user) for _ in range(10)
    ]
    other_requests = [
        fake_request(random.choice([True, False])) for _ in range(10)
    ]
    for req in reqeusts:
        for _ in range(random.randint(0, 5)):
            fake_response(req)
    resp = client.get('/api/v1/request',
                      HTTP_AUTHORIZATION=encode_auth(user.email, password))
    assert resp.status_code == 200
    resp_dict = json.loads(resp.content)
    assert sorted(resp_dict['requests'],
                  key=lambda d: d['request_id']) == sorted(
                      (request_converter.to_dict(req) for req in reqeusts),
                      key=lambda d: d['request_id'])
Example #5
0
def test_success(has_start_time, create_full_user, client):
    user, password = create_full_user
    d = {
        'duration': int(fake.time_delta().total_seconds()),
        'latitude': float(fake.latitude()),
        'longitude': float(fake.longitude()),
        'description': fake.text(),
        'title': fake.text(),
    }
    if has_start_time:
        d['start_time'] = int(fake.date_time().timestamp())
    resp = client.post('/api/v1/request',
                       data=d,
                       content_type='application/json',
                       HTTP_AUTHORIZATION=encode_auth(user.email, password))
    assert resp.status_code == 200
    resp_json = json.loads(resp.content)
    request_created = Request.objects.get(id=resp_json['request_id'])
    assert resp_json == request_converter.to_dict(request_created)
Example #6
0
def test_query(query, expected, create_full_user, client):
    user, password = create_full_user

    customers = [u for u, _ in generate_users(5)]
    workers = [u for u, _ in generate_users(5)]
    for u in chain(customers, workers):
        u.save()

    default_args = lambda: {
        'duration': fake.time_delta(),
        'latitude': fake.latitude(),
        'longitude': fake.longitude(),
        'description': fake.text(),
        'customer': random.choice(customers)
    }
    reqeusts = [
        Request(start_time=datetime.fromtimestamp(1000),
                assigned_to=random.choice(workers),
                finished=True,
                **default_args()),
        Request(start_time=datetime.fromtimestamp(30000),
                assigned_to=None,
                finished=False,
                **default_args())
    ]
    for r in reqeusts:
        r.clean()
        r.save()
    resp = client.get(f'/api/v1/request?{query}',
                      HTTP_AUTHORIZATION=encode_auth(user.email, password))
    assert resp.status_code == 200
    resp_dict = json.loads(resp.content)
    resp_requests = resp_dict['requests']
    assert len(resp_requests) == len(expected)
    assert sorted([request_converter.to_dict(reqeusts[i]) for i in expected],
                  key=lambda d: d['request_id']) == sorted(
                      resp_requests, key=lambda d: d['request_id'])
Example #7
0
def test_query_radius(lat, long, radius, expected, client, create_full_user):
    request_dict_lst = [
        fake_request_creation(True),
        fake_request_creation(False),
    ]
    reqeusts = [Request.objects.create_request(**d) for d in request_dict_lst]
    reqeusts[0].latitude = 0
    reqeusts[0].longitude = 0
    reqeusts[0].save()

    reqeusts[1].latitude = -50
    reqeusts[1].longitude = 50
    reqeusts[1].save()

    user, password = create_full_user
    resp = client.get(f'/api/v1/request?lat={lat}&long={long}&radius={radius}',
                      HTTP_AUTHORIZATION=encode_auth(user.email, password))
    assert resp.status_code == 200
    resp_dict = json.loads(resp.content)
    resp_requests = resp_dict['requests']
    assert len(resp_requests) == len(expected)
    assert sorted([request_converter.to_dict(reqeusts[i]) for i in expected],
                  key=lambda d: d['request_id']) == sorted(
                      resp_requests, key=lambda d: d['request_id'])