Beispiel #1
0
    def test_user_progress_anonymous(self):
        """Test API userprogress as anonymous works"""
        user = UserFactory.create()
        project = ProjectFactory.create(owner=user)
        tasks = TaskFactory.create_batch(2, project=project)
        taskruns = []
        for task in tasks:
            taskruns.extend(AnonymousTaskRunFactory.create_batch(2, task=task))

        res = self.app.get('/api/project/1/userprogress', follow_redirects=True)
        data = json.loads(res.data)

        error_msg = "The reported total number of tasks is wrong"
        assert len(tasks) == data['total'], error_msg

        error_msg = "The reported number of done tasks is wrong"
        assert len(taskruns) == data['done'], data

        # Add a new TaskRun and check again
        taskrun = AnonymousTaskRunFactory.create(task=tasks[0], info={'answer': u'hello'})

        res = self.app.get('/api/project/1/userprogress', follow_redirects=True)
        data = json.loads(res.data)
        error_msg = "The reported total number of tasks is wrong"
        assert len(tasks) == data['total'], error_msg

        error_msg = "Number of done tasks is wrong: %s" % len(taskruns)
        assert len(taskruns) + 1 == data['done'], error_msg
    def test_anonymous_user_create_repeated_taskrun(self):
        """Test anonymous user cannot create two taskruns for the same task"""
        task = TaskFactory.create()
        taskrun1 = AnonymousTaskRunFactory.create(task=task)
        taskrun2 = AnonymousTaskRunFactory.build(task=task)

        assert_raises(Forbidden, ensure_authorized_to, 'create', taskrun2)
    def test_n_total_task_runs_site_returns_total_number_of_answers(self):
        AnonymousTaskRunFactory.create()
        TaskRunFactory.create()

        task_runs = stats.n_task_runs_site()

        assert task_runs == 2, task_runs
Beispiel #4
0
 def test_webhook_handler_all(self, q):
     """Test WEBHOOK requeing all works."""
     self.register()
     user = user_repo.get(1)
     project = ProjectFactory.create(owner=user, webhook='server')
     task = TaskFactory.create(project=project, n_answers=1)
     AnonymousTaskRunFactory.create(project=project, task=task)
     payload = self.payload(project, task)
     wh1 = Webhook(project_id=project.id, payload=payload,
                  response='error', response_status_code=500)
     webhook_repo.save(wh1)
     wh2 = Webhook(project_id=project.id, payload=payload,
                   response='ok', response_status_code=200)
     webhook_repo.save(wh2)
     wh3 = Webhook(project_id=project.id, payload=payload,
                   response='ok', response_status_code=200)
     webhook_repo.save(wh3)
     whs = webhook_repo.filter_by(project_id=project.id)
     url = "/project/%s/webhook?all=true" % (project.short_name)
     res = self.app.get(url)
     assert res.status_code == 200, res.status_code
     calls = []
     for w in whs:
         calls.append(call(webhook, project.webhook,
                           w.payload, w.id, True))
     q.assert_has_calls(calls)
Beispiel #5
0
    def test_user_progress_anonymous(self):
        """Test API userprogress as anonymous works"""
        user = UserFactory.create()
        app = AppFactory.create(owner=user)
        tasks = TaskFactory.create_batch(2, app=app)
        for task in tasks:
            taskruns = AnonymousTaskRunFactory.create_batch(2, task=task)
        taskruns = db.session.query(TaskRun)\
                     .filter(TaskRun.app_id == app.id)\
                     .filter(TaskRun.user_ip == '127.0.0.1')\
                     .all()

        res = self.app.get('/api/app/1/userprogress', follow_redirects=True)
        data = json.loads(res.data)

        error_msg = "The reported total number of tasks is wrong"
        assert len(tasks) == data['total'], error_msg

        error_msg = "The reported number of done tasks is wrong"
        assert len(taskruns) == data['done'], data

        # Add a new TaskRun and check again
        taskrun = AnonymousTaskRunFactory.create(task=tasks[0], info={'answer': u'hello'})

        res = self.app.get('/api/app/1/userprogress', follow_redirects=True)
        data = json.loads(res.data)
        error_msg = "The reported total number of tasks is wrong"
        assert len(tasks) == data['total'], error_msg

        error_msg = "Number of done tasks is wrong: %s" % len(taskruns)
        assert len(taskruns) + 1 == data['done'], error_msg
Beispiel #6
0
    def test_anonymous_user_create_repeated_taskrun(self):
        """Test anonymous user cannot create a taskrun for a task to which
        he has previously posted a taskrun"""
        task = TaskFactory.create()
        taskrun1 = AnonymousTaskRunFactory.create(task=task)
        taskrun2 = AnonymousTaskRunFactory.build(task=task)

        assert_raises(Forbidden, ensure_authorized_to, 'create', taskrun2)
 def test_stats_users(self):
     """Test CACHE PROJECT STATS user stats works."""
     pr = ProjectFactory.create()
     TaskRunFactory.create(project=pr)
     AnonymousTaskRunFactory.create(project=pr)
     users, anon_users, auth_users = stats_users(pr.id)
     assert len(users) == 2, len(users)
     assert len(anon_users) == 1, len(anon_users)
     assert len(auth_users) == 1, len(auth_users)
Beispiel #8
0
    def test_anonymous_user_create_repeated_taskrun(self):
        """Test anonymous user cannot create a taskrun for a task to which
        he has previously posted a taskrun"""

        task = TaskFactory.create()
        taskrun1 = AnonymousTaskRunFactory.create(task=task)
        taskrun2 = AnonymousTaskRunFactory.build(task=task)
        assert_raises(Forbidden,
                    getattr(require, 'taskrun').create,
                    taskrun2)
Beispiel #9
0
    def test_anonymous_user_create_taskrun(self):
        """Test anonymous user can create a taskrun for a task even though
        he has posted taskruns for different tasks in the same project"""

        tasks = TaskFactory.create_batch(2)
        taskrun1 = AnonymousTaskRunFactory.create(task=tasks[0])
        taskrun2 = AnonymousTaskRunFactory.build(task_id=tasks[1].id)

        assert_not_raises(Exception,
                          ensure_authorized_to, 'create', taskrun2)
 def create_mock_ip_addresses(self, geoip_mock):
     geoip_instance = MagicMock()
     locs = [{'latitude': 1, 'longitude': 1, 'country_name': 'England',
              'city': 'London', 'continent': 'Europe'},
             {'latitude': 2, 'longitude': 2, 'country_name': 'France',
              'city': 'Paris', 'continent': 'Europe'}]
     geoip_instance.record_by_addr.side_effect = locs
     geoip_mock.return_value = geoip_instance
     AnonymousTaskRunFactory.create(info={'ip_address': '1.1.1.1'})
     TaskRunFactory.create(info={'ip_address': '2.2.2.2'})
 def test_stats_users_with_period(self):
     """Test CACHE PROJECT STATS user stats with period works."""
     pr = ProjectFactory.create()
     d = date.today() - timedelta(days=6)
     TaskRunFactory.create(project=pr, created=d, finish_time=d)
     d = date.today() - timedelta(days=16)
     AnonymousTaskRunFactory.create(project=pr, created=d, finish_time=d)
     users, anon_users, auth_users = stats_users(pr.id, '1 week')
     assert len(users) == 2, len(users)
     assert len(anon_users) == 0, len(anon_users)
     assert len(auth_users) == 1, len(auth_users)
Beispiel #12
0
 def test_webhook_handler_post_oid_404(self):
     """Test WEBHOOK post oid 404 works."""
     self.register()
     user = user_repo.get(1)
     project = ProjectFactory.create(owner=user)
     task = TaskFactory.create(project=project, n_answers=1)
     AnonymousTaskRunFactory.create(project=project, task=task)
     payload = self.payload(project, task)
     webhook = Webhook(project_id=project.id, payload=payload,
                       response='OK', response_status_code=200)
     webhook_repo.save(webhook)
     url = "/project/%s/webhook/%s" % (project.short_name, 9999)
     res = self.app.post(url)
     assert res.status_code == 404, res.status_code
 def test_stats_dates(self):
     """Test CACHE PROJECT STATS date works."""
     pr = ProjectFactory.create()
     task = TaskFactory.create(project=pr, n_answers=1)
     today = datetime.now(pytz.utc)
     TaskFactory.create()
     TaskRunFactory.create(project=pr, task=task)
     AnonymousTaskRunFactory.create(project=pr)
     dates, dates_anon, dates_auth = stats_dates(pr.id)
     assert len(dates) == 15, len(dates)
     assert len(dates_anon) == 15, len(dates_anon)
     assert len(dates_auth) == 15, len(dates_auth)
     assert dates[today.strftime('%Y-%m-%d')] == 1
     assert dates_anon[today.strftime('%Y-%m-%d')] == 1
     assert dates_auth[today.strftime('%Y-%m-%d')] == 1
 def test_stats_dates_with_period(self):
     """Test CACHE PROJECT STATS dates with period works."""
     pr = ProjectFactory.create()
     d = date.today() - timedelta(days=6)
     task = TaskFactory.create(project=pr, n_answers=1, created=d)
     TaskRunFactory.create(project=pr, task=task, created=d, finish_time=d)
     dd = date.today() - timedelta(days=16)
     AnonymousTaskRunFactory.create(project=pr, created=dd, finish_time=dd)
     dates, dates_anon, dates_auth = stats_dates(pr.id, '1 week')
     assert len(dates) == 7, len(dates)
     assert len(dates_anon) == 7, len(dates_anon)
     assert len(dates_auth) == 7, len(dates_auth)
     assert dates[d.strftime('%Y-%m-%d')] == 1
     assert dates_anon[d.strftime('%Y-%m-%d')] == 0
     assert dates_auth[d.strftime('%Y-%m-%d')] == 1
Beispiel #15
0
    def test_admin_update_anonymous_taskrun(self):
        """Test admins cannot update anonymously posted taskruns"""

        anonymous_taskrun = AnonymousTaskRunFactory.create()

        assert_raises(Forbidden,
                      ensure_authorized_to, 'update', anonymous_taskrun)
Beispiel #16
0
    def test_authenticated_user_delete_anonymous_taskrun(self):
        """Test authenticated users cannot delete an anonymously posted taskrun"""

        anonymous_taskrun = AnonymousTaskRunFactory.create()

        assert_raises(Forbidden,
                      ensure_authorized_to, 'delete', anonymous_taskrun)
Beispiel #17
0
    def test_anonymous_02_gets_different_tasks(self):
        """ Test SCHED newtask returns N different Tasks for the Anonymous User"""
        assigned_tasks = []
        # Get a Task until scheduler returns None
        project = ProjectFactory.create()
        tasks = TaskFactory.create_batch(3, project=project, info={})
        res = self.app.get('api/project/%s/newtask' %project.id)
        data = json.loads(res.data)
        while data.get('info') is not None:
            # Save the assigned task
            assigned_tasks.append(data)

            task = db.session.query(Task).get(data['id'])
            # Submit an Answer for the assigned task
            tr = AnonymousTaskRunFactory.create(project=project, task=task)
            res = self.app.get('api/project/%s/newtask' %project.id)
            data = json.loads(res.data)

        # Check if we received the same number of tasks that the available ones
        assert len(assigned_tasks) == len(tasks), len(assigned_tasks)
        # Check if all the assigned Task.id are equal to the available ones
        err_msg = "Assigned Task not found in DB Tasks"
        for at in assigned_tasks:
            assert self.is_task(at['id'], tasks), err_msg
        # Check that there are no duplicated tasks
        err_msg = "One Assigned Task is duplicated"
        for at in assigned_tasks:
            assert self.is_unique(at['id'], assigned_tasks), err_msg
Beispiel #18
0
    def test_anonymous_user_update_anoymous_taskrun(self):
        """Test anonymous users cannot update an anonymously posted taskrun"""

        anonymous_taskrun = AnonymousTaskRunFactory.create()

        assert_raises(Unauthorized,
                      ensure_authorized_to, 'update', anonymous_taskrun)
Beispiel #19
0
    def test_anonymous_user_create_first_taskrun(self):
        """Test anonymous user can create a taskrun for a given task if he
        hasn't already done it"""
        task = TaskFactory.create()
        taskrun = AnonymousTaskRunFactory.build(task=task)

        assert_not_raises(Exception, ensure_authorized_to, 'create', taskrun)
Beispiel #20
0
    def test_admin_delete_anonymous_taskrun(self):
        """Test admins can delete anonymously posted taskruns"""

        anonymous_taskrun = AnonymousTaskRunFactory.create()

        assert_not_raises(Exception,
                          ensure_authorized_to, 'delete', anonymous_taskrun)
Beispiel #21
0
    def test_anonymous_user_read(self):
        """Test anonymous user can read any taskrun"""
        anonymous_taskrun = AnonymousTaskRunFactory.create()
        user_taskrun = TaskRunFactory.create()

        assert_not_raises(Exception,
                          ensure_authorized_to, 'read', anonymous_taskrun)
        assert_not_raises(Exception, ensure_authorized_to, 'read', user_taskrun)
Beispiel #22
0
    def test_anonymous_user_create_taskrun_non_allow_anonymous_contrib(self):
        """Test anonymous user cannot create a taskrun for a project that does
        not allow for anonymous contributors"""
        project = ProjectFactory.create(allow_anonymous_contributors=False)
        task = TaskFactory.create(project=project)
        taskrun = AnonymousTaskRunFactory.build(task=task)

        assert_raises(Unauthorized, ensure_authorized_to, 'create', taskrun)
Beispiel #23
0
    def test_admin_update_anonymous_taskrun(self):
        """Test admins cannot update anonymously posted taskruns"""

        anonymous_taskrun = AnonymousTaskRunFactory.create()

        assert_raises(Forbidden,
                      getattr(require, 'taskrun').update,
                      anonymous_taskrun)
Beispiel #24
0
    def test_authenticated_user_delete_anonymous_taskrun(self):
        """Test authenticated users cannot delete an anonymously posted taskrun"""

        anonymous_taskrun = AnonymousTaskRunFactory.create()

        assert_raises(Forbidden,
                      getattr(require, 'taskrun').delete,
                      anonymous_taskrun)
Beispiel #25
0
    def test_anonymous_user_delete_anonymous_taskrun(self):
        """Test anonymous users cannot delete an anonymously posted taskrun"""

        anonymous_taskrun = AnonymousTaskRunFactory.create()

        assert_raises(Unauthorized,
                      getattr(require, 'taskrun').delete,
                      anonymous_taskrun)
Beispiel #26
0
    def test_admin_delete_anonymous_taskrun(self):
        """Test admins can delete anonymously posted taskruns"""

        anonymous_taskrun = AnonymousTaskRunFactory.create()

        assert_not_raises(Exception,
                      getattr(require, 'taskrun').delete,
                      anonymous_taskrun)
 def test_stats_hours(self):
     """Test CACHE PROJECT STATS hours works."""
     pr = ProjectFactory.create()
     task = TaskFactory.create(n_answers=1)
     today = datetime.now(pytz.utc)
     TaskFactory.create()
     TaskRunFactory.create(project=pr, task=task)
     AnonymousTaskRunFactory.create(project=pr)
     hours, hours_anon, hours_auth, max_hours, \
         max_hours_anon, max_hours_auth = stats_hours(pr.id)
     assert len(hours) == 24, len(hours)
     assert hours[today.strftime('%H')] == 2, hours[today.strftime('%H')]
     assert hours_anon[today.strftime('%H')] == 1, hours_anon[today.strftime('%H')]
     assert hours_auth[today.strftime('%H')] == 1, hours_auth[today.strftime('%H')]
     assert max_hours == 2
     assert max_hours_anon == 1
     assert max_hours_auth == 1
Beispiel #28
0
    def test_authenticated_user_update_anonymous_taskrun(self):
        """Test authenticated users cannot update an anonymously posted taskrun"""

        with self.flask_app.test_request_context('/'):
            anonymous_taskrun = AnonymousTaskRunFactory.create()

            assert_raises(Forbidden,
                          getattr(require, 'taskrun').update,
                          anonymous_taskrun)
Beispiel #29
0
    def test_anonymous_user_create_repeated_taskrun(self):
        """Test anonymous user cannot create a taskrun for a task to which
        he has previously posted a taskrun"""

        with self.flask_app.test_request_context('/'):
            task = TaskFactory.create()
            taskrun1 = AnonymousTaskRunFactory.create(task=task)
            taskrun2 = AnonymousTaskRunFactory.build(task=task)
            assert_raises(Forbidden,
                        getattr(require, 'taskrun').create,
                        taskrun2)

            # But the user can still create taskruns for different tasks
            task2 = TaskFactory.create(app=task.app)
            taskrun3 = AnonymousTaskRunFactory.build(task=task2)
            assert_not_raises(Exception,
                          getattr(require, 'taskrun').create,
                          taskrun3)
Beispiel #30
0
    def test_anonymous_user_create_taskrun_non_allow_anonymous_contrib(self):
        """Test anonymous user cannot create a taskrun for a project that does
        not allow for anonymous contributors"""

        project = AppFactory.create(allow_anonymous_contributors=False)
        task = TaskFactory.create(app=project)
        taskrun = AnonymousTaskRunFactory.build(task=task)

        assert_raises(Unauthorized, getattr(require, 'taskrun').create, taskrun)
Beispiel #31
0
    def test_taskrun_delete(self):
        """Test TaskRun API delete works"""
        admin = UserFactory.create()
        owner = UserFactory.create()
        non_owner = UserFactory.create()
        project = ProjectFactory.create(owner=owner)
        task = TaskFactory.create(project=project)
        anonymous_taskrun = AnonymousTaskRunFactory.create(task=task, info='my task result')
        user_taskrun = TaskRunFactory.create(task=task, user=owner, info='my task result')

        ## anonymous
        res = self.app.delete('/api/taskrun/%s' % user_taskrun.id)
        error_msg = 'Anonymous should not be allowed to delete'
        assert_equal(res.status, '401 UNAUTHORIZED', error_msg)

        ### real user but not allowed to delete anonymous TaskRuns
        url = '/api/taskrun/%s?api_key=%s' % (anonymous_taskrun.id, owner.api_key)
        res = self.app.delete(url)
        error_msg = 'Authenticated user should not be allowed ' \
                    'to delete anonymous TaskRuns'
        assert_equal(res.status, '403 FORBIDDEN', error_msg)

        ### real user but not allowed as not owner!
        url = '/api/taskrun/%s?api_key=%s' % (user_taskrun.id, non_owner.api_key)
        res = self.app.delete(url)
        error_msg = 'Should not be able to delete TaskRuns of others'
        assert_equal(res.status, '403 FORBIDDEN', error_msg)

        #### real user
        # DELETE with not allowed args
        url = '/api/taskrun/%s?api_key=%s' % (user_taskrun.id, owner.api_key)
        res = self.app.delete(url + "&foo=bar")
        err = json.loads(res.data)
        assert res.status_code == 415, err
        assert err['status'] == 'failed', err
        assert err['target'] == 'taskrun', err
        assert err['action'] == 'DELETE', err
        assert err['exception_cls'] == 'AttributeError', err

        # Owner with valid args can delete
        res = self.app.delete(url)
        assert_equal(res.status, '204 NO CONTENT', res.data)

        ### root
        url = '/api/taskrun/%s?api_key=%s' % (anonymous_taskrun.id, admin.api_key)
        res = self.app.delete(url)
        error_msg = 'Admin should be able to delete TaskRuns of others'
        assert_equal(res.status, '204 NO CONTENT', error_msg)
Beispiel #32
0
    def test_authenticated_user_read(self):
        """Test authenticated user can read any taskrun"""

        own_taskrun = TaskRunFactory.create()
        anonymous_taskrun = AnonymousTaskRunFactory.create()
        other_users_taskrun = TaskRunFactory.create()

        assert self.mock_authenticated.id == own_taskrun.user.id
        assert self.mock_authenticated.id != other_users_taskrun.user.id
        assert_not_raises(Exception,
                          getattr(require, 'taskrun').read, anonymous_taskrun)
        assert_not_raises(Exception,
                          getattr(require, 'taskrun').read,
                          other_users_taskrun)
        assert_not_raises(Exception,
                          getattr(require, 'taskrun').read, own_taskrun)
Beispiel #33
0
    def test_get_locs_returns_list_of_locations_with_each_different_ip(self, geoip_mock, current_app):
        current_app.config = {'GEO': True}
        geoip_instance = Mock()
        ip_addr = lambda ip: {"1.1.1.1": {'latitude': 1, 'longitude': 1}, "2.2.2.2": None}.get(ip)
        geoip_instance.record_by_addr = ip_addr
        geoip_mock.return_value = geoip_instance

        AnonymousTaskRunFactory.create(user_ip="1.1.1.1")
        AnonymousTaskRunFactory.create(user_ip="1.1.1.1")
        AnonymousTaskRunFactory.create(user_ip="2.2.2.2")

        locations = stats.get_locs()

        assert len(locations) == 2, locations
        assert locations[0]['loc'] == {'latitude': 1, 'longitude': 1}, locations[0]
        assert locations[1]['loc'] == {'latitude': 0, 'longitude': 0}, locations[1]
Beispiel #34
0
    def test_task_query_participated_user_ip(self):
        """Test API Task query with participated arg user_ip."""
        admin, owner, user = UserFactory.create_batch(3)
        project = ProjectFactory.create(owner=owner)
        tasks1 = TaskFactory.create_batch(10,
                                          project=project,
                                          info=dict(foo='fox'))
        tasks2 = TaskFactory.create_batch(10,
                                          project=project,
                                          info=dict(foo='dog'))
        tasks = tasks1 + tasks2
        AnonymousTaskRunFactory.create(task=tasks[0])
        AnonymousTaskRunFactory.create(task=tasks[1])
        AnonymousTaskRunFactory.create(task=tasks[2])

        url = '/api/task?participated=1&all=1'

        res = self.app.get(url)
        data = json.loads(res.data)

        assert len(data) == 17, len(data)
        participated_tasks = [tasks[0].id, tasks[1].id, tasks[2].id]

        for task in data:
            assert task['id'] not in participated_tasks, task['id']

        # limit & offset
        url = '/api/task?participated=1&all=1&limit=10&offset=10'

        res = self.app.get(url)
        data = json.loads(res.data)

        assert len(data) == 7, len(data)
        participated_tasks = [tasks[0].id, tasks[1].id, tasks[2].id]

        for task in data:
            assert task['id'] not in participated_tasks, task['id']

        # last_id
        url = '/api/task?participated=1&all=1&last_id=%s' % (tasks[0].id)

        res = self.app.get(url)
        data = json.loads(res.data)

        assert len(data) == 17, len(data)
        participated_tasks = [tasks[0].id, tasks[1].id, tasks[2].id]

        for task in data:
            assert task['id'] not in participated_tasks, task['id']

        # orderby & desc
        url = '/api/task?participated=1&all=1&orderby=created&desc=1'

        res = self.app.get(url)
        data = json.loads(res.data)

        assert len(data) == 17, len(data)
        participated_tasks = [tasks[0].id, tasks[1].id, tasks[2].id]

        assert data[0]['id'] == tasks[-1].id

        for task in data:
            assert task['id'] not in participated_tasks, task['id']

        # info & fulltextsearch
        url = '/api/task?participated=1&all=1&orderby=created&desc=1&info=foo::fox&fulltextsearch=1'

        res = self.app.get(url)
        data = json.loads(res.data)

        assert len(data) == 7, len(data)
        participated_tasks = [tasks[0].id, tasks[1].id, tasks[2].id]

        assert data[0]['id'] == tasks1[-1].id

        for task in data:
            assert task['id'] not in participated_tasks, task['id']
Beispiel #35
0
 def setUp(self):
     super(TestStats, self).setUp()
     self.project = AppFactory.create()
     for task in TaskFactory.create_batch(4, app=self.project, n_answers=3):
         TaskRunFactory.create(task=task)
         AnonymousTaskRunFactory.create(task=task)
Beispiel #36
0
    def test_taskrun_update_with_result(self):
        """Test TaskRun API update with result works"""
        admin = UserFactory.create()
        owner = UserFactory.create()
        non_owner = UserFactory.create()
        project = ProjectFactory.create(owner=owner)
        task = TaskFactory.create(project=project, n_answers=2)
        anonymous_taskrun = AnonymousTaskRunFactory.create(
            task=task, info='my task result')
        user_taskrun = TaskRunFactory.create(task=task,
                                             user=owner,
                                             info='my task result')

        task_run = dict(project_id=project.id,
                        task_id=task.id,
                        info='another result')
        datajson = json.dumps(task_run)

        # anonymous user
        # No one can update anonymous TaskRuns
        url = '/api/taskrun/%s' % anonymous_taskrun.id
        res = self.app.put(url, data=datajson)
        assert anonymous_taskrun, anonymous_taskrun
        assert_equal(anonymous_taskrun.user, None)
        error_msg = 'Should not be allowed to update'
        assert_equal(res.status, '401 UNAUTHORIZED', error_msg)

        # real user but not allowed as not owner!
        url = '/api/taskrun/%s?api_key=%s' % (user_taskrun.id,
                                              non_owner.api_key)
        res = self.app.put(url, data=datajson)
        error_msg = 'Should not be able to update TaskRuns of others'
        assert_equal(res.status, '403 FORBIDDEN', error_msg)

        # real user
        url = '/api/taskrun/%s?api_key=%s' % (user_taskrun.id, owner.api_key)
        out = self.app.get(url, follow_redirects=True)
        task = json.loads(out.data)
        datajson = json.loads(datajson)
        datajson['link'] = task['link']
        datajson['links'] = task['links']
        datajson = json.dumps(datajson)
        url = '/api/taskrun/%s?api_key=%s' % (user_taskrun.id, owner.api_key)
        res = self.app.put(url, data=datajson)
        out = json.loads(res.data)
        assert_equal(res.status, '403 FORBIDDEN', error_msg)

        # PUT with not JSON data
        res = self.app.put(url, data=task_run)
        err = json.loads(res.data)
        assert_equal(res.status, '403 FORBIDDEN', error_msg)

        # PUT with not allowed args
        res = self.app.put(url + "&foo=bar", data=json.dumps(task_run))
        err = json.loads(res.data)
        assert_equal(res.status, '415 UNSUPPORTED MEDIA TYPE', error_msg)

        # PUT with fake data
        task_run['wrongfield'] = 13
        res = self.app.put(url, data=json.dumps(task_run))
        err = json.loads(res.data)
        assert_equal(res.status, '403 FORBIDDEN', error_msg)

        # root user
        url = '/api/taskrun/%s?api_key=%s' % (user_taskrun.id, admin.api_key)
        res = self.app.put(url, data=datajson)
        assert_equal(res.status, '403 FORBIDDEN', error_msg)
Beispiel #37
0
    def test_anonymous_user_update_anoymous_taskrun(self):
        """Test anonymous users cannot update an anonymously posted taskrun"""
        anonymous_taskrun = AnonymousTaskRunFactory.create()

        assert_raises(Unauthorized, ensure_authorized_to, 'update',
                      anonymous_taskrun)
Beispiel #38
0
 def _add_task_run(self, app, task, user=None):
     tr = AnonymousTaskRunFactory.create(project=app, task=task)
    def test_taskrun_update(self):
        """Test TaskRun API update works"""
        admin = UserFactory.create()
        owner = UserFactory.create()
        non_owner = UserFactory.create()
        project = ProjectFactory.create(owner=owner)
        task = TaskFactory.create(project=project)
        anonymous_taskrun = AnonymousTaskRunFactory.create(
            task=task, info='my task result')
        user_taskrun = TaskRunFactory.create(task=task,
                                             user=owner,
                                             info='my task result')

        task_run = dict(project_id=project.id,
                        task_id=task.id,
                        info='another result')
        datajson = json.dumps(task_run)

        # anonymous user
        # No one can update anonymous TaskRuns
        url = '/api/taskrun/%s' % anonymous_taskrun.id
        res = self.app.put(url, data=datajson)
        assert anonymous_taskrun, anonymous_taskrun
        assert_equal(anonymous_taskrun.user, None)
        error_msg = 'Should not be allowed to update'
        assert_equal(res.status, '401 UNAUTHORIZED', error_msg)

        # real user but not allowed as not owner!
        url = '/api/taskrun/%s?api_key=%s' % (user_taskrun.id,
                                              non_owner.api_key)
        res = self.app.put(url, data=datajson)
        error_msg = 'Should not be able to update TaskRuns of others'
        assert_equal(res.status, '403 FORBIDDEN', error_msg)

        # real user
        url = '/api/taskrun/%s?api_key=%s' % (user_taskrun.id, owner.api_key)
        out = self.app.get(url, follow_redirects=True)
        task = json.loads(out.data)
        datajson = json.loads(datajson)
        datajson['link'] = task['link']
        datajson['links'] = task['links']
        datajson = json.dumps(datajson)
        url = '/api/taskrun/%s?api_key=%s' % (user_taskrun.id, owner.api_key)
        res = self.app.put(url, data=datajson)
        out = json.loads(res.data)
        assert_equal(res.status, '403 FORBIDDEN', res.data)

        # PUT with not JSON data
        res = self.app.put(url, data=task_run)
        err = json.loads(res.data)
        assert res.status_code == 403, err
        assert err['status'] == 'failed', err
        assert err['target'] == 'taskrun', err
        assert err['action'] == 'PUT', err
        assert err['exception_cls'] == 'Forbidden', err

        # PUT with not allowed args
        res = self.app.put(url + "&foo=bar", data=json.dumps(task_run))
        err = json.loads(res.data)
        assert res.status_code == 415, err
        assert err['status'] == 'failed', err
        assert err['target'] == 'taskrun', err
        assert err['action'] == 'PUT', err
        assert err['exception_cls'] == 'AttributeError', err

        # PUT with fake data
        task_run['wrongfield'] = 13
        res = self.app.put(url, data=json.dumps(task_run))
        err = json.loads(res.data)
        assert res.status_code == 403, err
        assert err['status'] == 'failed', err
        assert err['target'] == 'taskrun', err
        assert err['action'] == 'PUT', err
        assert err['exception_cls'] == 'Forbidden', err
        task_run.pop('wrongfield')

        # root user
        url = '/api/taskrun/%s?api_key=%s' % (user_taskrun.id, admin.api_key)
        res = self.app.put(url, data=datajson)
        assert_equal(res.status, '403 FORBIDDEN', res.data)
Beispiel #40
0
    def test_admin_update_anonymous_taskrun(self):
        """Test admins cannot update anonymously posted taskruns"""
        anonymous_taskrun = AnonymousTaskRunFactory.create()

        assert_raises(Forbidden, ensure_authorized_to, 'update',
                      anonymous_taskrun)
Beispiel #41
0
    def test_authenticated_user_delete_anonymous_taskrun(self):
        """Test authenticated users cannot delete an anonymously posted taskrun"""
        anonymous_taskrun = AnonymousTaskRunFactory.create()

        assert_raises(Forbidden, ensure_authorized_to, 'delete',
                      anonymous_taskrun)
Beispiel #42
0
 def prepare_data(self):
     self.project = ProjectFactory.create()
     for task in TaskFactory.create_batch(4, project=self.project, n_answers=3):
         TaskRunFactory.create(task=task)
         AnonymousTaskRunFactory.create(task=task)
Beispiel #43
0
    def test_admin_delete_anonymous_taskrun(self):
        """Test admins can delete anonymously posted taskruns"""
        anonymous_taskrun = AnonymousTaskRunFactory.create()

        assert_not_raises(Exception, ensure_authorized_to, 'delete',
                          anonymous_taskrun)