Exemplo n.º 1
0
def app(mocker):  # noqa
    db_fd, db_path = tempfile.mkstemp()
    app = statsapp.create_app({
        'TESTING': True,
        'SQLALCHEMY_DATABASE_URI': 'sqlite:///' + db_path,
        'STRAVA_CLIENT_ID': '',
        'STRAVA_CLIENT_SECRET': '',
        'WITHINGS_CLIENT_ID': '',
        'WITHINGS_CLIENT_SECRET': '',
        'GOODREADS_CLIENT_ID': '',
        'GOODREADS_CLIENT_SECRET': '',
        'GOODREADS_USERID': '',
        'GSHEET_CLIENT_ID': '',
        'GSHEET_CLIENT_SECRET': '',
        'GSHEET_DOC_ID': '',
        'GOOGLEFIT_CLIENT_ID': '',
        'GOOGLEFIT_CLIENT_SECRET': '',
        'DEFAULT_USER_EMAIL': '*****@*****.**',
    })

    with app.app_context():
        # let's mock out any more calls to create_app and have it just return the app we
        # have now. otherwise it will end up creating a non-test instance of the app :S
        # this doesn't prevent doing "from statsapp import create_app" from instantiating a non-test app though.        mocker.patch('statsapp.create_app', return_value=app)
        db.init_app(app)
        db.create_all()
        User.create_user(app.config['DEFAULT_USER_EMAIL'], 'password')

        print(id(app))
        yield app

    os.close(db_fd)
    os.unlink(db_path)
Exemplo n.º 2
0
def test_get_data_and_upsert(mock_withings_api):
    weight = 3

    mock_withings_api.return_value = weight
    user = User.get_default_user()
    date = datetime.date.today()  # doesn't matter what the day is
    PullWithingsData().get_data_and_upsert(date, user)

    data = WithingsData.query.all()
    assert len(data) == 1

    datum = data[0]
    assert datum.weight_kg == weight
Exemplo n.º 3
0
    def run(self):
        dates = util.get_dates_between(self.start_date, self.end_date)
        with self.app.app_context():
            if not self.user_id:
                users = User.query.all()
            else:
                users = [User.get_default_user()]

        for user in users:
            for date in dates:
                try:
                    self.get_data_and_upsert(date, user)
                except Exception as e:
                    print(f"failed to get data for {user} on {date}")
                    logging.exception(e)
Exemplo n.º 4
0
def test_get_data_and_upsert(mock_googlefit_api):
    steps = 1
    distance = 2

    mock_googlefit_api.return_value = steps, distance
    user = User.get_default_user()
    date = datetime.date.today()  # doesn't matter what the day is
    PullRecentGoogleFitData().get_step_data_and_upsert(date, user)

    data = GoogleFitData.query.all()
    assert len(data) == 1

    datum = data[0]
    assert datum.step_count == steps
    assert datum.distance_metres == distance
Exemplo n.º 5
0
def test_get_most_recent_weight():
    # set up a couple of weights
    user = User.get_default_user()
    recent_data = WithingsData(user=user, date=datetime.date(2020, 1, 1))
    weight = WithingsData.get_most_recent_weight(user)
    assert weight is None

    past_data = WithingsData(user=user,
                             date=datetime.date(2019, 1, 1),
                             weight_kg=5)
    db.session.add(recent_data)
    db.session.add(past_data)
    db.session.commit()

    weight = WithingsData.get_most_recent_weight(user)
    assert weight == 5
Exemplo n.º 6
0
def fetch_token(name, user=None):
    if user is None:
        user = User.get_default_user()

    if name in current_app.config['OAUTH1_SERVICES']:
        model = OAuth1Token
    else:
        model = OAuth2Token

    token = model.query.filter_by(
        name=name,
        user=user
    ).first()
    if token:
        return token.to_token()
    else:
        return None
Exemplo n.º 7
0
def weight():
    user = User.get_default_user()
    weight_data = WithingsData.get_weight_datapoints_for_user(user)
    # that is an assumption. Let's do a sort
    earliest_date = sorted(weight_data, key=lambda x: x[0])[0][0]

    # TODO persist this in a DB
    runs = StravaAPI.get_run_data(user)

    #monthly_step_data = GoogleFitData.get_monthly_step_data(user, start_date=earliest_date)
    #formatted_step_data = [
    #    dict(x=date.replace(day=15).isoformat(), y=step_count) for date, step_count in monthly_step_data.items()
    #]

    weekly_step_data = GoogleFitData.get_weekly_step_data(
        user, start_date=earliest_date)
    formatted_step_data = [
        dict(x=date.isoformat(), y=step_count)
        for date, step_count in weekly_step_data.items()
    ]

    formatted_weight_data = [
        dict(x=date.isoformat(), y=convert_kg_to_lbs(weight_kg))
        for date, weight_kg in weight_data
    ]

    formatted_run_data = [
        dict(x=date.date().isoformat(), y=1) for date, distance_metres in runs
        if date.date() >= earliest_date
    ]

    # if I do >1 yoga session a day, this screws up the chart.
    # we need to just extract the dates.
    yoga_sessions = GoogleFitYoga.get_sessions(user, start_date=earliest_date)
    yoga_dates = set(session.date for session in yoga_sessions)
    formatted_yoga_data = [
        dict(x=yoga_date.isoformat(), y=1) for yoga_date in yoga_dates
        if yoga_date >= earliest_date
    ]
    context = {
        'weight_data': formatted_weight_data,
        'step_data': formatted_step_data,
        'run_data': formatted_run_data,
        'yoga_data': formatted_yoga_data,
    }
    return render_template('weight.html', **context)
Exemplo n.º 8
0
def login():
    if request.method == 'POST':
        # do login stuff
        email = request.form.get("email")
        password = request.form.get("password")
        # do login stuff, set cookie, etc, redirect to homepage, show "HI THERE" thing
        user = User.check_login(email, password)
        # TODO use forms,
        if user:
            login_user(user)
            return redirect(url_for("user.authorized_apps"))
        else:
            return render_template("login.html")
    else:
        if current_user.is_authenticated:
            return redirect(url_for("user.authorized_apps"))

        # show the login form,
        # TODO set CSRF cookie
        return render_template('login.html')
Exemplo n.º 9
0
def data():
    user = User.get_default_user()
    raw_stats, errors = StatCollector.get_collected_stats(user)

    # format the errors.
    error_messages = [str(e) for e in errors]

    stats = []

    for stat_group in ORDERED_STAT_GROUPS:
        populated_stats = _get_populated_stat_groups(raw_stats,
                                                     stat_group['stat_groups'])
        if populated_stats:
            stats.append({
                'stats': populated_stats,
                'description': stat_group['description'],
                'stat_group': stat_group['stat_group_id']
            })

    data = dict(stats=stats, error_messages=error_messages)

    return jsonify(data)