Esempio n. 1
0
def test_refresh_token(test_client):
    userAuth = buildUserAuth()
    strava_client_id = 'TESTCLIENTID'
    strava_client_secret = 'TESTSECRET'

    strava_response = {
        'token_type': 'Bearer',
        'access_token': random_utils.randomString(10),
        'expires_at': random_utils.randint(0, 10000),
        'expires_in': random_utils.randint(0, 100),
        'refresh_token': random_utils.randomString(10)
    }
    expectedPostBody = {
        'client_id': strava_client_id,
        'client_secret': strava_client_secret,
        'grant_type': 'refresh_token',
        'refresh_token': userAuth.strava_refresh_token
    }

    with requests_mock.Mocker() as m:
        stravaUrl = 'https://www.strava.com/api/v3/oauth/token'
        adapter = m.post(stravaUrl, text=json.dumps(strava_response))

        assert unit.refresh_auth_token(userAuth) == strava_response
        adapter.call_count == 1
        assert "client_id=" + expectedPostBody[
            'client_id'] in adapter.last_request.text
        assert "client_secret=" + expectedPostBody[
            'client_secret'] in adapter.last_request.text
        assert "grant_type=" + expectedPostBody[
            'grant_type'] in adapter.last_request.text
        assert "refresh_token=" + expectedPostBody[
            'refresh_token'] in adapter.last_request.text
def buildUser(overridenValues={}):
    data = {
        "id": str(random_utils.randint(0, 1000)),
        "email": random_utils.randomString(13),
        "basemap": buildBasemap(),
        "is_admin": False,
        "last_update": random_utils.randint(0, 100000)
    }

    for (key, value) in overridenValues.items():
        data[key] = value

    return User(data)
Esempio n. 3
0
def generate_mock_strava_api(runIds, numberOfNoiseActivities, mock):
    # Save the last Item for the end
    runIdsCopy = runIds.copy()
    lastId = runIdsCopy[-1]
    del runIdsCopy[-1]

    activityList = []
    activityListPage = 1
    for i in reversed(range(len(runIdsCopy) + numberOfNoiseActivities)):
        noiseThreshold = 1.0 * (i - len(runIdsCopy)) / (len(runIdsCopy) + 1)
        isNoise = False

        idOfActivity = None
        if len(runIdsCopy) == 0 or (random.random() < noiseThreshold):
            idOfActivity = random_utils.randint(0, 1000000)
            isNoise = True
        else:
            idOfActivity = runIdsCopy[0]
            del runIdsCopy[0]

        generate_endpoint_for_activity(mock, idOfActivity)
        activityList.append(
            generate_summary_activity('Run', isNoise, id=idOfActivity))
        if len(activityList) == 30:
            generate_endpoint_for_activity_list_page(mock, activityListPage, activityList)
            activityList = []
            activityListPage += 1

    # Generate the api for the last item
    generate_endpoint_for_activity(mock, lastId)
    activityList.append(generate_summary_activity('Run', False, lastId))
    generate_endpoint_for_activity_list_page(
        mock, activityListPage, activityList)
def test_get_updated_user_auth_when_valid_does_nothing():
    userAuth = generate_user_auth(
        {'strava_expiration_time': int(time.time()) + 1000})
    strava_response = {
        'token_type': 'Bearer',
        'access_token': random_utils.randomString(10),
        'expires_at': random_utils.randint(0, 10000),
        'expires_in': random_utils.randint(0, 100),
        'refresh_token': random_utils.randomString(10)
    }
    with requests_mock.Mocker() as m:
        stravaUrl = 'https://www.strava.com/api/v3/oauth/token'
        adapter = m.post(stravaUrl, text=json.dumps(strava_response))
        newUserAuth = unit.getUpdatedUserAuth(userAuth.id)
        assert userAuth.strava_auth_token == newUserAuth.strava_auth_token
        assert adapter.call_count == 0
Esempio n. 5
0
def buildRunMap(overridenValues={}):
    data = {
        'id': random_utils.randomString(4),
        'mapName': random_utils.randomString(14),
        'userId': random_utils.randomString(10),
        'center': random_utils.randomCord(),
        'zoom': random_utils.randint(0, 12),
        'runs': []
    }

    for i in range(random_utils.randint(0, 5)):
        data['runs'].append(random_utils.randomString(5))

    for (key, value) in overridenValues.items():
        data[key] = value

    return RunMap(data)
Esempio n. 6
0
def buildBasemap(*overridenValues):
    data = {
        "zoom": random_utils.randint(1, 12),
        "center": random_utils.randomCord(),
        "markers": []
    }

    for i in range(random_utils.randint(1, 5)):
        data["markers"].append(buildMarker())

    if not overridenValues:
        overridenValues = {}

    for (key, value) in overridenValues:
        data[key] = value

    return Basemap(data)
Esempio n. 7
0
def test_collect_runs_returns_the_runs_of_interest():
    userAuth = buildUserAuth()
    runIds = []
    for i in range(10):
        id = random_utils.randint(0, 10000)
        run = buildRun(overridenValues={'id': str(id), 'userId': userAuth.id})
        runIds.append(id)

    with requests_mock.Mocker() as m:
        strava_api.generate_mock_strava_api(runIds, 30, m)
        runs = unit.collectNewRuns(userAuth, last_update=5)

    assert len(runs) == 10
def test_get_updated_user_auth_when_expired_updates(test_client):
    userAuth = generate_user_auth(
        {'strava_expiration_time': int(time.time()) - 1000})

    strava_response = {
        'token_type': 'Bearer',
        'access_token': random_utils.randomString(10),
        'expires_at': random_utils.randint(0, 10000),
        'expires_in': random_utils.randint(0, 100),
        'refresh_token': random_utils.randomString(10)
    }

    with requests_mock.Mocker() as m:
        stravaUrl = 'https://www.strava.com/api/v3/oauth/token'
        m.post(stravaUrl, text=json.dumps(strava_response))
        unit.getUpdatedUserAuth(userAuth.id)
        # ensure that it have been saved to the db.
        updatedUser = unit.getUserAuthById(userAuth.id)
        assert updatedUser.strava_expiration_time == Decimal(
            strava_response['expires_at'])
        assert updatedUser.strava_refresh_token == strava_response[
            'refresh_token']
        assert updatedUser.strava_auth_token == strava_response['access_token']
Esempio n. 9
0
def test_update_user_only_inserts_runs_up_to_max_into_db():
    userAuth = buildUserAuth()
    runIds = []
    for i in range(40):
        id = random_utils.randint(0, 10000)
        run = buildRun(overridenValues={'id': str(id), 'userId': userAuth.id})
        runIds.append(id)

    with requests_mock.Mocker() as m:
        strava_api.generate_mock_strava_api(runIds, 0, m)
        unit.MAX_RUNS_TO_COLLECT = 10
        runs = unit.collectNewRuns(userAuth)

    assert len(runs) == 30
Esempio n. 10
0
def test_get_activity_by_id():
    userAuth = buildUserAuth()
    activityId = random_utils.randint(0, 100)
    strava_response = {'fakedata': random_utils.randomString(6)}

    with requests_mock.Mocker() as m:
        stravaUrl = 'https://www.strava.com/api/v3/activities/' \
                    + str(activityId)
        headers = {'Authorization': 'Bearer ' + userAuth.strava_auth_token}
        print(stravaUrl)
        m.get(stravaUrl,
              text=json.dumps(strava_response),
              request_headers=headers)

        assert unit.get_activity_by_id(userAuth, activityId) == strava_response
Esempio n. 11
0
def test_add_runs_to_run_maps():
    #Set up a few run maps with given locations
    startLocations = [[Decimal(75.3425), Decimal(-95.300)],
                      [Decimal(44.946636), Decimal(-93.293241)],
                      [Decimal(54.8675), Decimal(-85.123)],
                      ]
    runMaps = []
    expectedRunList = []
    runs = []

    for start in startLocations:
        runMap = buildRunMap(overridenValues={'center': start})
        expectedRunList.append(runMap.runs.copy())
        runMaps.append(runMap)

    # build a handfull of runs around the start location that must be added to
    # the map
    for i in range(20):
        index = random_utils.randint(0, len(startLocations)-1)
        run = buildRun(overridenValues={'start': startLocations[index]})
        expectedRunList[index] = [run.id] + expectedRunList[index]
        runs.append(run)

    # Now add a few runs that are not apart of any existing run map
    newLocation = [Decimal(40.688237), Decimal(-112.073817)]
    runsFromNewMap = [buildRun(overridenValues={'start': newLocation})]
    runsFromNewMap.append(buildRun(overridenValues={'start': newLocation}))
    runs += runsFromNewMap

    #reverse them so the 'newest ones' are first
    runs = reversed(runs)
    updatedMaps, newMaps = unit.addRunsToRunMaps(runMaps, runs)

    for i in range(len(runMaps)):
        assert updatedMaps[i].runs == expectedRunList[i]

    assert newMaps[0].runs == [runsFromNewMap[1].id, runsFromNewMap[0].id]
    assert newMaps[0].center == newLocation
Esempio n. 12
0
def generate_summary_activity(type, commuteFlag, id=None, hasGPS=True):
    return {
        "resource_state": random_utils.randint(0, 5),
        "athlete": {
            "id": random_utils.randint(0, 10000),
            "resource_state": random_utils.randint(0, 100)
        },
        "name": random_utils.randomString(5),
        "distance": random_utils.randomDecimal(0, 100, 3),
        "type": type,
        "workout_type": random_utils.randomString(15),
        "id": id if id else random_utils.randint(0, 1000000),
        "commute": commuteFlag,
        "external_id": random_utils.randomString(5),
        "utc_offset": random_utils.randint(-10000, 10000),
        "start_latlng": random_utils.randomCord() if hasGPS else None,
        "end_latlng": random_utils.randomCord() if hasGPS else None,
        "location_city": random_utils.randomString(6),
        "location_state": random_utils.randomString(6),
        "location_country": random_utils.randomString(4),
        "start_latitude": [random_utils.randomCord()[0]],
        "start_longitude": [random_utils.randomCord()[1]],
        "achievement_count": random_utils.randint(0, 10)
    }
Esempio n. 13
0
def generate_detailed_activity(id=random_utils.randint(0, 1000000)):
    return {
        "id": id,
        "resource_state": random_utils.randint(0, 10000),
        "athlete": {
            "id": random_utils.randint(0, 10000),
            "resource_state": random_utils.randint(0, 10000)
        },
        "name": random_utils.randomString(6),
        "distance": random_utils.randint(0, 10000),
        "moving_time": random_utils.randint(0, 10000),
        "elapsed_time": random_utils.randint(0, 10000),
        "type": "Ride",
        "start_latlng": random_utils.randomCord(),
        "end_latlng": random_utils.randomCord(),
        "start_latitude": random_utils.randomCord()[0],
        "start_longitude": random_utils.randomCord()[1],
        "achievement_count": random_utils.randint(0, 10000),
        "kudos_count": random_utils.randint(0, 10000),
        "comment_count": random_utils.randint(0, 10000),
        "map": {
            "id": random_utils.randomString(6),
            "polyline": random_utils.randomString(20),
            "resource_state": random_utils.randint(0, 10000),
            "summary_polyline": random_utils.randomString(6)
        },
        "trainer": False,
        "commute": False,
        "manual": False,
    }