Ejemplo n.º 1
0
    def pull_by_goal_start_end(self, goal, start, end):
        """Return an array of check-ins given a goal ID and start date and an end date"""
        goal = Goal.pull_by_id(goal)
        timeframes = Timeframe.get_timeframes(goal.check_in_frequency_name, start, end)
        timeframes = [x.get_id() for x in timeframes]

        return self.pull_by_goal_timeframes(goal.get_id(), timeframes)
Ejemplo n.º 2
0
def get_goal(id):
    goal = Goal.pull_by_id(id)
    if (not goal):
        raise NotFoundError()

    if (not goal.public and goal.user != current_user.get_id()):
        raise UnauthorizedError()

    return goal.to_json(), HTTP_200_OK
Ejemplo n.º 3
0
def get_goal(id):
    goal = Goal.pull_by_id(id)
    if (not goal):
        raise NotFoundError()

    if (not goal.public and goal.user != current_user.get_id()):
        raise UnauthorizedError()

    return goal.to_json(), HTTP_200_OK
Ejemplo n.º 4
0
def update_goal():
    validate_form(request.form, ['id'])
    goal = Goal.pull_by_id(request.form['id'])
    if (not goal): 
        raise NotFoundError()
    if (goal.user != current_user.get_id()):
        raise UnauthorizedError()
    goal.update(request.form)

    return empty_ok()
Ejemplo n.º 5
0
def update_goal():
    validate_form(request.form, ['id'])
    goal = Goal.pull_by_id(request.form['id'])
    if (not goal):
        raise NotFoundError()
    if (goal.user != current_user.get_id()):
        raise UnauthorizedError()
    goal.update(request.form)

    return empty_ok()
Ejemplo n.º 6
0
    def test_persist(
            self):  ## This sorta also tests pull by ID and exists(), fwiw
        goal = self.create_test_goal()  ## Calls persist
        self.assertTrue(goal.exists())

        check = Goal.pull_by_id(goal.id)
        self.assertEqual(goal, check)

        with self.assertRaisesRegexp(goly.errors.ResourceAlreadyExistsError,
                                     "Unable to create goal"):
            goal.persist()
Ejemplo n.º 7
0
def get_check_in(id, tfid):
    """Get the check-in for a given timeframe.  Returns 404 if there is no check-in for that timeframe"""
    goal = Goal.pull_by_id(id)
    if (not goal):
        raise NotFoundError()
    
    if goal.user != current_user.get_id():
        raise UnauthorizedError
    
    check_in = CheckIn.pull_by_goal_timeframe(id, tfid)
    if (not check_in):
        raise NotFoundError()

    return check_in.to_json(), 200    
Ejemplo n.º 8
0
def get_current_check_in(id):
    """Get the current check-in for a given goal.  Returns 404 if the current check-in or goal does not exist"""
    goal = Goal.pull_by_id(id)
    if (not goal):
        raise NotFoundError()
    
    if goal.user != current_user.get_id():
        raise UnauthorizedError
    
    check_in = CheckIn.pull_by_goal_timeframe(id, Timeframe.get_current_timeframe(goal.check_in_frequency_name).get_id())
    if (not check_in):
        raise NotFoundError()

    return check_in.to_json(), 200
Ejemplo n.º 9
0
def check_in(id):
    validate_form(request.form, ["value"])
    goal = Goal.pull_by_id(id)
    if (not goal):
        raise NotFoundError()
    
    if goal.user != current_user.get_id():
        raise UnauthorizedError
    
    if ('timeframe' in request.form):
        timeframe = Timeframe.pull_by_id(request.form['timeframe'])
    else:
        timeframe = Timeframe.get_current_timeframe(goal.check_in_frequency_name)

    check_in = CheckIn(goal, timeframe, request.form['value'])
    return_code = 200 if check_in.exists() else 201
    check_in.persist()

    return check_in.to_json(), return_code
Ejemplo n.º 10
0
def get_by_time(id):
    goal = Goal.pull_by_id(id)
    if (not goal):
        raise NotFoundError()
    
    if goal.user != current_user.get_id():
        raise UnauthorizedError

    if (not 'start' in request.args or not 'end' in request.args):
        raise InvalidRequest(["start and end are required parameters"])

    try:
        start = datetime.datetime.strptime(request.args['start'], "%Y-%m-%d %H:%M:%S")
        end = datetime.datetime.strptime(request.args['end'], "%Y-%m-%d %H:%M:%S")
    except ValueError as e:
        raise InvalidRequest([e.message])

    check_ins = CheckIn.pull_by_goal_start_end(id, start, end)

    return jsonify({"check-ins": [check_in.to_dict() for check_in in check_ins]}), 200
Ejemplo n.º 11
0
    def test_create(self):
        # Requires login:
        res = self.test_client.post("/goals/create/", data=self.new_goal)
        setup.assertRequiresLogin(self, res)

        self.login()

        ## Test that it rejects bad inputs
        bad_goal = self.new_goal.copy()
        bad_goal['name'] = None
        res = self.test_client.post("/goals/create/", data=bad_goal)
        setup.assertInvalid(self, res, "name")

        bad_goal['name'] = self.new_goal['name']
        bad_goal['prompt'] = ""
        res = self.test_client.post("/goals/create/", data=bad_goal)

        setup.assertBadData(self, res,
                            "Prompt must be between 0 and 255 characters")

        ## Test that it actually registers at all :-)
        res = self.test_client.post("/goals/create/", data=self.new_goal)
        setup.assertOk(self, res, 201)
        data = json.loads(res.data)
        self.assertIn('id', data)
        goal = Goal.pull_by_id(data['id'])
        self.assertIsNotNone(goal)
        for key, val in self.new_goal.iteritems():
            self.assertEqual(val, data[key])
            if (key == 'frequency' or key == 'check_in_frequency'):
                self.assertEqual(val,
                                 Frequency.get_name_by_id(getattr(goal, key)))
            else:
                self.assertEqual(val, getattr(goal, key))

        ## Shouldn't be able to register something that already exists
        res = self.test_client.post("/goals/create/", data=self.new_goal)
        self.assertEqual(res.status_code, 409)
        data = json.loads(res.data)
        self.assertIn('detail', data)
        self.assertIn('Test goal already exists', data['detail'])
Ejemplo n.º 12
0
    def test_create(self):
        # Requires login:
        res = self.test_client.post("/goals/create/", data=self.new_goal)
        setup.assertRequiresLogin(self, res)

        self.login()

        ## Test that it rejects bad inputs
        bad_goal = self.new_goal.copy()
        bad_goal['name'] = None
        res = self.test_client.post("/goals/create/", data=bad_goal)
        setup.assertInvalid(self, res, "name")

        bad_goal['name'] = self.new_goal['name']
        bad_goal['prompt'] = "" 
        res = self.test_client.post("/goals/create/", data=bad_goal)

        setup.assertBadData(self, res, "Prompt must be between 0 and 255 characters")

        ## Test that it actually registers at all :-)
        res = self.test_client.post("/goals/create/", data=self.new_goal)
        setup.assertOk(self, res, 201)
        data = json.loads(res.data)
        self.assertIn('id', data)
        goal = Goal.pull_by_id(data['id'])
        self.assertIsNotNone(goal)
        for key, val in self.new_goal.iteritems():
            self.assertEqual(val, data[key])
            if (key == 'frequency' or key == 'check_in_frequency'):
                self.assertEqual(val, Frequency.get_name_by_id(getattr(goal, key)))
            else:
                self.assertEqual(val, getattr(goal, key))

        ## Shouldn't be able to register something that already exists
        res = self.test_client.post("/goals/create/", data=self.new_goal)
        self.assertEqual(res.status_code, 409)
        data = json.loads(res.data)
        self.assertIn('detail', data)
        self.assertIn('Test goal already exists', data['detail'])
Ejemplo n.º 13
0
    def test_update(self):
        ## Requires login
        res = self.test_client.post("/goals/update/", data={'id': 0})
        setup.assertRequiresLogin(self, res)

        ## Validates form
        self.login()
        res = self.test_client.post("/goals/update/", data={'favorite_muppet': 'kermit'})
        setup.assertInvalid(self, res, 'id')        
        
        ## 404's
        res = self.test_client.post("/goals/update/", data={'id': 0, 'name': 'test goal 2.0'})
        setup.assert404(self, res)

        ## Actually works
        goal = self.create_test_goal()
        data = {'id': goal['id']}
        data['name'] = "Test Goal 2.0"
        data['prompt'] = "Guess how many eggs I had for breakfast today!"
        data['frequency'] = "monthly"
        data['target'] = 100
        data['input_type'] = "binary"
        data['active'] = False
        data['public'] = True
        data['check_in_frequency'] = "daily"
        
        res = self.test_client.post("/goals/update/", data=data)
        setup.assertOk(self, res, 200)

        updated_goal = Goal.pull_by_id(goal['id'])
        for key, val in data.iteritems():
            if (key == 'frequency' or key == 'check_in_frequency'):
                self.assertEqual(Frequency.get_name_by_id(getattr(updated_goal, key)), val)
            else:
                self.assertEqual(getattr(updated_goal, key), val)

        ## If any part is invalid, no part should go through
        bad_data = {'id': goal['id']}
        bad_data['name'] = "Test Goal 3.0"
        bad_data['prompt'] = "How many jars of sand did you collect?"
        bad_data['frequency'] = "daily"
        bad_data['target'] = 1000
        bad_data['input_type'] = "numeric"
        bad_data['active'] = True
        bad_data['public'] = "banana"
        bad_data['check_in_frequency'] = "daily"

        res = self.test_client.post("/goals/update/", data=bad_data)
        setup.assertBadData(self, res, "Public must be a boolean")
        updated_goal = Goal.pull_by_id(goal['id'])
        for key, val in data.iteritems():
            if (key == 'frequency' or key == 'check_in_frequency'):
                self.assertEqual(Frequency.get_name_by_id(getattr(updated_goal, key)), val)
            else:
                self.assertEqual(getattr(updated_goal, key), val)

        
        ## Can't update someone else's goal
        self.logout()
        self.login_other_user()
        res = self.test_client.post("/goals/update/", data=bad_data) ## using bad_data here ensures we don't update
        setup.assertInvalidCredentials(self, res)
Ejemplo n.º 14
0
    def test_update(self):
        ## Requires login
        res = self.test_client.post("/goals/update/", data={'id': 0})
        setup.assertRequiresLogin(self, res)

        ## Validates form
        self.login()
        res = self.test_client.post("/goals/update/",
                                    data={'favorite_muppet': 'kermit'})
        setup.assertInvalid(self, res, 'id')

        ## 404's
        res = self.test_client.post("/goals/update/",
                                    data={
                                        'id': 0,
                                        'name': 'test goal 2.0'
                                    })
        setup.assert404(self, res)

        ## Actually works
        goal = self.create_test_goal()
        data = {'id': goal['id']}
        data['name'] = "Test Goal 2.0"
        data['prompt'] = "Guess how many eggs I had for breakfast today!"
        data['frequency'] = "monthly"
        data['target'] = 100
        data['input_type'] = "binary"
        data['active'] = False
        data['public'] = True
        data['check_in_frequency'] = "daily"

        res = self.test_client.post("/goals/update/", data=data)
        setup.assertOk(self, res, 200)

        updated_goal = Goal.pull_by_id(goal['id'])
        for key, val in data.iteritems():
            if (key == 'frequency' or key == 'check_in_frequency'):
                self.assertEqual(
                    Frequency.get_name_by_id(getattr(updated_goal, key)), val)
            else:
                self.assertEqual(getattr(updated_goal, key), val)

        ## If any part is invalid, no part should go through
        bad_data = {'id': goal['id']}
        bad_data['name'] = "Test Goal 3.0"
        bad_data['prompt'] = "How many jars of sand did you collect?"
        bad_data['frequency'] = "daily"
        bad_data['target'] = 1000
        bad_data['input_type'] = "numeric"
        bad_data['active'] = True
        bad_data['public'] = "banana"
        bad_data['check_in_frequency'] = "daily"

        res = self.test_client.post("/goals/update/", data=bad_data)
        setup.assertBadData(self, res, "Public must be a boolean")
        updated_goal = Goal.pull_by_id(goal['id'])
        for key, val in data.iteritems():
            if (key == 'frequency' or key == 'check_in_frequency'):
                self.assertEqual(
                    Frequency.get_name_by_id(getattr(updated_goal, key)), val)
            else:
                self.assertEqual(getattr(updated_goal, key), val)

        ## Can't update someone else's goal
        self.logout()
        self.login_other_user()
        res = self.test_client.post(
            "/goals/update/",
            data=bad_data)  ## using bad_data here ensures we don't update
        setup.assertInvalidCredentials(self, res)
Ejemplo n.º 15
0
    def test_update(self):
        goal = self.create_test_goal()

        with self.assertRaisesRegexp(goly.errors.ResourceAlreadyExistsError,
                                     "Unable to create goal"):
            goal.update({"name": goal.name})

        data = {
            "name": "New test name",
            "prompt": "New test prompt",
            "frequency": "yearly",
            "check_in_frequency": "quarterly",
            "target": 100,
            "input_type": "numeric",
            "active": False,
            "public": True
        }

        goal.update(data)

        for attr, name in data.iteritems():
            if (attr in ['check_in_frequency', 'frequency']):
                self.assertEqual(Frequency.get_name_by_id(getattr(goal, attr)),
                                 data[attr])
            else:
                self.assertEqual(getattr(goal, attr), data[attr])

        check = Goal.pull_by_id(goal.get_id())  ## make sure these persisted

        for attr, name in data.iteritems():
            if (attr in ['check_in_frequency', 'frequency']):
                self.assertEqual(Frequency.get_name_by_id(getattr(goal, attr)),
                                 data[attr])
            else:
                self.assertEqual(getattr(goal, attr), data[attr])

        with self.assertRaisesRegexp(AssertionError,
                                     "Name must be between 0 and 50"):
            goal.update({"name": " "})

        with self.assertRaisesRegexp(AssertionError,
                                     "Name must be between 0 and 50"):
            goal.update({"name": "a" * 51})

        with self.assertRaisesRegexp(AssertionError,
                                     "Prompt must be between 0 and 255"):
            goal.update({"prompt": " "})

        with self.assertRaisesRegexp(AssertionError,
                                     "Prompt must be between 0 and 255"):
            goal.update({"prompt": "a" * 256})

        with self.assertRaisesRegexp(AssertionError,
                                     "frequency must be one of "):
            goal.update({"frequency": "not-an-option"})

        with self.assertRaisesRegexp(AssertionError,
                                     "Target must be an integer"):
            goal.update({"target": "banana"})

        with self.assertRaisesRegexp(AssertionError,
                                     "Input type must be binary or numeric"):
            goal.update({"input_type": "pineapple"})

        with self.assertRaisesRegexp(AssertionError,
                                     "Active must be a boolean"):
            goal.update({'active': "fish"})

        with self.assertRaisesRegexp(AssertionError,
                                     "Public must be a boolean"):
            goal.update({"public": "filet"})

        with self.assertRaisesRegexp(AssertionError,
                                     "check_in_frequency must be one of"):
            goal.update(
                {"check_in_frequency": "whenever I feel like it, gosh"})

        with self.assertRaisesRegexp(AssertionError,
                                     "Check-in frequency must conform"):
            goal.update({"check_in_frequency": "weekly"})
Ejemplo n.º 16
0
 def reconstruct(self):
     self.goal_obj = Goal.pull_by_id(self.goal)
     self.timeframe_obj = Timeframe.pull_by_id(self.timeframe)