Example #1
0
def test_get_provider_reason_from_both_mappings_for_new_mapping(device):
    """
    Checks that the mapping are consistent for objects stored in the new format.
    """
    for reason, agency_event in PROVIDER_REASON_TO_AGENCY_EVENT.items():
        event_type, event_type_reason = (agency_event if len(agency_event) == 2
                                         else agency_event + (None, ))
        obj = factories.EventRecord(device=device,
                                    event_type=event_type,
                                    event_type_reason=event_type_reason)
        provider_reason = get_provider_reason_from_both_mappings(obj)
        assert provider_reason == reason
Example #2
0
def test_get_provider_reason_from_both_mappings_for_old_mapping(device):
    """
    Checks that the mapping are consistent for objects stored in the old format.
    """
    for reason, agency_event in OLD_PROVIDER_REASON_TO_AGENCY_EVENT.items():
        obj = factories.EventRecord(device=device, event_type=agency_event)
        provider_reason = get_provider_reason_from_both_mappings(obj)
        if agency_event == "service_end":
            # We skip this case because the old mapping is wrong for this one.
            # We want to map a Agency "service_end" to "maintenance"
            continue
        assert provider_reason == reason
Example #3
0
def test_get_provider_reason_from_both_mappings_new_objects_not_in_old(device):
    """
    Checks that the function to get the provider_reason from the EventRecord
    uses the old mapping for events that are not in the new mapping.
    """
    obj = factories.EventRecord(
        device=device,
        event_type=enums.PROVIDER_EVENT_TYPE_REASON.rebalance_pick_up.name,
    )
    provider_reason = get_provider_reason_from_both_mappings(obj)
    assert provider_reason in AGENCY_EVENT_TO_PROVIDER_REASON.values()
    assert provider_reason == enums.PROVIDER_EVENT_TYPE_REASON.rebalance_pick_up.name
Example #4
0
def test_get_provider_reason_from_both_mappings_old_objects(device):
    """
    Checks that the function to get the provider_reason from the EventRecord
    works as expected for old objects.
    """
    obj = factories.EventRecord(
        device=device,
        event_type=enums.PROVIDER_EVENT_TYPE_REASON.rebalance_drop_off.name,
    )
    provider_reason = get_provider_reason_from_both_mappings(obj)
    assert provider_reason in OLD_AGENCY_EVENT_TO_PROVIDER_REASON.values()
    assert provider_reason == enums.PROVIDER_EVENT_TYPE_REASON.rebalance_drop_off.name
Example #5
0
def test_get_provider_reason_from_both_mappings_new_objects(device):
    """
    Checks that the function to get the provider_reason from the EventRecord
    works as expected for new objects.
    """
    obj = factories.EventRecord(
        device=device,
        event_type=enums.PROVIDER_EVENT_TYPE_REASON.service_end.name,
        event_type_reason=enums.EVENT_TYPE_REASON.maintenance.name,
    )
    provider_reason = get_provider_reason_from_both_mappings(obj)
    assert provider_reason in AGENCY_EVENT_TO_PROVIDER_REASON.values()
    assert provider_reason == enums.PROVIDER_EVENT_TYPE_REASON.maintenance.name
Example #6
0
def test_device_list_basic(client, django_assert_num_queries):
    now = timezone.now()

    uuid1 = "aaaaaaa1-1342-413b-8e89-db802b2f83f6"
    uuid2 = "ccccccc3-1342-413b-8e89-db802b2f83f6"

    provider = factories.Provider(name="Test provider")
    provider2 = factories.Provider(name="Test another provider")

    device1 = factories.Device(
        id=uuid1,
        provider=provider,
        identification_number="1AAAAA",
        model="Testa_Model_S",
        category="car",
        propulsion=["combustion"],
        registration_date=now,
        dn_status="available",
        dn_gps_point="Point(40 15.0)",
        dn_gps_timestamp=now,
        dn_battery_pct=0.5,
    )
    device2 = factories.Device(
        id=uuid2,
        provider=provider2,
        identification_number="3CCCCC",
        model="Testa_Model_X",
        category="scooter",
        propulsion=["electric"],
        registration_date=now,
        dn_status="unavailable",
        dn_gps_point=None,
        dn_gps_timestamp=None,
        dn_battery_pct=None,
    )

    # Add an event on the first device
    factories.EventRecord(
        device=device1,
        timestamp=now,
        event_type=enums.EVENT_TYPE.maintenance.name,
        properties={
            "trip_id": "b3da2d46-065f-4036-903c-49d796f09357",
            "telemetry": {
                "timestamp": 1_325_376_000_000,
                "gps": {"lat": 33.996_339, "lng": -118.48153},
            },
        },
    )
def test_follow_up(client, settings, requests_mock):
    """Catching up new telemetries from the last one we got."""
    settings.POLLER_CREATE_REGISTER_EVENTS = True
    event = factories.EventRecord(
        device__provider__base_api_url="http://provider")
    device = event.device
    provider = device.provider
    provider.last_event_time_polled = event.timestamp
    provider.save()
    expected_event = factories.EventRecord.build(
        event_type=enums.EVENT_TYPE.service_end.name, timestamp=timezone.now())
    stdout, stderr = io.StringIO(), io.StringIO()

    # Mocking must fail if the command does not make the expected query
    requests_mock.get(
        urllib.parse.urljoin(provider.base_api_url, "/status_changes"),
        status_code=400,
    )
    requests_mock.get(
        urllib.parse.urljoin(
            provider.base_api_url,
            "/status_changes?%s" % urllib.parse.urlencode(
                {"start_time": round(event.timestamp.timestamp() * 1000)}),
        ),
        json=make_response(provider,
                           device,
                           expected_event,
                           event_type_reason="service_end"),
    )
    call_command("poll_providers",
                 "--raise-on-error",
                 stdout=stdout,
                 stderr=stderr)

    assert_command_success(stdout, stderr)

    assert device.event_records.count() == 2
    event = device.event_records.latest("timestamp")
    assert_event_equal(event, expected_event)
def test_device_list_basic(client, django_assert_num_queries):
    today = datetime.datetime(2012, 1, 1, tzinfo=datetime.timezone.utc)

    uuid1 = "aaaaaaa1-1342-413b-8e89-db802b2f83f6"
    uuid2 = "ccccccc3-1342-413b-8e89-db802b2f83f6"

    provider = factories.Provider(name="Test provider")
    provider2 = factories.Provider(name="Test another provider")

    device = factories.Device(
        id=uuid1,
        provider=provider,
        identification_number="1AAAAA",
        model="Testa_Model_S",
        category="car",
        propulsion=["combustion"],
        registration_date=today,
        dn_status="available",
        dn_gps_point="Point(40 15.0)",
        dn_gps_timestamp=today,
        dn_battery_pct=0.5,
    )
    factories.Device(
        id=uuid2,
        provider=provider2,
        identification_number="3CCCCC",
        model="Testa_Model_X",
        category="scooter",
        propulsion=["electric"],
        registration_date=today,
        dn_status="unavailable",
        dn_gps_point=None,
        dn_gps_timestamp=None,
        dn_battery_pct=None,
    )

    # Add some telemetries on the first device
    factories.EventRecord(device=device, saved_at=today, event_type="reserve")
    factories.EventRecord.create_batch(3,
                                       device=device,
                                       saved_at=today -
                                       datetime.timedelta(seconds=10))

    expected_device = {
        "id": uuid1,
        "provider_id": str(provider.id),
        "provider_name": "Test provider",
        "identification_number": "1AAAAA",
        "model": "Testa_Model_S",
        "status": "available",
        "category": "car",
        "propulsion": ["combustion"],
        "position": {
            "type": "Point",
            "coordinates": [40, 15.0]
        },
        "last_telemetry_date": "2012-01-01T00:00:00Z",
        "registration_date": "2012-01-01T00:00:00Z",
        "battery": 0.5,
    }
    expected_device2 = {
        "id": uuid2,
        "provider_id": str(provider2.id),
        "provider_name": "Test another provider",
        "identification_number": "3CCCCC",
        "model": "Testa_Model_X",
        "status": "unavailable",
        "category": "scooter",
        "propulsion": ["electric"],
        "last_telemetry_date": None,
        "position": None,
        "registration_date": "2012-01-01T00:00:00Z",
        "battery": None,
    }
    # test auth
    response = client.get("/prv/vehicles/")
    assert response.status_code == 401

    n = BASE_NUM_QUERIES
    n += 1  # query on devices
    n += 1  # count on devices
    with django_assert_num_queries(n):
        response = client.get(
            "/prv/vehicles/",
            **auth_header(SCOPE_PRV_API, provider_id=provider.id))
    assert response.status_code == 200
    data = response.data["results"]
    assert len(data) == 2

    assert expected_device in data
    assert expected_device2 in data

    # test auth
    response = client.get("/prv/vehicles/%s/" % device.id)
    assert response.status_code == 401

    n = BASE_NUM_QUERIES
    n += 1  # query on devices
    n += 1  # query to get areas of device
    expected_device["areas"] = []
    expected_device["provider_logo"] = None

    with django_assert_num_queries(n):
        response = client.get(
            "/prv/vehicles/%s/" % device.id,
            **auth_header(SCOPE_PRV_API, provider_id=provider.id),
        )
    assert response.status_code == 200
    assert response.data == expected_device
Example #9
0
def test_device_list_basic(client, django_assert_num_queries):
    today = datetime.datetime(2012, 1, 1, tzinfo=datetime.timezone.utc)
    uuid1 = uuid.UUID("aaaaaaa1-1342-413b-8e89-db802b2f83f6")
    uuid2 = uuid.UUID("ccccccc3-1342-413b-8e89-db802b2f83f6")

    provider = factories.Provider(name="Test provider")
    provider2 = factories.Provider(name="Test another provider")

    device = factories.Device(
        id=uuid1,
        provider=provider,
        identification_number="1AAAAA",
        model="Testa_Model_S",
        category="car",
        propulsion=["combustion"],
        registration_date=today,
        dn_status="available",
    )
    factories.Device(
        id=uuid2,
        provider=provider,
        identification_number="3CCCCC",
        model="Testa_Model_X",
        category="scooter",
        propulsion=["electric"],
        registration_date=today,
        dn_status="available",
    )
    other_device = factories.Device(provider=provider2)

    # Add some telemetries on the first device
    factories.EventRecord(
        device=device,
        saved_at=today - datetime.timedelta(seconds=10),
        timestamp=today - datetime.timedelta(seconds=10),
    )
    # Last event
    factories.EventRecord(
        device=device,
        saved_at=today,
        event_type=enums.EVENT_TYPE.reserve.name,
        timestamp=today,
    )
    # timestamp predates second record, but it was saved afterwards
    factories.EventRecord(
        device=device,
        saved_at=today + datetime.timedelta(seconds=10),
        event_type=enums.EVENT_TYPE.maintenance_drop_off.name,
        timestamp=today - datetime.timedelta(seconds=5),
    )

    expected_device = {
        "device_id": str(uuid1),
        "provider_id": str(provider.id),
        "vehicle_id": "1AAAAA",
        "model": "Testa_Model_S",
        "type": "car",
        "propulsion": ["combustion"],
        "mfgr": "",
        "year": None,
        "status": "available",
        "prev_event": "reserve",
        "updated": 1_325_376_000_000,
    }

    expected_device2 = {
        "device_id": str(uuid2),
        "provider_id": str(provider.id),
        "vehicle_id": "3CCCCC",
        "model": "Testa_Model_X",
        "type": "scooter",
        "propulsion": ["electric"],
        "mfgr": "",
        "year": None,
        "status": "available",
        "prev_event": None,
        "updated": None,
    }

    # test auth
    response = client.get(reverse("agency:device-list"))
    assert response.status_code == 401

    n = BASE_NUM_QUERIES
    n += 1  # query on devices
    n += 1  # query on last telemetry
    with django_assert_num_queries(n):
        response = client.get(
            reverse("agency:device-list"),
            **auth_header(SCOPE_AGENCY_API, provider_id=provider.id),
        )
    assert response.status_code == 200
    assert len(response.data) == 2

    assert expected_device in response.data
    assert expected_device2 in response.data

    # test auth
    response = client.get(reverse("agency:device-detail", args=[device.id]))
    assert response.status_code == 401

    n = BASE_NUM_QUERIES
    n += 1  # query on devices
    n += 1  # query on last telemetry
    with django_assert_num_queries(n):
        response = client.get(
            reverse("agency:device-detail", args=[device.id]),
            **auth_header(SCOPE_AGENCY_API, provider_id=provider.id),
        )
    assert response.status_code == 200
    assert response.data == expected_device

    # cannot access other providers data
    response = client.get(
        reverse("agency:device-detail", args=[other_device.id]),
        **auth_header(SCOPE_AGENCY_API, provider_id=provider.id),
    )
    assert response.status_code == 404
Example #10
0
    factories.EventRecord(
        device=device1,
        timestamp=now,
        event_type=enums.EVENT_TYPE.maintenance.name,
        properties={
            "trip_id": "b3da2d46-065f-4036-903c-49d796f09357",
            "telemetry": {
                "timestamp": 1_325_376_000_000,
                "gps": {"lat": 33.996_339, "lng": -118.48153},
            },
        },
    )
    # A telemetry should not be considered as an event
    factories.EventRecord(
        device=device1,
        timestamp=now - datetime.timedelta(seconds=1),
        event_type=enums.EVENT_TYPE.telemetry.name,
    )
    # This one is too old
    factories.EventRecord(device=device1, timestamp=now - datetime.timedelta(hours=1))

    # Add an event on the second device
    factories.EventRecord(
        device=device2,
        timestamp=now,
        event_type=enums.EVENT_TYPE.trip_start.name,
        properties={
            "trip_id": None,
            "telemetry": {
                "timestamp": 1_325_376_000_000,
                "gps": {"lat": 33.996_339, "lng": -118.48153},