def test_to_json(self):
     g = Goal(name="Goal 1", target="10")
     db.session.add(g)
     db.session.commit()
     with self.app.test_request_context("/"):
         json_goal = g.to_json()
     expected_keys = ["id", "name", "target", "timestamp", "instances"]
     self.assertEqual(sorted(json_goal.keys()), sorted(expected_keys))
 def test_goals_to_json(self):
     u = User(email="*****@*****.**", password="******")
     g1 = Goal(author_id=1, name="Goal 1")
     g2 = Goal(author_id=1, name="Goal 2")
     db.session.add(u)
     db.session.add(g1)
     db.session.add(g2)
     db.session.commit()
     expected_keys = ["id", "name", "target", "timestamp", "instances"]
     for json_goal in u.goals_to_json():
         self.assertEqual(sorted(json_goal.keys()), sorted(expected_keys))
 def test_goals_property(self):
     u = User(email="*****@*****.**", password="******")
     g1 = Goal(author_id=1, name="Goal 1")
     db.session.add(u)
     db.session.add(g1)
     db.session.commit()
     self.assertEqual(len(u.goals), 1)
     g2 = Goal(author_id=1, name="Goal 2")
     db.session.add(g2)
     db.session.commit()
     self.assertEqual(len(u.goals), 2)
Exemple #4
0
def save_objectives(profile):
    """ Save objective data. """
    objective1 = Goal(description="Test Objective 1", goal_profile=profile)
    objective1.save()
    objective2 = Goal(description="Test Objective 2", goal_profile=profile)
    objective2.save()
    objective3 = Goal(description="Test Objective 3", goal_profile=profile)
    objective3.save()
    return objective1, objective2, objective3
    def post(self):
        """Create a new goal"""
        request_body = request.get_json(force=True)
        self.goals_logger.info('Start to create a new goal')
        self.goals_logger.debug('The request body is: %s', request_body)

        goal, error = goal_schema.load(request_body)
        goal["assignee"] = "Global"
        self.goals_logger.error(goal)
        # if error:
        #     self.goals_logger.error("Schema load error, check your request body!")
        #     return goal, 500

        # print("The goal body is : ", file=sys.stderr)
        # print(goal_schema.dump(goal), file=sys.stderr)

        contributors = User.objects(role="contributor")
        len_contributors = len(contributors)
        total_goals = request_body["total_number"]
        if (len_contributors != 0):
            personal_total_goals = int(total_goals / len_contributors)
            self.goals_logger.debug('The personal total goals numbers is: %s',
                                    personal_total_goals)

            mark_idx = total_goals % len_contributors

            for c, contributor in enumerate(contributors):
                assignee_id = str(contributor.id)
                user = User.objects.get_or_404(id=contributor.id)
                user_name = user.first_name + ' ' + user.last_name
                self.goals_logger.debug("Start to create goal for %s",
                                        assignee_id)

                personal_goal = Goal(verticals=request_body["verticals"],
                                     assignee_id=assignee_id,
                                     assignee=user_name,
                                     deadline=request_body["deadline"],
                                     total_number=personal_total_goals)
                if c < mark_idx:
                    personal_goal.total_number = personal_total_goals + 1

                personal_goal = personal_goal.save()
                goal.personal_goals.append(str(personal_goal.id))

        try:
            new_goal = goal.save()
            self.goals_logger.info('The new global goal has been saved!')
        except Exception as e:
            self.goals_logger.error("Fail to save, %s", str(e))
            return str(e), 400
        # TODO: Fan -- why there is two elements in the return lists?
        return goal_schema.dump(new_goal), 200
    def test_goal_instance(self):
        g = Goal(id=1, name="Goal 1")
        db.session.add(g)
        db.session.commit()
        # Unsuccessful goal instance creation
        response = self.client.post("/goals/new-goal-instance",
                                    headers=self.get_api_headers(),
                                    data=json.dumps({}))
        self.assertEqual(response.status_code, 400)
        json_response = json.loads(response.get_data(as_text=True))
        self.assertEqual(json_response["message"],
                         "Goal instance does not have a goal ID")

        response = self.client.post("/goals/new-goal-instance",
                                    headers=self.get_api_headers(),
                                    data=json.dumps({"goal_id": ""}))
        self.assertEqual(response.status_code, 400)
        json_response = json.loads(response.get_data(as_text=True))
        self.assertEqual(json_response["message"],
                         "Goal instance does not have a goal ID")

        response = self.client.post("/goals/new-goal-instance",
                                    headers=self.get_api_headers(),
                                    data=json.dumps({"goal_id": "1"}))
        self.assertEqual(response.status_code, 201)
        json_response = json.loads(response.get_data(as_text=True))
        expected_keys = ["id", "name", "target", "timestamp", "instances"]
        self.assertEqual(sorted(json_response.keys()), sorted(expected_keys))
    def put(self):
        """Return a list of goals with filters"""
        filters = request.get_json(force=True)
        self.goals_logger.info('info Return a list of goals with filters: ')
        self.goals_logger.info(filters)

        goals = Goal.objects(__raw__=filters)
        return goals_schema.dump(goals)
 def test_from_json(self):
     json_goal = {"name": "Goal 1"}
     with self.assertRaises(ValidationError):
         Goal.from_json(json_goal)
     json_goal = {"name": "Goal 1", "target": ""}
     with self.assertRaises(ValidationError):
         Goal.from_json(json_goal)
     json_goal = {"name": "", "target": "10"}
     with self.assertRaises(ValidationError):
         Goal.from_json(json_goal)
     json_goal = {"target": "10"}
     with self.assertRaises(ValidationError):
         Goal.from_json(json_goal)
     json_goal = {"name": "Goal 1", "target": "10"}
     g = Goal.from_json(json_goal)
     self.assertTrue(isinstance(g, Goal))
 def test_instances_property(self):
     g = Goal(name="Goal 1", target="10")
     gi1 = GoalInstance(goal_id=1)
     db.session.add(g)
     db.session.add(gi1)
     db.session.commit()
     self.assertEqual(len(g.instances), 1)
     gi2 = GoalInstance(goal_id=1)
     db.session.add(gi2)
     db.session.commit()
     self.assertEqual(len(g.instances), 2)
    def patch(self, goal_id):
        """Update a goal"""
        print("Start to update a new goal ", file=sys.stderr)
        goal = Goal.objects.get_or_404(id=goal_id)

        goal_patch = request.get_json(force=True)
        try:
            goal.update(**goal_patch)
            self.goal_logger.debug('The goal has been changed!')
        except Exception as e:
            return str(e), 400

        self.goal_logger.info(
            'Check if need to change the total goal number..')
        try:
            new_total_number = goal_patch["total_number"]
            self.goal_logger.debug('The total number has been changed to %s',
                                   new_total_number)
        except Exception as e:
            self.goal_logger.debug('The total goals number has no change')
            new_total_number = goal.total_number

        self.goal_logger.info('start to update personal goals')
        if goal.personal_goals:

            self.goal_logger.debug("show change content json: %s", goal_patch)

            personal_total_goals = int(new_total_number /
                                       len(goal.personal_goals))
            mark_idx = new_total_number % len(goal.personal_goals)

            for c, goal_id in enumerate(goal.personal_goals):
                self.goal_logger.debug("idx: %d, goal_id: %s", c, goal_id)

                personal_goal = Goal.objects(id=str(goal_id))

                self.goal_logger.debug("Personal goal %s has been fetched",
                                       personal_goal)

                if c < mark_idx:
                    goal_patch["total_number"] = personal_total_goals + 1
                else:
                    goal_patch["total_number"] = personal_total_goals

                self.goal_logger.debug("The new goal patch is: %s", goal_patch)

                personal_goal.update(**goal_patch)

        self.goal_logger.debug("Global and personal goals have been changed",
                               goal_patch)
        return 200
    def test_get_user(self):
        u = User(email="*****@*****.**", password="******")
        db.session.add(u)
        db.session.commit()
        # Request for a user id that does not exist
        response = self.client.get("/users/2", headers=self.get_api_headers())
        self.assertEqual(response.status_code, 404)

        # Request for a valid user id with no goals
        response = self.client.get("/users/1", headers=self.get_api_headers())
        self.assertEqual(response.status_code, 200)
        json_response = json.loads(response.get_data(as_text=True))
        self.assertEqual(len(json_response), 0)

        g1 = Goal(author_id=1, name="Goal 1")
        g2 = Goal(author_id=1, name="Goal 2")
        db.session.add(g1)
        db.session.add(g2)
        db.session.commit()
        # Request for a valid user id with two goals
        response = self.client.get("/users/1", headers=self.get_api_headers())
        self.assertEqual(response.status_code, 200)
        json_response = json.loads(response.get_data(as_text=True))
        self.assertEqual(len(json_response), 2)
        expected_keys = ["id", "name", "target", "timestamp", "instances"]
        for json_goal in json_response:
            self.assertEqual(sorted(json_goal.keys()), sorted(expected_keys))

        g3 = Goal(author_id=2, name="Goal 3")
        db.session.add(g3)
        db.session.commit()
        # The endpoint doesn't return goals that belong to other users
        response = self.client.get("/users/1", headers=self.get_api_headers())
        self.assertEqual(response.status_code, 200)
        json_response = json.loads(response.get_data(as_text=True))
        self.assertEqual(len(json_response), 2)
        for json_goal in json_response:
            self.assertTrue(json_goal["name"] != "Goal 3")
    def test_goal(self):
        u = User(email="*****@*****.**", password="******")
        db.session.add(u)
        db.session.commit()
        # Submit a goal that lacks information
        response = self.client.post("/goals/new-goal",
                                    headers=self.get_api_headers(),
                                    data=json.dumps({}))
        self.assertEqual(response.status_code, 400)
        json_response = json.loads(response.get_data(as_text=True))
        self.assertEqual(json_response["message"], "Goal does not have a name")

        response = self.client.post("/goals/new-goal",
                                    headers=self.get_api_headers(),
                                    data=json.dumps({"name": ""}))
        self.assertEqual(response.status_code, 400)
        json_response = json.loads(response.get_data(as_text=True))
        self.assertEqual(json_response["message"], "Goal does not have a name")

        response = self.client.post("/goals/new-goal",
                                    headers=self.get_api_headers(),
                                    data=json.dumps({"target": ""}))
        self.assertEqual(response.status_code, 400)
        json_response = json.loads(response.get_data(as_text=True))
        self.assertEqual(json_response["message"], "Goal does not have a name")

        response = self.client.post("/goals/new-goal",
                                    headers=self.get_api_headers(),
                                    data=json.dumps({"name": "Goal 1"}))
        self.assertEqual(response.status_code, 400)
        json_response = json.loads(response.get_data(as_text=True))
        self.assertEqual(json_response["message"],
                         "Goal does not have a target")

        response = self.client.post("/goals/new-goal",
                                    headers=self.get_api_headers(),
                                    data=json.dumps({
                                        "name": "Goal 1",
                                        "target": ""
                                    }))
        self.assertEqual(response.status_code, 400)
        json_response = json.loads(response.get_data(as_text=True))
        self.assertEqual(json_response["message"],
                         "Goal does not have a target")

        # Successful goal submission
        response = self.client.post("/goals/new-goal",
                                    headers=self.get_api_headers(),
                                    data=json.dumps({
                                        "name": "Goal 1",
                                        "target": "10"
                                    }))
        self.assertEqual(response.status_code, 201)
        json_response = json.loads(response.get_data(as_text=True))
        expected_keys = ["id", "name", "target", "timestamp", "instances"]
        self.assertEqual(sorted(json_response.keys()), sorted(expected_keys))

        # Unsuccessful goal deletion
        response = self.client.post("/goals/delete-goal/2",
                                    headers=self.get_api_headers())
        self.assertEqual(response.status_code, 404)

        gi = GoalInstance(goal_id=1)
        db.session.add(gi)
        db.session.commit()
        # Successful goal deletion
        self.assertEqual(len(GoalInstance.query.all()), 1)
        # Currently broken while login functionality is being implemented
        # response = self.client.post(
        #     "/goals/delete-goal/1",
        #     headers=self.get_api_headers()
        # )
        # self.assertEqual(response.status_code, 200)
        # print(Goal.query.filter_by(id=1).first())
        # self.assertEqual(len(GoalInstance.query.all()), 0)

        g = Goal(name="Goal 1", target="10")
        db.session.add(g)
        db.session.commit()
 def test_date_property(self):
     g = Goal(name="Goal 1", target="10")
     db.session.add(g)
     db.session.commit()
     self.assertTrue(isinstance(g.date, str))