Ejemplo n.º 1
0
    def test_staff_task(self, mock_staff, mock_restaff):
        # Staff a task with no assignment
        unassigned_task = self.tasks['awaiting_processing']
        response = self.api_client.post(
            reverse(
                'orchestra:orchestra:project_management:staff_task'),
            json.dumps({
                'task_id': unassigned_task.id
            }),
            content_type='application/json')
        self.assertTrue(mock_staff.called)
        self.assertEqual(response.status_code, 200)
        is_restaff = load_encoded_json(response.content)['is_restaff']
        self.assertFalse(is_restaff)

        # Restaff a task with an assignment
        assigned_task = self.tasks['review_task']
        response2 = self.api_client.post(
            reverse(
                'orchestra:orchestra:project_management:staff_task'),
            json.dumps({
                'task_id': assigned_task.id
            }),
            content_type='application/json')
        self.assertTrue(mock_restaff.called)
        self.assertEqual(response2.status_code, 200)
        is_restaff2 = load_encoded_json(response2.content)['is_restaff']
        self.assertTrue(is_restaff2)
Ejemplo n.º 2
0
    def _test_reverted_task(self, task, iteration, num_iterations,
                            task_status, latest_data, expected_audit,
                            revert_before=False):
        response = self._revert_task(
            task, iteration, revert_before=revert_before, commit=False)
        self.assertEqual(response.status_code, 200)
        task.refresh_from_db()
        fake_audit = load_encoded_json(response.content)
        self.assertEqual(fake_audit, expected_audit)

        self.assertEqual(task.status, Task.Status.COMPLETE)
        self.assertEqual(task.assignments.count(), 2)
        for assignment in task.assignments.all():
            self.assertEqual(assignment.iterations.count(), 2)

        response = self._revert_task(
            task, iteration, revert_before=revert_before, commit=True)
        self.assertEqual(response.status_code, 200)
        task.refresh_from_db()
        audit = load_encoded_json(response.content)
        self.assertEqual(audit, fake_audit)
        task.refresh_from_db()
        self.assertEqual(task.status, task_status)
        self.assertEqual(
            get_iteration_history(task).count(), num_iterations)

        verify_iterations(task.id)

        if num_iterations:
            self.assertEqual(
                current_assignment(task).in_progress_task_data,
                latest_data)

        verify_iterations(task.id)
    def _test_reverted_task(self, task, iteration, num_iterations,
                            task_status, latest_data, expected_audit,
                            revert_before=False):
        response = self._revert_task(
            task, iteration, revert_before=revert_before, commit=False)
        self.assertEquals(response.status_code, 200)
        task.refresh_from_db()
        fake_audit = load_encoded_json(response.content)
        self.assertEqual(fake_audit, expected_audit)

        self.assertEquals(task.status, Task.Status.COMPLETE)
        self.assertEquals(task.assignments.count(), 2)
        for assignment in task.assignments.all():
            self.assertEquals(assignment.iterations.count(), 2)

        response = self._revert_task(
            task, iteration, revert_before=revert_before, commit=True)
        self.assertEqual(response.status_code, 200)
        task.refresh_from_db()
        audit = load_encoded_json(response.content)
        self.assertEqual(audit, fake_audit)
        task.refresh_from_db()
        self.assertEqual(task.status, task_status)
        self.assertEqual(
            get_iteration_history(task).count(), num_iterations)

        verify_iterations(task.id)

        if num_iterations:
            self.assertEquals(
                current_assignment(task).in_progress_task_data,
                latest_data)

        verify_iterations(task.id)
Ejemplo n.º 4
0
def assign_task_api(request):
    worker_username = load_encoded_json(request.body)['worker_username']
    try:
        worker = Worker.objects.get(user__username=worker_username)
        task_id = load_encoded_json(request.body)['task_id']
        assign_task(worker.id, task_id)
    except (Worker.DoesNotExist, Task.DoesNotExist,
            WorkerCertificationError) as e:
        raise BadRequest(e)
Ejemplo n.º 5
0
def assign_task_api(request):
    worker_username = load_encoded_json(request.body)['worker_username']
    try:
        worker = Worker.objects.get(user__username=worker_username)
        task_id = load_encoded_json(request.body)['task_id']
        assign_task(worker.id, task_id)
    except (Worker.DoesNotExist,
            Task.DoesNotExist,
            WorkerCertificationError) as e:
        raise BadRequest(e)
Ejemplo n.º 6
0
def reassign_assignment_api(request):
    worker_username = load_encoded_json(request.body)['worker_username']
    try:
        worker = Worker.objects.get(user__username=worker_username)
    except Worker.DoesNotExist:
        raise BadRequest('Worker not found for the given username.')
    assignment_id = load_encoded_json(request.body)['assignment_id']

    try:
        reassign_assignment(worker.id, assignment_id)
    except (WorkerCertificationError, TaskAssignmentError) as e:
        raise BadRequest(e)
Ejemplo n.º 7
0
def reassign_assignment_api(request):
    worker_username = load_encoded_json(request.body)['worker_username']
    try:
        worker = Worker.objects.get(user__username=worker_username)
    except Worker.DoesNotExist:
        raise BadRequest('Worker not found for the given username.')
    assignment_id = load_encoded_json(request.body)['assignment_id']

    try:
        reassign_assignment(worker.id, assignment_id)
    except (WorkerCertificationError, TaskAssignmentError) as e:
        raise BadRequest(e)
Ejemplo n.º 8
0
    def test_entry_level_task_assignment(self):
        response = (self.clients[2].get(
            '/orchestra/api/interface/new_task_assignment/entry_level/'))

        # no task available for user3 because no entry-level certification
        self.assertEquals(response.status_code, 400)
        returned = load_encoded_json(response.content)
        self.assertEquals(returned['message'],
                          'No worker certificates')

        # user 0 only has certification for entry level tasks
        response = (self.clients[0].get(
            '/orchestra/api/interface/new_task_assignment/entry_level/'))
        self.assertEquals(response.status_code, 200)
        returned = load_encoded_json(response.content)

        task = Task.objects.get(id=returned['id'])
        self.assertEquals({
            'id': task.id,
            'assignment_id': task.assignments.get(worker=self.workers[0]).id,
            'step': task.step.slug,
            'project': task.project.workflow_version.slug,
            'detail': task.project.short_description
        }, returned)

        # task assignment for invalid id should give bad request
        self._verify_bad_task_assignment_information(
            self.clients[0], {'task_id': -1},
            'Task matching query does not exist.')

        # task assignment for user3 not assigned to a task
        self._verify_bad_task_assignment_information(
            self.clients[2], {'task_id': task.id},
            'Worker is not associated with task')

        # task assignment is assigned to user 0
        self._verify_good_task_assignment_information(
            self.clients[0], {'task_id': task.id},
            task.project.short_description,
            'Processing', 'Processing', False,
            False, {}, self.workers[0])

        # no more tasks for user 0 left
        response = (self.clients[0].get(
            '/orchestra/api/interface/new_task_assignment/entry_level/'))
        self.assertEquals(response.status_code, 400)
        returned = load_encoded_json(response.content)
        self.assertEquals(returned['message'],
                          'No task')
Ejemplo n.º 9
0
    def test_save_entry_level_task_assignment(self):
        # user 0 only has certification for entry level tasks
        response = (self.clients[0].get(
            '/orchestra/api/interface/new_task_assignment/entry_level/'))
        self.assertEqual(response.status_code, 200)
        returned = load_encoded_json(response.content)
        task = Task.objects.get(id=returned['id'])

        # incorrect task id
        response = self.clients[0].post(
            '/orchestra/api/interface/save_task_assignment/',
            json.dumps({
                'task_id': -1,
                'task_data': 'test'
            }),
            content_type='application/json')
        self.assertEqual(response.status_code, 400)
        returned = load_encoded_json(response.content)
        self.assertEqual(returned['message'], 'No task for given id')

        # user does not have a permission to save
        response = self.clients[1].post(
            '/orchestra/api/interface/save_task_assignment/',
            json.dumps({
                'task_id': task.id,
                'task_data': 'test'
            }),
            content_type='application/json')
        self.assertEqual(response.status_code, 400)
        returned = load_encoded_json(response.content)
        self.assertEqual(returned['message'],
                         'Worker is not associated with task')

        # save new info
        new_data = {'new_test_key': 'new_test_value'}
        response = self.clients[0].post(
            '/orchestra/api/interface/save_task_assignment/',
            json.dumps({
                'task_id': task.id,
                'task_data': new_data
            }),
            content_type='application/json')
        self.assertEqual(response.status_code, 200)

        self._verify_good_task_assignment_information(
            self.clients[0], {'task_id': task.id},
            task.project.short_description, 'Processing', 'Processing', False,
            False, new_data, self.workers[0])
Ejemplo n.º 10
0
    def test_entry_level_task_assignment(self):
        response = (self.clients[2].get(
            '/orchestra/api/interface/new_task_assignment/entry_level/'))

        # no task available for user3 because no entry-level certification
        self.assertEqual(response.status_code, 400)
        returned = load_encoded_json(response.content)
        self.assertEqual(returned['message'], 'No worker certificates')

        # user 0 only has certification for entry level tasks
        response = (self.clients[0].get(
            '/orchestra/api/interface/new_task_assignment/entry_level/'))
        self.assertEqual(response.status_code, 200)
        returned = load_encoded_json(response.content)

        task = Task.objects.get(id=returned['id'])
        self.assertEqual(
            {
                'id': task.id,
                'assignment_id':
                task.assignments.get(worker=self.workers[0]).id,
                'step': task.step.slug,
                'project': task.project.workflow_version.slug,
                'detail': task.project.short_description
            }, returned)

        # task assignment for invalid id should give bad request
        self._verify_bad_task_assignment_information(
            self.clients[0], {'task_id': -1},
            'Task matching query does not exist.')

        # task assignment for user3 not assigned to a task
        self._verify_bad_task_assignment_information(
            self.clients[2], {'task_id': task.id},
            'Worker is not associated with task')

        # task assignment is assigned to user 0
        self._verify_good_task_assignment_information(
            self.clients[0], {'task_id': task.id},
            task.project.short_description, 'Processing', 'Processing', False,
            False, {}, self.workers[0])

        # no more tasks for user 0 left
        response = (self.clients[0].get(
            '/orchestra/api/interface/new_task_assignment/entry_level/'))
        self.assertEqual(response.status_code, 400)
        returned = load_encoded_json(response.content)
        self.assertEqual(returned['message'], 'No task')
Ejemplo n.º 11
0
def submit_task_assignment(request):
    assignment_information = load_encoded_json(request.body)
    worker = Worker.objects.get(user=request.user)
    command_type = assignment_information['command_type']

    if command_type in ('submit', 'accept'):
        iteration_status = Iteration.Status.REQUESTED_REVIEW
    elif command_type == 'reject':
        iteration_status = Iteration.Status.PROVIDED_REVIEW
    else:
        raise BadRequest('Illegal command')

    try:
        submit_task(assignment_information['task_id'],
                    assignment_information['task_data'],
                    iteration_status,
                    worker)
        return {}
    except TaskStatusError:
        raise BadRequest('Task already completed')
    except Task.DoesNotExist:
        raise BadRequest('No task for given id')
    except IllegalTaskSubmission as e:
        raise BadRequest(e)
    except TaskAssignmentError as e:
        raise BadRequest(e)
Ejemplo n.º 12
0
    def test_project_assignment_recorded_time(self):
        project = self.projects['base_test_project']
        worker = self.workers[0]

        task = self.tasks['review_task']
        assignment = TaskAssignment.objects.filter(worker=worker,
                                                   task=task).first()
        other_assignment = get_new_task_assignment(
            worker, Task.Status.AWAITING_PROCESSING)

        # create 3 time entries
        TimeEntry.objects.create(worker=self.workers[0],
                                 date=datetime.datetime.now().date(),
                                 time_worked=datetime.timedelta(hours=1),
                                 assignment=assignment)
        TimeEntry.objects.create(worker=self.workers[0],
                                 date=datetime.datetime.now().date(),
                                 time_worked=datetime.timedelta(hours=1),
                                 assignment=other_assignment)
        TimeEntry.objects.create(worker=self.workers[0],
                                 date=datetime.datetime.now().date(),
                                 time_worked=datetime.timedelta(minutes=15),
                                 assignment=assignment)

        response = self.api_client.post(
            '/orchestra/api/project/project_information/',
            {'project_ids': [project.id]},
            format='json')
        returned = load_encoded_json(response.content)
        returned_task = returned[str(project.id)]['tasks']
        returned_assignment = returned_task['step1']['assignments'][0]
        recorded_time = returned_assignment['recorded_work_time']
        self.assertEqual(recorded_time, 105 * 60)  # 1:15 + 0:30
Ejemplo n.º 13
0
def create_subsequent_tasks_api(request):
    project_id = load_encoded_json(request.body)['project_id']
    try:
        project = Project.objects.get(id=project_id)
    except Project.DoesNotExist:
        raise BadRequest('Project not found for the given id.')
    create_subsequent_tasks(project)
Ejemplo n.º 14
0
def message_project_team(request):
    """
    Endpoint for sending arbitrary message to a project team.
    Payload example:
    {'message': 'Chat message', 'project_id': 'some-id-123'}
    """
    data = load_encoded_json(request.body)
    try:
        message = data['message']
        project_id = data['project_id']
        project = Project.objects.get(id=project_id)
    except KeyError:
        text = ('An object with `message` and `project_id` attributes'
                ' should be supplied')
        raise BadRequest(text)
    except Project.DoesNotExist:
        raise BadRequest('No project for given id')
    if project.slack_group_id:
        message_experts_slack_group(project.slack_group_id, message)
    else:
        error_message = (
            "The following project doesn't have slack_group_id: {}"
        ).format(project)
        raise BadRequest(error_message)
    return {'success': True}
Ejemplo n.º 15
0
def project_information(request):
    try:
        data = load_encoded_json(request.body)
        project_ids = data['project_ids']
        return get_project_information(project_ids)
    except KeyError:
        raise BadRequest('project_ids is required')
Ejemplo n.º 16
0
def create_todos_from_template(request):
    """
    Endpoint for creating todos in a project.
    Payload example:
    {
        'todolist_template_slug': 'some-template-slug-123',
        'step_slug': 'some-step-slug-123',
        'project_id': 'some-project-id-123'
        'additional_data': {
            'some_key': 'some_value'
        }
    }
    """
    data = load_encoded_json(request.body)
    try:
        todolist_template_slug = data.get('todolist_template_slug')
        step_slug = data.get('step_slug')
        project_id = data.get('project_id')
        additional_data = data.get('additional_data')
        if step_slug and project_id and todolist_template_slug:
            add_todolist_template(todolist_template_slug, project_id,
                                  step_slug, additional_data)
            todos = Todo.objects.filter(
                template__slug=todolist_template_slug,
                project__id=project_id,
                step__slug=step_slug).order_by('-created_at')
            serializer = BulkTodoSerializerWithoutQA(todos, many=True)
            return {'success': True, 'todos': serializer.data}
        else:
            text = ('An object with `template_slug`, `step_slug`,'
                    ' and `project_id` attributes should be supplied')
            raise Exception(text)
    except Exception as e:
        return {'success': False, 'errors': {'error': str(e)}}
Ejemplo n.º 17
0
def create_subsequent_tasks_api(request):
    project_id = load_encoded_json(request.body)['project_id']
    try:
        project = Project.objects.get(id=project_id)
    except Project.DoesNotExist:
        raise BadRequest('Project not found for the given id.')
    create_subsequent_tasks(project)
Ejemplo n.º 18
0
def edit_slack_membership_api(request):
    body = load_encoded_json(request.body)
    try:
        project_management.edit_slack_membership(
            body['project_id'], body['username'], body['action'])
    except slacker.Error as e:
        raise BadRequest(e)
Ejemplo n.º 19
0
def submit_task_assignment(request):
    assignment_information = load_encoded_json(request.body)
    worker = Worker.objects.get(user=request.user)
    command_type = assignment_information['command_type']

    if command_type in ('submit', 'accept'):
        iteration_status = Iteration.Status.REQUESTED_REVIEW
    elif command_type == 'reject':
        iteration_status = Iteration.Status.PROVIDED_REVIEW
    else:
        raise BadRequest('Illegal command')

    try:
        submit_task(assignment_information['task_id'],
                    assignment_information['task_data'], iteration_status,
                    worker)
        return {}
    except TaskStatusError:
        raise BadRequest('Task already completed')
    except Task.DoesNotExist:
        raise BadRequest('No task for given id')
    except IllegalTaskSubmission as e:
        raise BadRequest(e)
    except TaskAssignmentError as e:
        raise BadRequest(e)
Ejemplo n.º 20
0
def edit_slack_membership_api(request):
    body = load_encoded_json(request.body)
    try:
        project_management.edit_slack_membership(
            body['project_id'], body['username'], body['action'])
    except slacker.Error as e:
        raise BadRequest(e)
Ejemplo n.º 21
0
    def test_update_todos_from_todolist_template_success(self):
        num_todos = Todo.objects.all().count()
        update_todos_from_todolist_template_url = \
            reverse('orchestra:todos:update_todos_from_todolist_template')
        todolist_template = TodoListTemplateFactory(
            slug=self.todolist_template_slug,
            name=self.todolist_template_name,
            description=self.todolist_template_description,
            todos={
                'items': [{
                    'id':
                    1,
                    'description':
                    'todo parent',
                    'project':
                    self.project.id,
                    'step':
                    self.step.slug,
                    'items': [{
                        'id': 2,
                        'project': self.project.id,
                        'step': self.step.slug,
                        'description': 'todo child',
                        'items': []
                    }]
                }]
            },
        )
        resp = self.request_client.post(
            update_todos_from_todolist_template_url, {
                'todolist_template': todolist_template.slug,
                'project': self.project.id,
                'step': self.step.slug
            })

        self.assertEqual(resp.status_code, 200)
        self.assertEqual(Todo.objects.all().count(), num_todos + 3)
        todos = load_encoded_json(resp.content)
        expected_todos = [
            _todo_data('todo child',
                       False,
                       template=todolist_template.id,
                       parent_todo=todos[1]['id'],
                       project=self.project.id,
                       step=self.step.slug),
            _todo_data('todo parent',
                       False,
                       template=todolist_template.id,
                       parent_todo=todos[2]['id'],
                       project=self.project.id,
                       step=self.step.slug),
            _todo_data(self.todolist_template_name,
                       False,
                       template=todolist_template.id,
                       project=self.project.id,
                       step=self.step.slug),
        ]
        for todo, expected_todo in zip(todos, expected_todos):
            self._verify_todo_content(todo, expected_todo)
Ejemplo n.º 22
0
 def ensure_response(self,
                     response,
                     expected_json_payload,
                     expected_status_code):
     self.assertEquals(response.status_code, expected_status_code)
     returned = load_encoded_json(response.content)
     self.assertEquals(returned,
                       expected_json_payload)
Ejemplo n.º 23
0
 def _verify_todolist_template_list(self, expected_todolist_templates):
     resp = self.request_client.get(self.todolist_template_list_url)
     self.assertEqual(resp.status_code, 200)
     data = load_encoded_json(resp.content)
     for todolist_template, expected_todolist_template in \
             zip(data, expected_todolist_templates):
         self._verify_todolist_template_content(todolist_template,
                                                expected_todolist_template)
Ejemplo n.º 24
0
    def test_staff_command(self, mock_slack, mock_mail):
        task = TaskFactory(status=Task.Status.AWAITING_PROCESSING)
        data = get_mock_slack_data(
            text='staff {}'.format(task.id),
            user_id=self.worker.slack_user_id)
        response = self.request_client.post(self.url, data)
        self.assertEqual(load_encoded_json(response.content).get('text'),
                         'Staffed task {}!'.format(task.id))

        task = TaskFactory(status=Task.Status.PENDING_REVIEW)
        data = get_mock_slack_data(
            text='staff {}'.format(task.id),
            user_id=self.worker.slack_user_id)

        response = self.request_client.post(self.url, data)
        self.assertEqual(load_encoded_json(response.content).get('text'),
                         'Staffed task {}!'.format(task.id))
Ejemplo n.º 25
0
    def test_staff_command(self, mock_slack, mock_mail):
        task = TaskFactory(status=Task.Status.AWAITING_PROCESSING)
        data = get_mock_slack_data(text='staff {}'.format(task.id),
                                   user_id=self.worker.slack_user_id)
        response = self.request_client.post(self.url, data)
        self.assertEqual(
            load_encoded_json(response.content)['attachments'][0]['text'],
            self.staffbot.staffing_success.format(task.id))

        task = TaskFactory(status=Task.Status.PENDING_REVIEW)
        data = get_mock_slack_data(text='staff {}'.format(task.id),
                                   user_id=self.worker.slack_user_id)

        response = self.request_client.post(self.url, data)
        self.assertEqual(
            load_encoded_json(response.content)['attachments'][0]['text'],
            self.staffbot.staffing_success.format(task.id))
Ejemplo n.º 26
0
 def ensure_response(self,
                     response,
                     expected_json_payload,
                     expected_status_code):
     self.assertEqual(response.status_code, expected_status_code)
     returned = load_encoded_json(response.content)
     self.assertEqual(returned,
                      expected_json_payload)
Ejemplo n.º 27
0
 def _check_client_dashboard_state(self, client, non_empty_status):
     response = client.get('/orchestra/api/interface/dashboard_tasks/')
     returned = load_encoded_json(response.content)
     for status, val in returned['tasks'].items():
         if status == non_empty_status:
             self.assertTrue(len(val) > 0)
         else:
             self.assertTrue(len(val) == 0)
Ejemplo n.º 28
0
 def test_just_args(self):
     body = b64encode(create_request_body('the_counter', 2).encode('ascii'))
     response = self.client.post(self.url,
                                 body,
                                 content_type='application/json')
     self.assertEqual(response.status_code, 200)
     self.assertEqual(load_encoded_json(response.content), {})
     self.assertEqual(CALL_COUNTER, 2)
Ejemplo n.º 29
0
 def _check_client_dashboard_state(self, client, non_empty_status):
     response = client.get('/orchestra/api/interface/dashboard_tasks/')
     returned = load_encoded_json(response.content)
     for status, val in returned['tasks'].items():
         if status == non_empty_status:
             self.assertTrue(len(val) > 0)
         else:
             self.assertTrue(len(val) == 0)
Ejemplo n.º 30
0
def project_information(request):
    try:
        data = load_encoded_json(request.body)
        project_id = data['project_id']
        return get_project_information(project_id)
    except KeyError:
        raise BadRequest('project_id is required')
    except Project.DoesNotExist:
        raise BadRequest('No project for given id')
Ejemplo n.º 31
0
def revert_task_api(request):
    body = load_encoded_json(request.body)
    try:
        audit = revert_task_to_iteration(body['task_id'], body['iteration_id'],
                                         body.get('revert_before'),
                                         body.get('commit'))
    except Task.DoesNotExist as e:
        raise BadRequest(e)
    return audit
Ejemplo n.º 32
0
def project_information(request):
    try:
        data = load_encoded_json(request.body)
        project_id = data['project_id']
        return get_project_information(project_id)
    except KeyError:
        raise BadRequest('project_id is required')
    except Project.DoesNotExist:
        raise BadRequest('No project for given id')
Ejemplo n.º 33
0
def revert_task_api(request):
    body = load_encoded_json(request.body)
    try:
        audit = revert_task_to_iteration(
            body['task_id'], body['iteration_id'],
            body.get('revert_before'), body.get('commit'))
    except Task.DoesNotExist as e:
        raise BadRequest(e)
    return audit
Ejemplo n.º 34
0
 def _verify_bad_task_assignment_information(self, client, post_data,
                                             error_message):
     response = client.post(
         '/orchestra/api/interface/task_assignment_information/',
         json.dumps(post_data),
         content_type='application/json')
     self.assertEqual(response.status_code, 400)
     returned = load_encoded_json(response.content)
     self.assertEqual(returned['message'], error_message)
Ejemplo n.º 35
0
def task_assignment_information(request):
    try:
        worker = Worker.objects.get(user=request.user)
        return get_task_overview_for_worker(
            load_encoded_json(request.body)['task_id'], worker)
    except TaskAssignmentError as e:
        raise BadRequest(e)
    except Task.DoesNotExist as e:
        raise BadRequest(e)
Ejemplo n.º 36
0
    def test_save_entry_level_task_assignment(self):
        # user 0 only has certification for entry level tasks
        response = (self.clients[0].get(
            '/orchestra/api/interface/new_task_assignment/entry_level/'))
        self.assertEquals(response.status_code, 200)
        returned = load_encoded_json(response.content)
        task = Task.objects.get(id=returned['id'])

        # incorrect task id
        response = self.clients[0].post(
            '/orchestra/api/interface/save_task_assignment/',
            json.dumps({'task_id': -1,
                        'task_data': 'test'}),
            content_type='application/json')
        self.assertEquals(response.status_code, 400)
        returned = load_encoded_json(response.content)
        self.assertEquals(returned['message'],
                          'No task for given id')

        # user does not have a permission to save
        response = self.clients[1].post(
            '/orchestra/api/interface/save_task_assignment/',
            json.dumps({'task_id': task.id,
                        'task_data': 'test'}),
            content_type='application/json')
        self.assertEquals(response.status_code, 400)
        returned = load_encoded_json(response.content)
        self.assertEquals(returned['message'],
                          'Worker is not associated with task')

        # save new info
        new_data = {'new_test_key': 'new_test_value'}
        response = self.clients[0].post(
            '/orchestra/api/interface/save_task_assignment/',
            json.dumps({'task_id': task.id,
                        'task_data': new_data}),
            content_type='application/json')
        self.assertEquals(response.status_code, 200)

        self._verify_good_task_assignment_information(
            self.clients[0], {'task_id': task.id},
            task.project.short_description,
            'Processing', 'Processing', False,
            False, new_data, self.workers[0])
Ejemplo n.º 37
0
def update_timer(request):
    worker = Worker.objects.get(user=request.user)
    try:
        if request.method == 'POST':
            data = load_encoded_json(request.body)
            time_tracking.update_timer(
                worker, data.get('description'), data.get('assignment'))
    except Exception as e:
        logger.error(e, exc_info=True)
        raise e
Ejemplo n.º 38
0
 def _verify_todos_list(self, project_id, expected_todos, success):
     resp = self.request_client.get(self.list_create_url,
                                    {'project__id': project_id})
     if success:
         self.assertEqual(resp.status_code, 200)
         data = load_encoded_json(resp.content)
         for todo, expected_todo in zip(data, expected_todos):
             self._verify_todo_content(todo, expected_todo)
     else:
         self.assertEqual(resp.status_code, 403)
Ejemplo n.º 39
0
def update_timer(request):
    worker = Worker.objects.get(user=request.user)
    try:
        if request.method == 'POST':
            data = load_encoded_json(request.body)
            time_tracking.update_timer(worker, data.get('description'),
                                       data.get('assignment'))
    except Exception as e:
        logger.error(e, exc_info=True)
        raise e
Ejemplo n.º 40
0
 def test_no_dispatch(self):
     response = self.client.post(
         self.url,
         b64encode(create_request_body('some_func').encode('ascii')),
         content_type='application/json')
     self.assertEqual(response.status_code, 400)
     self.assertEqual(load_encoded_json(response.content), {
         'message': 'No beanstalk dispatch table configured',
         'error': 400
     })
Ejemplo n.º 41
0
def task_assignment_information(request):
    try:
        worker = Worker.objects.get(user=request.user)
        return get_task_overview_for_worker(
            load_encoded_json(request.body)['task_id'],
            worker)
    except TaskAssignmentError as e:
        raise BadRequest(e)
    except Task.DoesNotExist as e:
        raise BadRequest(e)
Ejemplo n.º 42
0
 def test_get_timer(self, mock_get):
     timer = TaskTimer(worker=self.worker, start_time=timezone.now())
     timer.save()
     resp = self.request_client.get(
         reverse('orchestra:orchestra:get_timer'))
     mock_get.assert_called_with(self.worker)
     data = load_encoded_json(resp.content)
     expected = TaskTimerSerializer(timer).data
     expected['time_worked'] = '1:00:00'
     self.assertEqual(data, expected)
Ejemplo n.º 43
0
def unarchive_slack_channel_api(request):
    body = load_encoded_json(request.body)
    try:
        project_id = body.get('project_id')
        project = Project.objects.get(id=project_id)
        unarchive_project_slack_group(project)
    except Project.DoesNotExist:
        raise BadRequest('Project not found for the given id.')
    except slacker.Error as e:
        raise BadRequest(e)
Ejemplo n.º 44
0
def upload_image(request):
    upload_data = load_encoded_json(request.body)
    image_type = upload_data['image_type']
    image_data = base64.b64decode(upload_data['image_data'])
    prefix = upload_data.get('prefix') or ''
    if settings.PRODUCTION:
        prefix = os.path.join('production', prefix)
    else:
        prefix = os.path.join('development', prefix)
    return {'url': upload_editor_image(image_data, image_type, prefix)}
Ejemplo n.º 45
0
    def test_staff_command(self, mock_slack, mock_mail):
        task = TaskFactory(status=Task.Status.AWAITING_PROCESSING)
        data = get_mock_slack_data(
            text='staff {}'.format(task.id),
            user_id=self.worker.slack_user_id)
        response = self.request_client.post(self.url, data)
        self.assertEqual(
            load_encoded_json(response.content)['attachments'][0]['text'],
            self.staffbot.staffing_success.format(task.id))

        task = TaskFactory(status=Task.Status.PENDING_REVIEW)
        data = get_mock_slack_data(
            text='staff {}'.format(task.id),
            user_id=self.worker.slack_user_id)

        response = self.request_client.post(self.url, data)
        self.assertEqual(
            load_encoded_json(response.content)['attachments'][0]['text'],
            self.staffbot.staffing_success.format(task.id))
Ejemplo n.º 46
0
 def _verify_bad_task_assignment_information(
         self, client, post_data, error_message):
     response = client.post(
         '/orchestra/api/interface/task_assignment_information/',
         json.dumps(post_data),
         content_type='application/json')
     self.assertEquals(response.status_code, 400)
     returned = load_encoded_json(response.content)
     self.assertEquals(returned['message'],
                       error_message)
Ejemplo n.º 47
0
def upload_image(request):
    upload_data = load_encoded_json(request.body)
    image_type = upload_data['image_type']
    image_data = base64.b64decode(upload_data['image_data'])
    prefix = upload_data.get('prefix') or ''
    if settings.PRODUCTION:
        prefix = os.path.join('production', prefix)
    else:
        prefix = os.path.join('development', prefix)
    return {'url': upload_editor_image(image_data, image_type, prefix)}
Ejemplo n.º 48
0
def save_task_assignment(request):
    assignment_information = load_encoded_json(request.body)
    worker = Worker.objects.get(user=request.user)
    try:
        save_task(assignment_information['task_id'],
                  assignment_information['task_data'], worker)
        return {}
    except Task.DoesNotExist:
        raise BadRequest('No task for given id')
    except TaskAssignmentError as e:
        raise BadRequest(e)
Ejemplo n.º 49
0
 def test_start_timer(self, mock_start):
     timer = TaskTimer(worker=self.worker, start_time=self.time)
     timer.save()
     mock_start.return_value = timer
     resp = self.request_client.post(
         reverse('orchestra:orchestra:start_timer'),
         data=json.dumps({'assignment': '11'}),
         content_type='application/json')
     mock_start.assert_called_with(self.worker, assignment_id='11')
     data = load_encoded_json(resp.content)
     serializer = TaskTimerSerializer(timer)
     self.assertEqual(data, serializer.data)
Ejemplo n.º 50
0
 def test_get_timer(self, mock_get):
     timer = TaskTimer(
         worker=self.worker,
         start_time=timezone.now())
     timer.save()
     resp = self.request_client.get(
         reverse('orchestra:orchestra:get_timer'))
     mock_get.assert_called_with(self.worker)
     data = load_encoded_json(resp.content)
     expected = TaskTimerSerializer(timer).data
     expected['time_worked'] = '1:00:00'
     self.assertEqual(data, expected)
Ejemplo n.º 51
0
def save_task_assignment(request):
    assignment_information = load_encoded_json(request.body)
    worker = Worker.objects.get(user=request.user)
    try:
        save_task(assignment_information['task_id'],
                  assignment_information['task_data'],
                  worker)
        return {}
    except Task.DoesNotExist:
        raise BadRequest('No task for given id')
    except TaskAssignmentError as e:
        raise BadRequest(e)
Ejemplo n.º 52
0
    def test_reviewer_task_assignment(self):
        # there is a review task for user 1
        response = (self.clients[1].get(
            '/orchestra/api/interface/new_task_assignment/reviewer/'))
        self.assertEquals(response.status_code, 200)

        returned = load_encoded_json(response.content)
        self._verify_good_task_assignment_information(
            self.clients[1], {'task_id': returned['id']},
            Task.objects.get(id=returned['id']).project.short_description,
            'Processing', 'Reviewing', True,
            False, {'test_key': 'test_value'}, self.workers[1])
Ejemplo n.º 53
0
    def test_permissions(self):
        self.api_client.force_authenticate(user=AnonymousUser())

        response = self.api_client.post(
            '/orchestra/api/project/project_information/',
            {'project_id': 1},
            format='json')
        self.assertEquals(response.status_code, 403)
        returned = load_encoded_json(response.content)
        self.assertEquals(
            returned,
            {'detail': 'You do not have permission to perform this action.'})
Ejemplo n.º 54
0
 def test_stop_timer(self, mock_stop):
     time_entry = TimeEntry(worker=self.worker, date=self.time.date(),
                            time_worked=datetime.timedelta(hours=1))
     time_entry.save()
     mock_stop.return_value = time_entry
     resp = self.request_client.post(
         reverse('orchestra:orchestra:stop_timer'),
         data=json.dumps({}),
         content_type='application/json')
     mock_stop.assert_called_with(self.worker)
     data = load_encoded_json(resp.content)
     serializer = TimeEntrySerializer(time_entry)
     self.assertEqual(data, serializer.data)
Ejemplo n.º 55
0
 def _make_assign_worker_task_request(self, worker_id,
                                      task_id, success=True):
     response = self.api_client.post(
         '/orchestra/api/project/assign_worker_to_task/',
         {
             'worker_id': worker_id,
             'task_id': task_id,
         },
         format='json')
     self.assertEquals(response.status_code, 200)
     data = load_encoded_json(response.content)
     self.assertEqual(data['success'], success)
     return data
Ejemplo n.º 56
0
    def test_save_reviewer_task_assignment(self):
        new_data = {'new_test_key': 'new_test_value'}

        # get a reviewer task
        response = (self.clients[1].get(
            '/orchestra/api/interface/new_task_assignment/reviewer/'))
        self.assertEquals(response.status_code, 200)

        returned = load_encoded_json(response.content)

        task = Task.objects.get(id=returned['id'])

        # entry level worker can't update the data
        response = self.clients[0].post(
            '/orchestra/api/interface/save_task_assignment/',
            json.dumps({'task_id': task.id,
                        'task_data': new_data}),
            content_type='application/json')
        self.assertEquals(response.status_code, 400)
        returned = load_encoded_json(response.content)
        self.assertEquals(returned['message'],
                          'Worker is not allowed to save')

        reviewer_data = {'reviewer_key': 'reviewer_value'}

        # reviewer can update the data
        response = self.clients[1].post(
            '/orchestra/api/interface/save_task_assignment/',
            json.dumps({'task_id': task.id,
                        'task_data': reviewer_data}),
            content_type='application/json')
        self.assertEquals(response.status_code, 200)

        self._verify_good_task_assignment_information(
            self.clients[1], {'task_id': task.id},
            task.project.short_description,
            'Processing', 'Reviewing', True,
            False, reviewer_data, self.workers[1])
Ejemplo n.º 57
0
 def test_time_entries_post_cannot_set_worker(self):
     """
     Worker is a read-only field and writes to it will be ignored by the
     serializer.
     """
     worker = Worker.objects.exclude(id=self.worker.id).first()
     self.time_entry_data['worker'] = worker.id
     resp = self.request_client.post(self.url,
                                     data=json.dumps(self.time_entry_data),
                                     content_type='application/json')
     data = load_encoded_json(resp.content)
     time_entry = TimeEntry.objects.get(id=data['id'])
     self.assertNotEqual(time_entry.worker, worker)
     self.assertEqual(time_entry.worker, self.worker)
Ejemplo n.º 58
0
def project_details_url(request):
    project_details = load_encoded_json(request.body)
    project_id = project_details.get('project_id')

    if project_id is None:
        raise BadRequest('project_id parameter is missing')
    project_details_url = '{}/project/{}'.format(
        reverse('orchestra:index'), project_id)
    parsed_url = urlparse(request.build_absolute_uri())
    url = urlunsplit((parsed_url.scheme,
                      parsed_url.netloc,
                      project_details_url,
                      '',
                      ''))
    return {'project_details_url': url}
Ejemplo n.º 59
0
 def test_time_entries_post(self):
     resp = self.request_client.post(self.url,
                                     data=json.dumps(self.time_entry_data),
                                     content_type='application/json')
     data = load_encoded_json(resp.content)
     time_entry = TimeEntry.objects.get(id=data['id'])
     self.assertEqual(time_entry.worker, self.worker)
     self.assertIsNone(time_entry.assignment)
     self.assertIsNone(time_entry.timer_start_time)
     self.assertIsNone(time_entry.timer_stop_time)
     self.assertFalse(time_entry.is_deleted)
     self.assertEqual(time_entry.description, 'test description')
     self.assertEqual(time_entry.date, datetime.date(2016, 5, 1))
     self.assertEqual(time_entry.time_worked,
                      datetime.timedelta(minutes=30))
Ejemplo n.º 60
0
def assign_worker_to_task(request):
    data = load_encoded_json(request.body)
    errors = {}
    try:
        assign_task(data.get('worker_id'), data.get('task_id'))
    except WorkerCertificationError as e:
        errors['worker_certification_error'] = str(e)
    except TaskAssignmentError as e:
        errors['task_assignment_error'] = str(e)
    except Exception as e:
        errors['error'] = str(e)
    success = len(errors) == 0
    return {
        'success': success,
        'errors': errors,
    }