Exemplo n.º 1
0
    def test_query_post_favorites_auth(self):
        """Test API POST Favorites works for user."""
        user = UserFactory.create()
        user2 = UserFactory.create()
        task = TaskFactory.create()
        url = self.url + '?api_key=%s' % user.api_key
        res = self.app.post(url, data=json.dumps(dict(task_id=task.id)))
        data = json.loads(res.data)
        assert res.status_code == 200, res.status_code
        assert data['fav_user_ids'] == [user.id], data

        url = self.url + '?api_key=%s' % user2.api_key
        res = self.app.post(url, data=json.dumps(dict(task_id=task.id)))
        data = json.loads(res.data)
        assert res.status_code == 200, res.status_code
        assert user.id in data['fav_user_ids'], data
        assert user2.id in data['fav_user_ids'], data

        url = self.url + '?api_key=%s' % user2.api_key
        res = self.app.post(url, data=json.dumps(dict(task_id=4000000000)))
        data = json.loads(res.data)
        assert res.status_code == 404, res.status_code
        assert data['status_code'] == 404, data

        url = self.url + '?api_key=%s' % user2.api_key
        res = self.app.post(url, data=json.dumps(dict(task_id=task.id)))
        data = json.loads(res.data)
        assert res.status_code == 200, res.status_code
        assert user.id in data['fav_user_ids'], data
        assert user2.id in data['fav_user_ids'], data
Exemplo n.º 2
0
    def test_user_not_allowed_actions_admin (self):
        """Test POST, PUT and DELETE for ADMIN actions are not allowed for user
        in the API"""
        admin = UserFactory.create()
        auth = UserFactory.create()
        user = UserFactory.create()
        url = 'api/user'
        res = self.app.post(url + '?api_key=%s' % admin.api_key,
                            data=json.dumps(user.to_public_json()))
        data = json.loads(res.data)
        assert res.status_code == 405, res.status_code
        assert data['status_code'] == 405, data

        # Update another user
        url += '/%s' % user.id
        new_info = user.info
        new_info['foo'] = 'bar'
        res = self.app.put(url + '?api_key=%s' % admin.api_key,
                           data=json.dumps(dict(name='new', info=new_info)))
        data = json.loads(res.data)
        assert res.status_code == 200, res.data
        assert data['name'] == 'new', data
        assert data['info']['foo'] == 'bar', data

        res = self.app.delete(url + '?apikey=%s' % auth.api_key)
        assert res.status_code == 405, res.status_code

        # Update the same user
        url = 'api/user/%s' % admin.id
        res = self.app.put(url + '?api_key=%s' % admin.api_key,
                           data=json.dumps(dict(name='newadmin')))
        data = json.loads(res.data)
        assert res.status_code == 200, res.data
        assert data['name'] == 'newadmin', data
Exemplo n.º 3
0
    def test_delete_blogpost(self, mock_delete):
        """Test API Blogpost delete post (DEL)."""
        mock_delete.return_value = True
        admin = UserFactory.create()
        owner = UserFactory.create()
        user = UserFactory.create()
        project = ProjectFactory.create(owner=owner)
        blogpost = BlogpostFactory.create(project=project)
        blogpost2 = BlogpostFactory.create(project=project)

        # As anon
        url = '/api/blogpost/%s' % blogpost.id
        res = self.app.delete(url)
        data = json.loads(res.data)
        assert res.status_code == 401, res.status_code

        # As user
        url = '/api/blogpost/%s?api_key=%s' % (blogpost.id, user.api_key)
        res = self.app.delete(url)
        assert res.status_code == 403, res.status_code

        # As owner
        url = '/api/blogpost/%s?api_key=%s' % (blogpost.id, owner.api_key)
        res = self.app.delete(url)
        assert res.status_code == 204, res.status_code
        assert mock_delete.called_with(blogpost.info['file_name'],
                                       blogpost.info['container'])

        # As admin
        url = '/api/blogpost/%s?api_key=%s' % (blogpost2.id, admin.api_key)
        res = self.app.delete(url)
        assert res.status_code == 204, res.status_code
Exemplo n.º 4
0
    def test_user_03_respects_limit_tasks(self):
        """ Test SCHED newtask respects the limit of 30 TaskRuns per Task"""
        project = ProjectFactory.create(info=dict(sched='depth_first_all'),
                                        owner=UserFactory.create(id=500))
        orig_tasks = TaskFactory.create_batch(1, project=project, n_answers=10)
        user = UserFactory.create()

        tasks = get_depth_first_all_task(project.id, user.id)
        assert len(tasks) == 1, len(tasks)
        assert tasks[0].id == orig_tasks[0].id, tasks
        assert tasks[0].state == 'ongoing', tasks

        for i in range(10):
            tr = TaskRun(project_id=project.id,
                         task_id=orig_tasks[0].id,
                         user_ip='127.0.0.%s' % i)
            db.session.add(tr)
            db.session.commit()

        tasks = get_depth_first_all_task(project.id, user.id)
        assert len(tasks) == 1, len(tasks)
        assert tasks[0].id == orig_tasks[0].id, tasks
        assert tasks[0].state == 'completed', tasks
        assert len(tasks[0].task_runs) == 10, tasks

        tr = TaskRun(project_id=project.id,
                     task_id=orig_tasks[0].id,
                     user_id=user.id)
        db.session.add(tr)
        db.session.commit()

        tasks = get_depth_first_all_task(project.id, user.id)

        assert len(tasks) == 0, tasks
Exemplo n.º 5
0
    def test_parse_post(self):
        response = '''{"comments": {"can_post": 0, "count": 4},
                 "date": 1298365200,
                 "from_id": 55555,
                 "geo": {"coordinates": "55.6745689498 37.8724562529",
                  "place": {"city": "Moskovskaya oblast",
                   "country": "Russian Federation",
                   "title": "Shosseynaya ulitsa, Moskovskaya oblast"},
                  "type": "point"},
                 "id": 465,
                 "likes": {"can_like": 1, "can_publish": 1, "count": 10, "user_likes": 0},
                 "online": 1,
                 "post_source": {"type": "api"},
                 "reply_count": 0,
                 "reposts": {"count": 3, "user_reposted": 0},
                 "text": "qwerty",
                 "to_id": 201164356}
            '''
        instance = Post()
        owner = UserFactory.create(remote_id=201164356)  # Travis Djangov
        author = UserFactory.create(remote_id=55555)
        instance.parse(json.loads(response))
        instance.save()

        self.assertTrue(instance.remote_id.startswith('201164356_'))
        self.assertEqual(instance.wall_owner, owner)
        self.assertEqual(instance.author, author)
        self.assertEqual(instance.reply_count, 0)
        self.assertEqual(instance.likes, 10)
        self.assertEqual(instance.reposts, 3)
        self.assertEqual(instance.comments, 4)
        self.assertEqual(instance.text, 'qwerty')
        self.assertTrue(isinstance(instance.date, datetime))
Exemplo n.º 6
0
    def test_org_decline_invitation(self):
        user_a = UserFactory.create(email="*****@*****.**")
        user_b = UserFactory.create(email="*****@*****.**")
        org = create_sample_organization(user_a, org_kwargs={
            'name': u"My first org",
        })
        project = create_sample_project(user_a, project_kwargs={
            'org': org
        })
        auth = AuthorizationAssociation.objects.create(
            org=org,
            user=user_b,
            is_active=False,
            is_admin=True
        )
        auth_p = AuthorizationAssociation.objects.create(
            project=project,
            user=user_b,
            is_active=False,
            is_admin=True
        )

        url = reverse("my_notifications")
        response = self.app.get(url, user=user_b)
        self.assertContains(response, org.name)
        form = response.forms['form_decline_{0}'.format(auth.pk)]
        response = form.submit().follow()
        self.assertContains(response, "Invitation has been declined")
        auth_filter = AuthorizationAssociation.objects.filter(pk=auth.pk)
        self.assertFalse(auth_filter.exists())
        auth_filter = AuthorizationAssociation.objects.filter(pk=auth_p.pk)
        self.assertFalse(auth_filter.exists())
Exemplo n.º 7
0
    def test_taskrun_cannot_be_deleted_associated_result_variation_2(self):
        """Test API taskrun cannot be deleted when a result is associated
        variation."""
        root = UserFactory.create(admin=True)
        results = self.create_result(filter_by=True)
        project = project_repo.get(results[0].project_id)
        task = task_repo.get_task(results[0].task_id)

        task.n_answers = 30

        task_repo.update(task)

        volunteer = UserFactory.create()
        tr_delete = TaskRunFactory.create(task=task, user=volunteer)

        results = result_repo.filter_by(project_id=project.id, task_id=task.id)

        assert len(results) == 1, len(results)
        # Owner
        for result in results:
            for tr in result.task_run_ids:
                url = '/api/taskrun/%s?api_key=%s' % (tr, root.api_key)
                res = self.app.delete(url)
                assert_equal(res.status, '403 FORBIDDEN', res.status)

            url = '/api/taskrun/%s?api_key=%s' % (tr_delete.id,
                                                  volunteer.api_key)
            res = self.app.delete(url)
            assert_equal(res.status, '204 NO CONTENT', res.status)
Exemplo n.º 8
0
    def test_project_revoke_invitation(self):
        user_a = UserFactory.create(email="*****@*****.**")
        user_b = UserFactory.create(email="*****@*****.**")
        project = create_sample_project(user_a, project_kwargs={
            'name': u"My first project",
        })
        project.add_user(user_b)
        url = reverse("dashboard")
        response = self.app.get(url, user=user_b)
        self.assertContains(response, u"My first project")

        auth = AuthorizationAssociation.objects.get(
            project=project,
            user=user_b
        )

        url = reverse("project_auth_delete", args=(project.pk, auth.pk))
        self.app.get(url, user=user_b, status=403)
        response = self.app.get(url, user=user_a)
        form = response.forms['delete_form']
        response = form.submit().follow()
        self.assertContains(
            response,
            'User {0} has been revoked.'.format(user_b.email),
        )
        url = reverse("dashboard")
        response = self.app.get(url, user=user_b)
        self.assertNotContains(response, u"My first project")
Exemplo n.º 9
0
    def test_org_accept_invitation(self):
        user_a = UserFactory.create(email="*****@*****.**")
        user_b = UserFactory.create(email="*****@*****.**")
        org = create_sample_organization(user_a, org_kwargs={
            'name': u"My first org",
        })
        project = create_sample_project(user_a, project_kwargs={
            'org': org
        })
        auth = AuthorizationAssociation.objects.create(
            org=org,
            user=user_b,
            is_active=False,
            is_admin=True
        )
        project.add_user(user_b, is_active=False)
        project = Project.objects.get(pk=project.pk)
        self.assertFalse(project.can_read(user_b))

        url = reverse("my_notifications")
        response = self.app.get(url, user=user_b)
        self.assertContains(response, org.name)
        form = response.forms['form_accept_{0}'.format(auth.pk)]
        response = form.submit().follow()
        self.assertContains(response, "You are now a member of this "
                                      "organization")
        auth = AuthorizationAssociation.objects.get(pk=auth.pk)
        self.assertTrue(auth.is_active)
        project = Project.objects.get(pk=project.pk)
        self.assertTrue(project.can_read(user_b))
Exemplo n.º 10
0
    def test_total_users_count(self):
        """Test total_users return 1 if there is one user"""

        UserFactory.create()
        count = self.user_repo.total_users()

        assert count == 1, count
Exemplo n.º 11
0
def test_order_allocations(app):
    org = OrganizationFactory.create()
    u1 = UserFactory.create(organization=org)
    u2 = UserFactory.create(organization=org)
    u3 = UserFactory.create(organization=org)
    vendor = VendorFactory.create()
    order = Order(
        ordered_by=u1, vendor=vendor,
        for_date=date.today(), placed_at=datetime.now(),
    )
    db.session.add(order)
    db.session.commit()
    assert order.total_amount == Decimal("0.00")
    oc1 = OrderContribution(order=order, user=u1, amount=Decimal("10.80"))
    db.session.add(oc1)
    db.session.commit()
    assert order.total_amount == Decimal("10.80")
    oc2 = OrderContribution(order=order, user=u2, amount=Decimal("2.50"))
    db.session.add(oc2)
    db.session.commit()
    assert order.total_amount == Decimal("13.30")
    oc3 = OrderContribution(order=order, user=u3, amount=Decimal("4.75"))
    db.session.add(oc3)
    db.session.commit()
    assert order.total_amount == Decimal("18.05")
Exemplo n.º 12
0
    def test_user_not_allowed_actions_user(self, caching_mock):
        """Test POST, PUT and DELETE for USER actions are not allowed for user
        in the API"""
        clean_user_mock = MagicMock()
        caching_mock.get.return_value = dict(refresh=clean_user_mock)
        admin = UserFactory.create()
        auth = UserFactory.create()
        user = UserFactory.create()
        url = 'api/user'
        res = self.app.post(url + '?api_key=%s' % auth.api_key,
                            data=json.dumps(user.to_public_json()))
        data = json.loads(res.data)
        assert res.status_code == 405, res.status_code
        assert data['status_code'] == 405, data

        # Update another user
        url += '/%s' % user.id
        res = self.app.put(url + '?api_key=%s' % auth.api_key,
                           data=json.dumps(dict(name='new')))
        assert res.status_code == 403, res.data

        res = self.app.delete(url + '?apikey=%s' % auth.api_key)
        assert res.status_code == 405, res.status_code

        # Update the same user
        url = 'api/user/%s' % auth.id
        res = self.app.put(url + '?api_key=%s' % auth.api_key,
                           data=json.dumps(dict(name='new')))
        data = json.loads(res.data)
        assert res.status_code == 200, res.data
        assert data['name'] == 'new', data
        clean_user_mock.assert_called_with(data['id'])
Exemplo n.º 13
0
    def test_result_post(self):
        """Test API Result creation"""
        admin = UserFactory.create()
        user = UserFactory.create()
        non_owner = UserFactory.create()
        project = ProjectFactory.create(owner=user)
        data = dict(info='final result')

        # anonymous user
        # no api-key
        res = self.app.post('/api/result', data=json.dumps(data))
        error_msg = 'Should not be allowed to create'
        assert_equal(res.status, '401 UNAUTHORIZED', error_msg)

        ### real user but not allowed as not owner!
        res = self.app.post('/api/result?api_key=' + non_owner.api_key,
                            data=json.dumps(data))

        error_msg = 'Should not be able to post tasks for projects of others'
        assert_equal(res.status, '403 FORBIDDEN', error_msg)

        # now a real user
        res = self.app.post('/api/result?api_key=' + user.api_key,
                            data=json.dumps(data))
        assert_equal(res.status, '403 FORBIDDEN', error_msg)

        # now the root user
        res = self.app.post('/api/result?api_key=' + admin.api_key,
                            data=json.dumps(data))
        assert_equal(res.status, '403 FORBIDDEN', error_msg)

        # POST with not JSON data
        url = '/api/result?api_key=%s' % user.api_key
        res = self.app.post(url, data=data)
        err = json.loads(res.data)
        assert res.status_code == 415, err
        assert err['status'] == 'failed', err
        assert err['target'] == 'result', err
        assert err['action'] == 'POST', err
        assert err['exception_cls'] == 'ValueError', err

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

        # POST with fake data
        data['wrongfield'] = 13
        res = self.app.post(url, data=json.dumps(data))
        err = json.loads(res.data)
        assert res.status_code == 415, err
        assert err['status'] == 'failed', err
        assert err['target'] == 'result', err
        assert err['action'] == 'POST', err
        assert err['exception_cls'] == 'TypeError', err
Exemplo n.º 14
0
    def test_admins_can_delete_any_user(self):
        """Test admins users can delete any given user"""
        himself = UserFactory.create()
        other_user = UserFactory.create()

        assert himself.id == self.mock_admin.id
        assert other_user.id != self.mock_admin.id
        assert_not_raises(Exception, ensure_authorized_to, 'delete', other_user)
Exemplo n.º 15
0
    def test_user_check_duplicated_username(self):
        # create a user
        UserFactory.create(username='******')

        # try to create another user with the same username
        self.data.update({'username': '******'})
        response = self.client.post(reverse('accounts_registration'), self.data)
        self.assertContains(response, u'Erro ao processar formulário')
Exemplo n.º 16
0
 def test_notify_news_admins(self):
     user = UserFactory.create(admin=False)
     user2 = UserFactory.create(admin=False)
     notify_news_admins()
     key = "notify:admin:%s" % user2.id
     value = sentinel.slave.get(key)
     err_msg = "Key should not exist"
     assert value is None, err_msg
Exemplo n.º 17
0
    def test_get_by_returns_none_if_no_user(self):
        """Test get_by returns None if no user matches the query"""

        UserFactory.create(name='Tyrion Lannister')

        user = self.user_repo.get_by(name='no_name')

        assert user is None, user
Exemplo n.º 18
0
    def test_get_users(self):

        tyrion = UserFactory.create(name='Tyrion Lannister')
        theon = UserFactory.create(name='reek', fullname='Theon Greyjoy')

        retrieved_users = self.user_repo.get_users([tyrion.id, theon.id])
        assert any(user == tyrion for user in retrieved_users)
        assert any(user == theon for user in retrieved_users)
Exemplo n.º 19
0
    def test_admins_can_delete_any_user(self):
        """Test admins users can delete any given user"""
        himself = UserFactory.create()
        other_user = UserFactory.create()

        assert himself.id == self.mock_admin.id
        assert other_user.id != self.mock_admin.id
        assert_not_raises(Exception, getattr(require, 'user').delete, other_user)
Exemplo n.º 20
0
    def test_result_update(self):
        """Test API result update"""
        admin = UserFactory.create()
        user = UserFactory.create()
        non_owner = UserFactory.create()
        data = dict(info=dict(foo='bar'))
        datajson = json.dumps(data)
        result = self.create_result(owner=user)

        ## anonymous
        res = self.app.put('/api/result/%s' % result.id, data=datajson)
        assert_equal(res.status, '401 UNAUTHORIZED', res.status)
        ### real user but not allowed as not owner!
        url = '/api/result/%s?api_key=%s' % (result.id, non_owner.api_key)
        res = self.app.put(url, data=datajson)
        assert_equal(res.status, '403 FORBIDDEN', res.status)

        ### real user
        url = '/api/result/%s?api_key=%s' % (result.id, user.api_key)
        res = self.app.put(url, data=datajson)
        out = json.loads(res.data)
        assert_equal(res.status, '200 OK', res.data)
        assert_equal(result.info['foo'], data['info']['foo'])
        assert result.id == out['id'], out

        ### root
        res = self.app.put('/api/result/%s?api_key=%s' % (result.id, admin.api_key),
                           data=datajson)
        assert_equal(res.status, '403 FORBIDDEN', res.status)

        # PUT with not JSON data
        res = self.app.put(url, data=None)
        err = json.loads(res.data)
        assert res.status_code == 415, err
        assert err['status'] == 'failed', err
        assert err['target'] == 'result', err
        assert err['action'] == 'PUT', err
        assert err['exception_cls'] == 'ValueError', err

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

        # PUT with fake data
        data['wrongfield'] = 13
        res = self.app.put(url, data=json.dumps(data))
        err = json.loads(res.data)
        assert res.status_code == 415, err
        assert err['status'] == 'failed', err
        assert err['target'] == 'result', err
        assert err['action'] == 'PUT', err
        assert err['exception_cls'] == 'TypeError', err
Exemplo n.º 21
0
    def test_filter_by_no_matches(self):
        """Test filter_by returns an empty list if no users match the query"""

        UserFactory.create(name='reek', fullname='Theon Greyjoy')

        retrieved_users = self.user_repo.filter_by(name='asha')

        assert isinstance(retrieved_users, list)
        assert len(retrieved_users) == 0, retrieved_users
Exemplo n.º 22
0
    def test_result_post(self):
        """Test API Result creation"""
        admin = UserFactory.create()
        user = UserFactory.create()
        non_owner = UserFactory.create()
        project = ProjectFactory.create(owner=user)
        data = dict(info="final result")

        # anonymous user
        # no api-key
        res = self.app.post("/api/result", data=json.dumps(data))
        error_msg = "Should not be allowed to create"
        assert_equal(res.status, "401 UNAUTHORIZED", error_msg)

        ### real user but not allowed as not owner!
        res = self.app.post("/api/result?api_key=" + non_owner.api_key, data=json.dumps(data))

        error_msg = "Should not be able to post tasks for projects of others"
        assert_equal(res.status, "403 FORBIDDEN", error_msg)

        # now a real user
        res = self.app.post("/api/result?api_key=" + user.api_key, data=json.dumps(data))
        assert_equal(res.status, "403 FORBIDDEN", error_msg)

        # now the root user
        res = self.app.post("/api/result?api_key=" + admin.api_key, data=json.dumps(data))
        assert_equal(res.status, "403 FORBIDDEN", error_msg)

        # POST with not JSON data
        url = "/api/result?api_key=%s" % user.api_key
        res = self.app.post(url, data=data)
        err = json.loads(res.data)
        assert res.status_code == 415, err
        assert err["status"] == "failed", err
        assert err["target"] == "result", err
        assert err["action"] == "POST", err
        assert err["exception_cls"] == "ValueError", err

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

        # POST with fake data
        data["wrongfield"] = 13
        res = self.app.post(url, data=json.dumps(data))
        err = json.loads(res.data)
        assert res.status_code == 415, err
        assert err["status"] == "failed", err
        assert err["target"] == "result", err
        assert err["action"] == "POST", err
        assert err["exception_cls"] == "TypeError", err
Exemplo n.º 23
0
    def test_result_update(self):
        """Test API result update"""
        admin = UserFactory.create()
        user = UserFactory.create()
        non_owner = UserFactory.create()
        data = dict(info=dict(foo="bar"))
        datajson = json.dumps(data)
        result = self.create_result(owner=user)

        ## anonymous
        res = self.app.put("/api/result/%s" % result.id, data=datajson)
        assert_equal(res.status, "401 UNAUTHORIZED", res.status)
        ### real user but not allowed as not owner!
        url = "/api/result/%s?api_key=%s" % (result.id, non_owner.api_key)
        res = self.app.put(url, data=datajson)
        assert_equal(res.status, "403 FORBIDDEN", res.status)

        ### real user
        url = "/api/result/%s?api_key=%s" % (result.id, user.api_key)
        res = self.app.put(url, data=datajson)
        out = json.loads(res.data)
        assert_equal(res.status, "200 OK", res.data)
        assert_equal(result.info["foo"], data["info"]["foo"])
        assert result.id == out["id"], out

        ### root
        res = self.app.put("/api/result/%s?api_key=%s" % (result.id, admin.api_key), data=datajson)
        assert_equal(res.status, "403 FORBIDDEN", res.status)

        # PUT with not JSON data
        res = self.app.put(url, data=None)
        err = json.loads(res.data)
        assert res.status_code == 415, err
        assert err["status"] == "failed", err
        assert err["target"] == "result", err
        assert err["action"] == "PUT", err
        assert err["exception_cls"] == "ValueError", err

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

        # PUT with fake data
        data["wrongfield"] = 13
        res = self.app.put(url, data=json.dumps(data))
        err = json.loads(res.data)
        assert res.status_code == 415, err
        assert err["status"] == "failed", err
        assert err["target"] == "result", err
        assert err["action"] == "PUT", err
        assert err["exception_cls"] == "TypeError", err
Exemplo n.º 24
0
    def test_get_user_summary_user_exists(self):
        """Test CACHE USERS get_user_summary returns a dict with the user data
        if the user exists"""
        UserFactory.create(name='zidane')
        UserFactory.create(name='figo')

        zizou = cached_users.get_user_summary('zidane')

        assert type(zizou) is dict, type(zizou)
        assert zizou != None, zizou
Exemplo n.º 25
0
    def test_get_user_summary_returns_fields(self):
        """Test CACHE USERS get_user_summary all the fields in the dict"""
        UserFactory.create(name='user')
        fields = ('id', 'name', 'fullname', 'created', 'api_key',
                  'twitter_user_id', 'google_user_id', 'facebook_user_id',
                  'info', 'email_addr', 'n_answers', 'rank', 'score', 'total')
        user = cached_users.get_user_summary('user')

        for field in fields:
            assert field in user.keys(), field
Exemplo n.º 26
0
 def test_notify_blog_users(self, mock):
     """Test Notify Blog users without pro or featured works."""
     owner = UserFactory.create(pro=False)
     user = UserFactory.create(subscribed=False)
     project = ProjectFactory.create(owner=owner, featured=False)
     TaskRunFactory.create(project=project)
     TaskRunFactory.create(project=project, user=user)
     blog = BlogpostFactory.create(project=project)
     res = notify_blog_users(blog.id, blog.project.id)
     msg = "0 users notified by email"
     assert res == msg, res
Exemplo n.º 27
0
    def test_project_registration_cycle(self):
        user_a = UserFactory.create(email="*****@*****.**")
        user_b = UserFactory.create(email="*****@*****.**")
        user_c = UserFactory.create(email="*****@*****.**")
        project = create_sample_project(user_a, project_kwargs={
            'name': u"My first project",
        })
        url = reverse('project_invite_user', args=(project.pk,))
        # require login
        self.app.get(url, status=302)
        # not part of the project yet
        self.app.get(url, user=user_b, status=404)
        response = self.app.get(url, user=user_a)
        self.assertContains(response, 'Invite')
        form = response.forms['register_form']
        # should handle uppercase email
        for key, value in {
            'email': '*****@*****.**',
        }.iteritems():
            form[key] = value
        response = form.submit().follow()

        self.assertContains(response, "Invitation has been sent")
        message = mail.outbox[-1]
        self.assertIn("*****@*****.**", message.to)
        self.assertTrue(
            message.body.find(
                "You have been invited to join the project") != -1
        )
        answer_url = line_starting(message.body, u"http://localhost:80/")
        response = self.app.get(answer_url, user=user_a, status=200)
        self.assertContains(
            response,
            u"You already accepted this invitation."
        )
        response = self.app.get(answer_url, user=user_c, status=200)
        self.assertContains(
            response,
            u"This invitation does not match your current user"
        )
        response = self.app.get(answer_url, user=user_b)
        self.assertContains(
            response,
            u"Invitation to project '{0}' has been".format(project.name)
        )

        url = reverse("dashboard")
        response = self.app.get(url, user=user_b)
        self.assertContains(response, escape(project.name))
        event = Event.objects.get(
            project=project
        )
        self.assertEqual(event.text, "joined the project as team member")
        self.assertEqual(event.user, user_b)
Exemplo n.º 28
0
    def test_search_by_name_capital_lower_letters(self):
        """Test search_by_name works the same with capital or lower letters"""

        user_capitals = UserFactory.create(name='JOJEN')
        user_lowers = UserFactory.create(name='meera')

        search_lower = self.user_repo.search_by_name('jojen')
        search_capital = self.user_repo.search_by_name('MEERA')

        assert user_capitals in search_lower, search_lower
        assert user_lowers in search_capital, search_capital
Exemplo n.º 29
0
 def test_notify_blog_users_pro_owner_feature_only_for_pros(self, mock):
     """Test Notify Blog users with pro owner project works."""
     owner = UserFactory.create(pro=True)
     user = UserFactory.create(subscribed=False)
     project = ProjectFactory.create(owner=owner)
     TaskRunFactory.create(project=project)
     TaskRunFactory.create(project=project, user=user)
     blog = BlogpostFactory.create(project=project)
     res = notify_blog_users(blog.id, blog.project.id)
     msg = "1 users notified by email"
     assert res == msg, res
Exemplo n.º 30
0
 def test_admin_can_crud(self):
     """Test admin user can crud tasks"""
     user = UserFactory.create()
     user2 = UserFactory.create()
     app = AppFactory.create(owner=user2)
     task = TaskFactory.create(app=app)
     with patch('pybossa.auth.task.current_user', new=user):
         assert_not_raises(Forbidden, getattr(require, 'task').create, task)
         assert_not_raises(Forbidden, getattr(require, 'task').read, task)
         assert_not_raises(Forbidden, getattr(require, 'task').update, task)
         assert_not_raises(Forbidden, getattr(require, 'task').delete, task)
Exemplo n.º 31
0
    def test_task_update_state(self):
        """Test API task n_answers updates state properly."""
        user = UserFactory.create()
        project = ProjectFactory.create(owner=user)
        task = TaskFactory.create(project=project,
                                  n_answers=1,
                                  state='ongoing')
        data = {'n_answers': 2}
        datajson = json.dumps(data)

        url = '/api/task/%s?api_key=%s' % (task.id, user.api_key)
        res = self.app.put(url, data=datajson)
        out = json.loads(res.data)
        assert_equal(res.status, '200 OK', res.data)
        assert_equal(task.n_answers, data['n_answers'])
        assert_equal(task.state, 'ongoing')
        assert task.id == out['id'], out

        task.state = 'completed'
        task_repo.update(task)

        data = {'n_answers': 1}
        datajson = json.dumps(data)

        res = self.app.put(url, data=datajson)
        out = json.loads(res.data)
        assert_equal(res.status, '200 OK', res.data)
        assert_equal(task.n_answers, data['n_answers'])
        assert_equal(task.state, 'completed')
        assert task.id == out['id'], out

        data = {'n_answers': 5}
        datajson = json.dumps(data)

        res = self.app.put(url, data=datajson)
        out = json.loads(res.data)
        assert_equal(res.status, '200 OK', res.data)
        assert_equal(task.n_answers, data['n_answers'])
        assert_equal(task.state, 'ongoing')
        assert task.id == out['id'], out
Exemplo n.º 32
0
    def test_reserve_task_category_lock_exclude_user(self):
        # with exclude_user = True, exclude user category key for user id = ``
        reserve_task_config = ["field_1", "field_2"]
        user = UserFactory.create()
        project = ProjectFactory.create(
            owner=user,
            info=dict(sched="task_queue_scheduler",
                      reserve_tasks=dict(category=reserve_task_config)))
        tasks = TaskFactory.create_batch(2,
                                         project=project,
                                         n_answers=1,
                                         info=dict(field_1="abc", field_2=123))

        non_excluded_user_id = 2
        acquire_reserve_task_lock(project.id, tasks[0].id, user.id, 1)
        acquire_reserve_task_lock(project.id, tasks[1].id,
                                  non_excluded_user_id, 1)
        expected_category_keys = [
            "reserve_task:project:{}:category:field_1:abc:field_2:123:user:{}:task:{}"
            .format(project.id, non_excluded_user_id, tasks[1].id)
        ]
        _, category_keys = get_reserve_task_category_info(reserve_task_config,
                                                          1,
                                                          1,
                                                          user.id,
                                                          exclude_user=True)
        assert category_keys == expected_category_keys, "reserve task category keys should exclude user {} reserve category key".format(
            user.id)
        # cleanup; release reserve task lock
        expiry = 1
        release_reserve_task_lock_by_id(project.id,
                                        tasks[0].id,
                                        user.id,
                                        1,
                                        expiry=expiry)
        release_reserve_task_lock_by_id(project.id,
                                        tasks[1].id,
                                        non_excluded_user_id,
                                        1,
                                        expiry=expiry)
Exemplo n.º 33
0
    def test_taskrun_updates_task_state(self, guard, mock_request):
        """Test API TaskRun POST updates task state"""
        guard.return_value = mock_contributions_guard(True)
        project = ProjectFactory.create()
        task = TaskFactory.create(project=project, n_answers=2)
        url = '/api/taskrun?api_key=%s' % project.owner.api_key

        # Post first taskrun
        data = dict(
            project_id=task.project_id,
            task_id=task.id,
            user_id=project.owner.id,
            info='my task result')
        datajson = json.dumps(data)
        mock_request.data = datajson

        tmp = self.app.post(url, data=datajson)
        r_taskrun = json.loads(tmp.data)

        assert tmp.status_code == 200, r_taskrun

        err_msg = "Task state should be different from completed"
        assert task.state == 'ongoing', err_msg

        # Post second taskrun
        mock_request.remote_addr = '127.0.0.0'
        admin = UserFactory.create()
        url = '/api/taskrun?api_key=%s' % admin.api_key
        data = dict(
            project_id=task.project_id,
            task_id=task.id,
            info='my task result anon')
        datajson = json.dumps(data)
        tmp = self.app.post(url, data=datajson)
        r_taskrun = json.loads(tmp.data)

        assert tmp.status_code == 200, r_taskrun
        assert r_taskrun['user_ip'] != '127.0.0.0', r_taskrun
        err_msg = "Task state should be equal to completed"
        assert task.state == 'completed', err_msg
Exemplo n.º 34
0
    def test_task_query_list_project_ids(self):
        """Get a list of tasks using a list of project_ids."""
        projects = ProjectFactory.create_batch(3)
        tasks = []
        for project in projects:
            tmp = TaskFactory.create_batch(2, project=project)
            for t in tmp:
                tasks.append(t)

        project_ids = [project.id for project in projects]
        url = '/api/task?project_id=%s&limit=100' % project_ids
        res = self.app.get(url)
        data = json.loads(res.data)
        assert len(data) == 3 * 2, len(data)
        for task in data:
            assert task['project_id'] in project_ids
        task_project_ids = list(set([task['project_id'] for task in data]))
        assert sorted(project_ids) == sorted(task_project_ids)

        # more filters
        res = self.app.get(url + '&orderby=created&desc=true')
        data = json.loads(res.data)
        assert data[0]['id'] == tasks[-1].id

        user = UserFactory.create()
        task_orig = tasks[0]
        task_run = TaskRunFactory.create(task=task_orig, user=user)

        project_ids = [project.id for project in projects]
        url = '/api/task?project_id=%s&limit=100&participated=true&api_key=%s' % (project_ids, user.api_key)
        res = self.app.get(url)
        data = json.loads(res.data)
        assert len(data) == (3 * 2) - 1, len(data)
        for task in data:
            assert task['project_id'] in project_ids
        task_project_ids = list(set([task['project_id'] for task in data]))
        assert sorted(project_ids) == sorted(task_project_ids)
        task_ids = [task['id'] for task in data]
        err_msg = 'This task should not be in the list as the user participated.'
        assert task_orig.id not in task_ids, err_msg
Exemplo n.º 35
0
def test_create(client):
    user = UserFactory.create()
    vendor = VendorFactory.create()
    db.session.commit()
    response = client.post('/api/orders',
                           data={
                               "contributed_by": user.id,
                               "contributed_amount": "8.50",
                               "ordered_by_id": user.id,
                               "vendor_id": vendor.id,
                           })
    assert response.status_code == 201
    assert response.headers["Access-Control-Allow-Origin"] == "*"
    assert "Location" in response.headers
    obj = json.loads(response.get_data(as_text=True))
    assert "id" in obj
    url = response.headers["Location"]
    path = urlparse(url).path
    resp2 = client.get(path)
    assert resp2.status_code == 200
    created = json.loads(resp2.get_data(as_text=True))
    assert created["contributions"][0]["amount"] == "8.50"
Exemplo n.º 36
0
 def create_project_with_contributors(self,
                                      anonymous,
                                      registered,
                                      two_tasks=False,
                                      name='my_app',
                                      info={}):
     project = ProjectFactory.create(name=name, info=info)
     task = TaskFactory(project=project)
     if two_tasks:
         task2 = TaskFactory(project=project)
     for i in range(anonymous):
         task_run = AnonymousTaskRunFactory(task=task,
                                            user_ip='127.0.0.%s' % i)
         if two_tasks:
             task_run2 = AnonymousTaskRunFactory(task=task2,
                                                 user_ip='127.0.0.%s' % i)
     for i in range(registered):
         user = UserFactory.create()
         task_run = TaskRunFactory(task=task, user=user)
         if two_tasks:
             task_run2 = TaskRunFactory(task=task2, user=user)
     return project
Exemplo n.º 37
0
    def test_subscribe_user_update_existing(self, mailchimp):
        """Test subscribe user update existing works."""
        with patch.dict(self.flask_app.config, {'MAILCHIMP_API_KEY': 'k-3',
                                                'MAILCHIMP_LIST_ID': 1}):
            user = UserFactory.create()
            nw = Newsletter()
            nw.init_app(self.flask_app)

            nw.subscribe_user(user, update=True)

            email = {'email': user.email_addr}
            merge_vars = {'FNAME': user.fullname}
            url = "%s/lists/1/members/%s" % (nw.root,
                                             nw.get_email_hash(user.email_addr))
            data = dict(email_address=user.email_addr,
                        status='pending',
                        status_if_new='pending',
                        merge_fields=dict(FNAME=user.fullname))
            mailchimp.assert_called_with(url, data=json.dumps(data),
                                         headers={'content-type':
                                                  'application/json'},
                                         auth=nw.auth)
    def test_list_user_employment_endpoint(self):
        role1 = RoleFactory.create(name="admin")
        BaseTestCase.user_id()

        PermissionFactory.create(keyword="view_user_employment_history",
                                 role=role1)
        user = UserFactory.create()
        user.save()
        UserRoleFactory.create(user=user, role=role1)
        UserEmploymentFactory.create_batch(3, user=user)

        response = self.client().get(
            self.make_url(f"/user_employment_history/user/{user.id}"),
            headers=self.headers(),
        )
        response_json = self.decode_from_json_string(
            response.data.decode("utf-8"))
        payload = response_json["payload"]
        self.assert200(response)
        self.assertEqual(len(payload["user_employments"]), 3)
        self.assertJSONKeysPresent(payload["user_employments"][0],
                                   "institution_name", "job_title")
Exemplo n.º 39
0
    def test_disqus_sso_payload_auth_user(self, mock_b64encode, mock_hmac):
        """Test Disqus SSO payload auth works."""
        user = UserFactory.create()

        DISQUS_PUBLIC_KEY = 'public'
        DISQUS_SECRET_KEY = 'secret'
        patch_dict = {'DISQUS_PUBLIC_KEY': DISQUS_PUBLIC_KEY,
                      'DISQUS_SECRET_KEY': DISQUS_SECRET_KEY}
        data = json.dumps({'id': user.id,
                           'username': user.name,
                           'email': user.email_addr})

        mock_b64encode.return_value = data

        with patch.dict(self.flask_app.config, patch_dict):
            message, timestamp, sig, pub_key = util.get_disqus_sso_payload(user)
            mock_b64encode.assert_called_with(data)
            mock_hmac.assert_called_with(DISQUS_SECRET_KEY, '%s %s' % (data, timestamp),
                                         hashlib.sha1)
            assert timestamp
            assert sig
            assert pub_key == DISQUS_PUBLIC_KEY
Exemplo n.º 40
0
    def test_sync_L3_without_target(self, mock_cat):
        project_syncer = ProjectSyncer(self.target_url, self.target_key)
        user = UserFactory.create(admin=True, email_addr=u'*****@*****.**')
        project_syncer.syncer = user

        project = ProjectFactory.create()
        project.info['data_classification'] = dict(
            input_data="L3 - community", output_data="L3 - community")
        project_repo.save(project)

        # no sync info by default
        assert not project.info.get("sync")

        payload = project_syncer._build_payload(project)

        # sync existing does put request
        headers = [('Authorization', user.api_key)]
        res = self.app.put("/api/project/{}".format(project.id),
                           headers=headers,
                           data=json.dumps(payload))
        assert res.status_code == 200, 'build_payload output should result in valid api query'
        assert res.json["info"]["sync"] == payload["info"]["sync"]
    def test_query_project(self):
        """Test API query for project endpoint works"""
        ProjectFactory.create(short_name='test-app', name='My New Project')
        user = UserFactory.create()
        # Test for real field
        res = self.app.get('/api/projectbyname/test-app?api_key=' + user.api_key, follow_redirects=True)
        data = json.loads(res.data)
        # Should return one result
        # Correct result
        assert data['short_name'] == 'test-app', data

        # Valid field but wrong value
        res = self.app.get('/api/projectbyname/wrongvalue?api_key=' + user.api_key)
        data = json.loads(res.data)
        assert data['status_code'] == 404, data

        # Multiple fields
        res = self.app.get('/api/projectbyname/test-app?name=My New Project&api_key=' + user.api_key)
        data = json.loads(res.data)
        # Correct result
        assert data['short_name'] == 'test-app', data
        assert data['name'] == 'My New Project', data
Exemplo n.º 42
0
    def test_newtask(self):
        """Test API project new_task method and authentication"""
        project = ProjectFactory.create()
        project.set_password('the_password')
        project_repo.save(project)
        TaskFactory.create_batch(2,
                                 project=project,
                                 info={'question': 'answer'})
        user = UserFactory.create()

        # anonymous
        # test getting a new task
        res = self.app.get('/api/project/%s/newtask' % project.id)
        assert res, res
        task = json.loads(res.data)
        assert 'error' in task['info'], 'No anonymous contributors'

        # as a real user, no password
        url = '/api/project/%s/newtask?api_key=%s' % (project.id, user.api_key)
        res = self.app.get(url)
        assert res.status_code == 403, res
        task = json.loads(res.data)
        assert task['exception_msg'] == 'No project password provided'

        url = '/project/%s/password?api_key=%s' % (project.short_name,
                                                   user.api_key)
        data = dict(password='******')
        res = self.app.post(url, data=data)

        c, v, e = get_pwd_cookie(project.short_name, res)

        assert c
        self.app.set_cookie('/', c, v)

        url = '/api/project/%s/newtask?api_key=%s' % (project.id, user.api_key)
        res = self.app.get(url)
        assert res.status_code == 200, res
        task = json.loads(res.data)
        assert task['info'].get('question') == 'answer'
Exemplo n.º 43
0
 def create_app_with_contributors(self,
                                  anonymous,
                                  registered,
                                  two_tasks=False,
                                  name='my_app',
                                  hidden=0):
     app = AppFactory.create(name=name, hidden=hidden)
     task = TaskFactory(app=app)
     if two_tasks:
         task2 = TaskFactory(app=app)
     for i in range(anonymous):
         task_run = AnonymousTaskRunFactory(task=task,
                                            user_ip='127.0.0.%s' % i)
         if two_tasks:
             task_run2 = AnonymousTaskRunFactory(task=task2,
                                                 user_ip='127.0.0.%s' % i)
     for i in range(registered):
         user = UserFactory.create()
         task_run = TaskRunFactory(task=task, user=user)
         if two_tasks:
             task_run2 = TaskRunFactory(task=task2, user=user)
     return app
Exemplo n.º 44
0
    def test_get_inactive_users_returns_jobs(self):
        """Test JOB get inactive users returns a list of jobs."""

        today = datetime.datetime.today()
        old_date = today - datetime.timedelta(days=120)
        date_str = old_date.strftime('%Y-%m-%dT%H:%M:%S.%f')
        if calendar.isleap(today.year):
            n_days_year = 366
        else:
            n_days_year = 365
        one_year = today - datetime.timedelta(days=n_days_year)
        one_year_str = one_year.strftime('%Y-%m-%dT%H:%M:%S.%f')
        user = UserFactory.create()
        # 3 months old contribution
        tr = TaskRunFactory.create(finish_time=date_str)
        # 1 year old contribution
        TaskRunFactory.create(finish_time=one_year_str)
        # User with a contribution from a long time ago
        TaskRunFactory.create(finish_time="2010-08-08T18:23:45.714110",
                              user=user)
        # User with a recent contribution
        TaskRunFactory.create(user=user)
        user = user_repo.get(tr.user_id)

        jobs_generator = get_inactive_users_jobs()
        jobs = []
        for job in jobs_generator:
            jobs.append(job)

        msg = "There should be one job."
        print jobs
        assert len(jobs) == 1, msg
        job = jobs[0]
        args = job['args'][0]
        assert job['queue'] == 'quaterly', job['queue']
        assert len(args['recipients']) == 1
        assert args['recipients'][0] == user.email_addr, args['recipients'][0]
        assert "UNSUBSCRIBE" in args['body']
        assert "Update" in args['html']
Exemplo n.º 45
0
    def test_completedtask_completedtaskrun_with_params(self):
        """Test API query for completedtask and completedtaskrun with params works"""
        project = ProjectFactory.create()
        task = TaskFactory.create(project=project,
                                  n_answers=2,
                                  state='ongoing',
                                  exported=False)
        admin = UserFactory.create()
        # Test no completedtask yet
        url = '/api/completedtask?project_id=1&api_key=api-key1'
        res = self.app.get(url)
        data = json.loads(res.data)
        assert len(data) == 0, data

        # mark task as completed
        task_runs = TaskRunFactory.create_batch(2, task=task)
        task.state = 'completed'
        task_repo.update(task)

        #  test task is completed
        url = '/api/completedtask?project_id=1&api_key=api-key1'
        res = self.app.get(url)
        data = json.loads(res.data)

        # correct result
        assert data[0]['project_id'] == 1, data
        assert data[0]['state'] == u'completed', data

        # call completedtask but with wrong project_id
        url = '/api/completedtask?project_id=99999999&api_key=api-key1'
        res = self.app.get(url)
        data = json.loads(res.data)
        assert len(data) == 0, data

        # get completed task runs
        url = '/api/completedtaskrun?project_id=1&api_key=api-key1'
        res = self.app.get(url)
        data = json.loads(res.data)
        assert len(data) == 2, data
Exemplo n.º 46
0
    def test_create_dict_job(self):
        """Test JOB create dict job works."""
        user = UserFactory.create(pro=True)
        project = ProjectFactory.create(owner=user)
        from sqlalchemy.sql import text
        from pybossa.core import db
        sql = text(
            '''SELECT project.id, project.short_name FROM project, "user"
                   WHERE project.owner_id="user".id AND "user".pro=True;''')
        results = db.slave_session.execute(sql)
        jobs_generator = create_dict_jobs(results, get_project_stats,
                                          (10 * 60))
        jobs = []
        for job in jobs_generator:
            jobs.append(job)

        err_msg = "There should be only one job"
        assert len(jobs) == 1, err_msg

        job = jobs[0]
        assert 'get_project_stats' in job['name'].__name__
        assert job['args'] == [project.id, project.short_name]
Exemplo n.º 47
0
    def test_csv_returns_all_users(self):
        restricted = UserFactory.create(restrict=True, id=5000016)
        self.register(fullname="Manolita")
        self.signout()
        self.register(fullname="Juan Jose",
                      name="juan",
                      email="*****@*****.**",
                      password="******")
        self.signout()
        self.register(fullname="Juan Jose2",
                      name="juan2",
                      email="*****@*****.**",
                      password="******")
        self.signin()

        res = self.app.get('/admin/users/export?format=csv',
                           follow_redirects=True)
        data = res.data
        assert restricted.name not in str(data.decode('utf-8'))
        import pandas as pd
        df = pd.read_csv(io.StringIO(data.decode('utf-8')))
        assert df.shape[0] == 3, df.shape[0]
Exemplo n.º 48
0
    def test_email_notif(self, get_contrib_emails):
        """
        if the project is configured, email notifications will be sent
        """
        owner = UserFactory.create(id=500, user_pref={'languages': ['en']})

        project = ProjectFactory.create(owner=owner, email_notif=True)
        project.info['sched'] = Schedulers.user_pref
        project_repo.save(project)
        tasks = TaskFactory.create_batch(1,
                                         project=project,
                                         n_answers=1,
                                         user_pref={'languages': ['en']})

        TaskRunFactory.create(task=tasks[0], user=owner)

        TaskFactory.create_batch(1,
                                 project=project,
                                 n_answers=1,
                                 user_pref={'languages': ['en']})
        send_email_notifications()
        get_contrib_emails.assert_called()
Exemplo n.º 49
0
    def test_csv_returns_all_users(self, password_needed):
        password_needed.return_value = False
        restricted = UserFactory.create(restrict=True, id=5000016)
        self.register(fullname="Manolita")
        project = self.create_project_and_tasks()
        self.signin()
        self.contribute(project)
        self.signout()

        self.register(fullname="Juan Jose",
                      name="juan",
                      email="*****@*****.**",
                      password="******")
        self.signin(email="*****@*****.**", password="******")
        self.contribute(project)
        self.signout()

        self.register(fullname="Juan Jose2",
                      name="juan2",
                      email="*****@*****.**",
                      password="******")
        self.signin(email="*****@*****.**", password="******")
        self.contribute(project)
        self.signout()
        self.signin()

        res = self.app.get('/admin/users/export?format=csv',
                           follow_redirects=True)
        data = res.data
        assert restricted.name not in data
        csv_content = StringIO.StringIO(data)
        csvreader = unicode_csv_reader(csv_content)
        # number of users is -1 because the first row in csv are the headers
        number_of_users = -1
        for row in csvreader:
            number_of_users += 1

        assert number_of_users == 4, number_of_users  # user report returning all users also returns [email protected]
Exemplo n.º 50
0
    def test_newtask_expired_cookie(self):
        """Test API project new_task expired cookie"""
        project = ProjectFactory.create(info={'timeout': 60})
        project.set_password('the_password')
        project_repo.save(project)
        TaskFactory.create_batch(2,
                                 project=project,
                                 info={'question': 'answer'})
        user = UserFactory.create()

        # simulate sending expired cookies
        with patch.dict(self.flask_app.config, {'PASSWD_COOKIE_TIMEOUT': -1}):
            url = '/project/%s/password?api_key=%s' % (project.short_name,
                                                       user.api_key)
            data = dict(password='******')
            res = self.app.post(url, data=data)

            c, v, e = get_pwd_cookie(project.short_name, res)

            assert c
            self.app.set_cookie('/', c, v)
            res = self.app.post(url, data=data)
            c, v, e = get_pwd_cookie(project.short_name, res)

            assert c

            url = '/project/%s/newtask?api_key=%s' % (project.short_name,
                                                      user.api_key)
            res = self.app.get(url)
            assert res.status_code == 302
            headers = {'Content-Type': 'application/json'}
            res = self.app.get(url, headers=headers)
            next_url = json.loads(res.data)['next']
            print next_url
            headers = {'Authorization': user.api_key}
            res = self.app.get(next_url, headers=headers)

            assert 'Enter the password to contribute to this project' in res.data, res.data
Exemplo n.º 51
0
    def test_project_contact_no_disabled_owner(self, enqueue):
        """Test Project Contact not emailing a disabled co-owner."""
        message = u'hello'

        admin, owner, user = UserFactory.create_batch(3)

        # Create a disabled user as a co-owner.
        coowner = UserFactory.create(name='My Disabled Co-Owner User',
                                     enabled=False,
                                     subadmin=True)

        # Create a project with a disabled co-owner.
        project = ProjectFactory.create(owner=owner,
                                        short_name='test-app',
                                        name='My New Project',
                                        owners_ids=[coowner.id])

        # Obtain a CSRF key.
        csrf = self.get_csrf('/account/signin')

        # Make a request to the api.
        url = '/project/' + project.short_name + '/contact?api_key=' + user.api_key
        data = dict(message=message)
        res = self.app.post(url,
                            headers={'X-CSRFToken': csrf},
                            content_type='application/json',
                            data=json.dumps(data))

        # Get contents of email.
        str_message = str(enqueue.call_args_list[0])

        # Verify recipient for project owner.
        recipients_index = str_message.find('recipients')
        assert recipients_index > -1
        assert str_message.find(owner.email_addr) > recipients_index

        # Verify no recipient for disabled co-owner.
        assert str_message.find(coowner.email_addr) == -1
Exemplo n.º 52
0
    def test_get_locked_task(self):
        owner = UserFactory.create(id=500)
        project = ProjectFactory.create(owner=owner)
        project.info['sched'] = Schedulers.locked
        project_repo.save(project)

        task1 = TaskFactory.create(project=project, info='task 1', n_answers=2)
        task2 = TaskFactory.create(project=project, info='task 2', n_answers=2)

        t1 = get_locked_task(project.id, 11)
        t2 = get_locked_task(project.id, 1)
        assert t1[0].id == task1.id
        assert t2[0].id == task1.id
        t3 = get_locked_task(project.id, 2)
        t4 = get_locked_task(project.id, 3)
        assert t3[0].id == task2.id
        assert t4[0].id == task2.id

        t5 = get_locked_task(project.id, 11)
        assert t5[0].id == task1.id

        t6 = get_locked_task(project.id, 4)
        assert not t6
Exemplo n.º 53
0
    def test_get_active_users_lock(self):
        """ Test number of locked tasks"""
        user = UserFactory.create(id=500)
        project = ProjectFactory.create(owner=user, info={'sched': 'default'})
        TaskFactory.create_batch(2, project=project, n_answers=2)

        # Register the active user as a locked task.
        register_active_user(project.id, user.id, sentinel.master)
        # Verify the count of locked tasks for this project equals 1.
        count = get_active_user_count(project.id, sentinel.master)
        assert count == 1

        # Unregister the active user as a locked task.
        unregister_active_user(project.id, user.id, sentinel.master)
        # Verify the count of locked tasks for this project equals 1.
        # There is a delay before the lock is released.
        count = get_active_user_count(project.id, sentinel.master)
        assert count == 1

        # Confirm lock released after a delay.
        time.sleep(EXPIRE_LOCK_DELAY + 1)
        count = get_active_user_count(project.id, sentinel.master)
        assert not count
Exemplo n.º 54
0
    def test_query_sql_injection(self):
        """Test API SQL Injection is not allowed works"""

        user = UserFactory.create()
        q = '1%3D1;SELECT%20*%20FROM%20task%20WHERE%201=1'
        res = self.app.get('/api/task?%s&api_key=%s' % (q, user.api_key))
        error = json.loads(res.data)
        assert res.status_code == 415, error
        assert error['action'] == 'GET', error
        assert error['status'] == 'failed', error
        assert error['target'] == 'task', error

        q = 'project_id=1%3D1;SELECT%20*%20FROM%20task%20WHERE%201'
        res = self.app.get('/api/apappp?' + q)
        assert res.status_code == 404, res.data

        q = 'project_id=1%3D1;SELECT%20*%20FROM%20task%20WHERE%201'
        res = self.app.get('/api/' + q)
        assert res.status_code == 404, res.data

        q = 'project_id=1%3D1;SELECT%20*%20FROM%20task%20WHERE%201'
        res = self.app.get('/api' + q)
        assert res.status_code == 404, res.data
Exemplo n.º 55
0
 def test_task_routing_2(self):
     '''
     task[0]: needs finance skill at least 0.8, should not be able to assign to the user
     task[1]: needs geography skill at least 0.5, should not be able to assign to the user
     task[3]: doesnt have filters, should be able to assign to the user
     '''
     user_info = dict(
         metadata={
             "profile": json.dumps({
                 "finance": 0.6,
                 "marketing": 0.4
             })
         })
     owner = UserFactory.create(id=500, info=user_info)
     user_repo.save(owner)
     project = ProjectFactory.create(owner=owner)
     project.info['sched'] = Schedulers.user_pref
     tasks = TaskFactory.create_batch(3, project=project, n_answers=10)
     tasks[0].worker_filter = {'finance': [0.8, '>=']}
     task_repo.save(tasks[0])
     tasks[1].worker_filter = {'geography': [0.5, '>=']}
     task_repo.save(tasks[1])
     assert n_available_tasks_for_user(project, 500) == 1
Exemplo n.º 56
0
    def test_query_projectstats_filter_project(self):
        owner = UserFactory.create()
        project1, project2 = ProjectFactory.create_batch(2, owner=owner)

        stats = PerformanceStatsFactory.create(user_id=owner.id,
                                               project_id=project1.id,
                                               info={'project': project1.id})
        stats = PerformanceStatsFactory.create(user_id=owner.id,
                                               project_id=project2.id,
                                               info={'project': project2.id})

        url = '/api/performancestats'
        res = self.app.get('{}?api_key={}&project_id={}'.format(
            url, owner.api_key, project1.id))
        data = json.loads(res.data)
        assert len(data) == 1
        assert data[0]['info']['project'] == project1.id

        res = self.app.get('{}?api_key={}&project_id={}'.format(
            url, owner.api_key, project2.id))
        data = json.loads(res.data)
        assert len(data) == 1
        assert data[0]['info']['project'] == project2.id
Exemplo n.º 57
0
    def test_subscribe_user_update_existing(self, mailchimp):
        """Test subscribe user update existing works."""
        with patch.dict(self.flask_app.config, {
                'MAILCHIMP_API_KEY': 'k-3',
                'MAILCHIMP_LIST_ID': 1
        }):
            user = UserFactory.create()
            nw = Newsletter()
            nw.init_app(self.flask_app)

            old_email = '*****@*****.**'

            tmp = {'data': [{'email': old_email}], 'success_count': 1}
            nw.client.lists.member_info.return_value = tmp

            nw.subscribe_user(user, old_email=old_email)

            email = {'email': old_email}
            merge_vars = {'FNAME': user.fullname, 'new-email': user.email_addr}
            nw.client.lists.subscribe.assert_called_with(1,
                                                         email,
                                                         merge_vars,
                                                         update_existing=True)
Exemplo n.º 58
0
    def test_task_priority_limit(self):
        """Test SCHED respects priority_0 field with limit"""
        project = ProjectFactory.create(info=dict(sched='depth_first_all'),
                                        owner=UserFactory.create(id=500))

        TaskFactory.create_batch(10, project=project)

        # Register
        self.register()
        self.signin()

        # By default, tasks without priority should be ordered by task.id (FIFO)
        tasks = db.session.query(Task).filter_by(
            project_id=project.id).order_by('id').all()
        url = 'api/project/%s/newtask?limit=2' % project.id
        self.set_proj_passwd_cookie(project, username='******')
        res = self.app.get(url)
        tasks1 = json.loads(res.data)
        # Check that we received a Task
        err_msg = "Task.id should be the same"
        assert tasks1[0].get('id') == tasks[0].id, err_msg

        # Now let's change the priority to a random task
        import random
        t = random.choice(tasks)
        # Increase priority to maximum
        t.priority_0 = 1
        db.session.add(t)
        db.session.commit()
        # Request again a new task
        res = self.app.get(url + '&orderby=priority_0&desc=true')
        tasks1 = json.loads(res.data)
        # Check that we received a Task
        err_msg = "Task.id should be the same"
        assert tasks1[0].get('id') == t.id, (err_msg, tasks1[0])
        err_msg = "Task.priority_0 should be the 1"
        assert tasks1[0].get('priority_0') == 1, err_msg
Exemplo n.º 59
0
    def test_newtask(self):
        """Test API project new_task method and authentication"""
        project = ProjectFactory.create()
        TaskFactory.create_batch(2, project=project)
        user = UserFactory.create()

        # anonymous
        # test getting a new task
        res = self.app.get('/api/project/%s/newtask' % project.id)
        assert res, res
        task = json.loads(res.data)
        assert_equal(task['project_id'], project.id)

        # The output should have a mime-type: application/json
        assert res.mimetype == 'application/json', res

        # as a real user
        url = '/api/project/%s/newtask?api_key=%s' % (project.id, user.api_key)
        res = self.app.get(url)
        assert res, res
        task = json.loads(res.data)
        assert_equal(task['project_id'], project.id)

        # Get NotFound for an non-existing project
        url = '/api/project/5000/newtask'
        res = self.app.get(url)
        err = json.loads(res.data)
        err_msg = "The project does not exist"
        assert err['status'] == 'failed', err_msg
        assert err['status_code'] == 404, err
        assert err['exception_cls'] == 'NotFound', err_msg
        assert err['target'] == 'project', err_msg

        # Get an empty task
        url = '/api/project/%s/newtask?offset=1000' % project.id
        res = self.app.get(url)
        assert res.data == '{}', res.data
Exemplo n.º 60
0
    def test_project_create(self):
        """Test Auditlog API project create works."""
        CategoryFactory.create()
        user = UserFactory.create()

        data = {
            'name':
            'New Name',
            'short_name':
            'new_short_name',
            'description':
            'new_description',
            'long_description':
            'new_long_description',
            'allow_anonymous_contributors':
            False,
            'info':
            dict(passwd_hash="hello",
                 data_classification=dict(input_data="L4 - public",
                                          output_data="L4 - public")),
            'zip_download':
            True
        }
        url = '/api/project?api_key=%s' % (user.api_key)
        self.app.post(url, data=json.dumps(data))
        logs = auditlog_repo.filter_by(project_short_name='new_short_name')

        assert len(logs) == 1, logs
        for log in logs:
            assert log.user_id == user.id, log.user_id
            assert log.user_name == user.name, log.user_name
            assert log.project_short_name == 'new_short_name', log.project_short_name
            assert log.caller == 'api', log.caller
            assert log.action == 'create', log.action
            assert log.attribute == 'project', log.attribute
            assert log.old_value == 'Nothing', log.old_value
            assert log.new_value == 'New project', log.new_value