Example #1
0
 def test_fail_having_more_than_one_task_overlapping(self):
     cpu = Cpu('Cpu A')
     Task('A', cpu, deadline=5, period=5, cpu_time=5)
     Task('B', cpu, deadline=5, period=5, cpu_time=5)
     with self.assertRaises(Exception):
         for x in range(20):
             cpu.update()
Example #2
0
    def setUp(self):
        self.service = KanbanBoardService()

        with patch('sqlalchemy.orm.query.Query') as MockQuery:
            self.mock_query = MockQuery.return_value
            self.mock_query.all.return_value = [
                Task(**{
                    'id': 1,
                    'title': 'mock-title-1',
                    'start_time': None,
                    'end_time': None,
                    'status': 0,
                    'payment': 0
                }),
                Task(**{
                    'id': 2,
                    'title': 'mock-title-2',
                    'start_time': None,
                    'end_time': None,
                    'status': 0,
                    'payment': 0
                })
            ]

        with patch('sqlalchemy.orm.session.Session') as MockSession:
            self.mock_session = MockSession.return_value
            self.mock_session.add.return_value = None
            self.mock_session.commit.return_value = None
            self.mock_session.close.return_value = None
            self.mock_session.query.return_value = self.mock_query

        with patch('utils.DBDriver.DBDriver') as MockDBDriver:
            self.service.dbms = MockDBDriver.return_value
            self.service.dbms.get_session.return_value = self.mock_session
Example #3
0
 def test_updated_task_after_cpu_udpate(self):
     cpu_a = Cpu('Cpu A')
     deadline = period = 10
     cpu_time = 5
     Task('A', cpu_a, deadline, period, cpu_time)
     Task('B', cpu_a, deadline, period, cpu_time)
     cpu_a.update()
Example #4
0
 def test_correct_simulation_1(self):
     cpu = Cpu('Cpu A')
     Task('A', cpu, deadline=10, period=10, cpu_time=5)
     Task('B', cpu, deadline=10, period=10, cpu_time=3)
     Task('C', cpu, deadline=10, period=20, cpu_time=1)
     Task('D', cpu, deadline=10, period=20, cpu_time=1)
     for x in range(40):
         cpu.update()
Example #5
0
def update_task(task_id):
    taskdb = TaskDB(g.mysql_db, g.mysql_cursor)

    task = Task(request.json['description'])
    taskdb.update_task(task_id, task)
    
    return jsonify({"status": "success", "id": task_id}), 200
Example #6
0
def add_task():
    taskdb = TaskDB(g.mysql_db, g.mysql_cursor)
        
    task = Task(request.json['description'])
    result = taskdb.insert_task(task)
    
    return jsonify({"status": "success", "id": result['task_id']}), 200
 def create_task(self, event):
     result = {
         'data': {},
         'status': 201  # Created.
     }
     fields = {'title': ['is_set', 'is_empty']}
     errors = self.validator.validate(event, result, fields)
     if not errors:
         body = event['body']
         task = Task(title=body['title'])
         session = self.dbms.get_session()
         try:
             session.add(task)
             session.commit()
             result['data'] = self.map_to_json(task)
         except Exception as ex:
             session.rollback()
             result['status'] = 500
             result['data'] = {'errors': {'db': 'session.commit error'}}
             print(ex)
         finally:
             session.close()
     else:
         result['data'] = {'errors': errors}
     return result
Example #8
0
    def create_task(self, task, headers):
        try:
            # Checking if the token is valid or not
            payload = JwtHandler.decode_auth_token(headers['Authorization'])
            if (payload):
                # Creating a task object
                task_obj = Task()
                task_obj.title = task['title']
                task_obj.laneId = task['laneId']
                task_obj.description = task['description']
                task_obj.userId = payload['sub']
                task_obj.position = task['position']
                task_obj.notificationTimeMinutes = task[
                    'notificationTimeMinutes']

                # Storing the task in tasks collection
                task_collection = self.__get_task_collection()
                saved_task = task_collection.insert_one(task_obj.__dict__)

                # Storing the task_id in the object and returning
                task_obj.id = str(saved_task.inserted_id)

                # Closing the DB connection
                self.mongo_db.disconnect()

                return task_obj
            else:
                return "Invalid Authorization"

        except Exception as exception:
            raise exception
Example #9
0
def create_task():
    description = request.form["description"]
    user_id = request.form["user_id"]
    duration = request.form["duration"]
    completed = request.form["completed"]
    user = user_repository.select(user_id)

    task = Task(description, user, duration, completed)

    task_repository.save(task)

    return redirect('/tasks')


# SHOW                                                  # for showing one thing in detail. {{task.description}} in the html can be placed inside an <a></a> tag
# GET '/tasks/<id>'

# EDIT                                                  # slightly harder code
# GET '/tasks/<id>/edit'

# UPDATE                                                # slightly harder code
# PUT '/tasks/<id>'

# DELETE
# DELETE '/tasks/<id>'
Example #10
0
    def post(self):
        data = ApiTask.parser.parse_args()
        print('you are here')
        if (len(data) == 0):
            task = Task('default', 0, 0, 0)
        else:
            task = Task(data['name'], data['weekday'], data['hour'],
                        data['grabber_id'])
        if data['url_id']:
            task.setUrl(data['url_id'])
        try:
            task.save_to_db()
        except:
            return {'message': 'Failed to save'}, 500

        return {'id': task.id}, 201
Example #11
0
def new(following_id):
    follower = User.get_by_id(current_user.id)
    following = User.get_by_id(following_id)

    if following.is_public:
        r = Relationship(follower=follower,
                         following=following,
                         is_approved=True)
    else:
        r = Relationship(follower=follower,
                         following=following,
                         is_approved=False)

    if r.save():
        if following.is_public:
            flash(f"You are now following {following.name}.")
            return redirect(url_for('users.show', username=following.username))
        else:
            flash(f"A follow request has been sent to {following.name}.")
            rq_job = app.task_queue.enqueue(
                'tasks.' + 'send_follow_request_email', following, follower,
                url_for('relationships.index'))
            task = Task(redis_job_id=rq_job.get_id(),
                        name='send_follow_request_email',
                        description='Send user a follow request email.',
                        relationship=r)
            task.save()
            return redirect(url_for('users.show', username=following.username))
    else:
        return render_template(
            'users/show.html',
            user=following,
            photos=Image.select().where(Image.user_id == following.id),
            errors=r.errors)
Example #12
0
def add_task():
    task_title = request.form['title']
    task_desc = request.form['description']
    new_task = Task(task_title, task_desc, False)
    print(request.form)
    add_new_task(new_task)
    return render_template('index.html', title="Home", tasks=tasks)
Example #13
0
    def get_tasks(self, project, limit=5):
        """
        Arbitrarily narrow down to only one workspace
        :param project_id: PHID of Phabricator project
        """
        task_list = []

        tasks = self.client.maniphest.search(
            queryKey="open", constraints={"projects": [project.id]}, limit=limit
        )["data"]

        # Parse JSON into Task objects
        for task in tasks:
            task_list.append(
                Task(
                    id=task["id"],
                    title=task["fields"]["name"],
                    link="{}".format(Config.PHABRICATOR_URI.replace("/api/", ""))
                    + "/T"
                    + str(task["id"]),
                    is_completed=("Completed" == task["fields"]["status"]["value"]),
                    created_at=datetime.strftime(
                        datetime.fromtimestamp(task["fields"]["dateCreated"]),
                        "%Y-%m-%d %H:%m:%S",
                    ),
                    priority=task["fields"]["priority"]["value"],
                    project=project,
                )
            )

        return task_list
Example #14
0
    def test_update_task_error_status_is_incorrect(self):
        """Test: update_task(self, event).
        Error: status is incorrect."""

        status = Task.Statuses.IN_PROGRESS.value
        self.mock_query.get.return_value = Task(**{
            'id': 3,
            'title': 'mock-title-3',
            'start_time': None,
            'end_time': None,
            'status': status,
            'payment': 0
        })
        status = Task.Statuses.TODO.value
        event = {
            'body': f'{{"status": {status}}}',
            'pathParameters': {
                'id': '3'
            }
        }
        actual = self.service.update_task(event)
        self.assertEqual(409, actual['status'])
        self.assertEqual(
            'status is incorrect', actual['data']['errors']['status']
        )
    def get_any_created_or_killed_task(self, host):
        try:
            if not self._tasks_collection:
                self.reload_collection()

            if self._tasks_collection:
                task_json = self._tasks_collection.find_one_and_update(
                    filter={
                        "$or": [{
                            'state': TaskStates().CREATED
                        }, {
                            'state': TaskStates().KILLED
                        }]
                    },
                    update={
                        '$set': {
                            'state': TaskStates().RUNNING,
                            'host': host
                        }
                    },
                    return_document=ReturnDocument.AFTER)

                if task_json:
                    self._m_logger.info(
                        'Running task {task}'.format(task=task_json))

                    return Task().convert_json_to_task(task_json=task_json)

        except Exception as e:
            self._m_logger.exception(
                'Encountered exception while getting task. {e}'.format(e=e))

        self.get_completion_stats()

        return None
Example #16
0
    def test_update_task_success_status_done(self):
        """Test: update_task(self, event).
        Status: DONE."""

        start_dt = datetime.now(tz=pytz.UTC)
        start_dt = start_dt - timedelta(days=1)
        start_dt = start_dt.replace(
            hour=14, minute=0, second=0, microsecond=0
        )
        self.mock_query.get.return_value = Task(**{
            'id': 3,
            'title': 'mock-title-3',
            'start_time': start_dt,
            'end_time': None,
            'status': Task.Statuses.IN_PROGRESS.value,
            'payment': 0
        })
        status = Task.Statuses.DONE.value
        event = {
            'body': f'{{"status": {status}}}',
            'pathParameters': {
                'id': '3'
            }
        }
        actual = self.service.update_task(event)
        self.assertEqual(205, actual['status'])
        self.assertEqual(status, actual['data']['status'])
Example #17
0
def add_task():
  taskTitle = request.form['title']
  taskDesc = request.form['description']
  newTask = Task(title=taskTitle, description=taskDesc, done=False)
  add_new_task(newTask)

  return render_template('index.html', title='Home', tasks=tasks)
Example #18
0
def get_stat():
    task_id = ''.join([random.choice(string.digits) for _ in range(16)])
    Task(task_id).create_task()
    async_task = AsyncTask(task_id=task_id)
    async_task.start()
    url_for('task_status', task_id=task_id)
    return task_id
Example #19
0
File: forms.py Project: DaC24/taskr
    def handle(self):

        # check if user has admin permissions
        if not is_admin(self.user_entity):
            return self.abort(401, detail="Admin permissions required")

        # populate form with POST data (if available)
        form = TaskForm(self.request.POST)

        # check if form was POSTed and that user input validates
        if self.request.method == 'POST' and form.validate():

            # create new project
            task = Task()

            # populate task from form
            form.populate_obj(task)
            # add user to project's user list and assign to self
            task.users.append(self.user_entity.key)
            task.assigned_to = self.user_entity.key
            # store task in datastore
            task.put()

            # record history item
            history_text = 'Project added'
            add_to_history(task, self.user_entity, history_text)
            self.session.add_flash(history_text)

            # redirect to task view on succesful save
            redirect_url = self.uri_for('task-view', task_id=task.key.urlsafe())
            return self.redirect(redirect_url)

        # render form and display
        context = {'form': form, 'task_or_project': 'project', 'add_or_edit': 'Add new'}
        return self.render_response('task_form.html', context)
Example #20
0
File: forms.py Project: DaC24/taskr
    def handle(self, task_id):

        # create new task (with parent)
        parent_task_key = ndb.Key(urlsafe=task_id)
        task = Task(parent=parent_task_key)

        # check if user is authed to add task
        if not authed_for_task(parent_task_key.get(), self.user_entity):
            return self.abort(401)

        # init form object with POST data
        form = TaskForm(self.request.POST)

        # if form was posted and it validates
        if self.request.method == 'POST' and form.validate():

            # build task from form and save
            form.populate_obj(task)
            task.put()

            # add history record for this task
            history_text = 'Task added'
            add_to_history(task, self.user_entity, history_text)
            self.session.add_flash(history_text)

            # build url to redirect to and issue 302 to browser
            redirect_url = self.uri_for('task-view', task_id=task.key.urlsafe())
            return self.redirect(redirect_url)

        # render form and return (rendering errors if necessary)
        context = {'form': form, 'task_or_project': 'task'}
        return self.render_response('task_form.html', context)
Example #21
0
    def test_update_task_exception(self):
        """Test: update_task(self, event)
        session.query(Task).all() throws Exception"""

        self.mock_query.get.return_value = Task(**{
            'id': 3,
            'title': 'mock-title-3',
            'start_time': None,
            'end_time': None,
            'status': 0,
            'payment': 0
        })
        status = Task.Statuses.IN_PROGRESS.value
        event = {
            'body': f'{{"status": {status}}}',
            'pathParameters': {
                'id': '3'
            }
        }
        self.mock_session.commit.side_effect = Mock(side_effect=Exception())
        actual = self.service.update_task(event)
        self.assertEqual(500, actual['status'])
        self.assertEqual(
            'session.commit error', actual['data']['errors']['db']
        )
class TestTask(TestCase):
    _item = Item()
    _task = Task()
    _db = SqlitePersistence(":memory:")

    def setUp(self):
        self._item.rig = "X01"
        self._item.description = "Something to handover"
        self._item.case = "CAS-12345"
        self._db.save(self._item)

        self._task.description = "Some update"
        self._task.item_id = 1
        self._db.save(self._task)

    def test_a_task_has_a_description(self):
        task = self._db.find(Task, 1)
        self.assertEqual(task.description, "Some update")

    def test_a_task_has_an_item(self):
        task = self._db.find(Task, 1)
        self.assertEqual(task.item.description, self._item.description)

    def test_a_saved_task_has_a_created_by_timestamp(self):
        task = self._db.find(Task, 1)
        self.assertIsNotNone(task.created_by)

    def test_a_saved_task_has_an_updated_by_timestamp(self):
        task = self._db.find(Task, 1)
        self.assertIsNotNone(task.updated_by)

    def test_a_saved_task_has_a_created_by(self):
        task = self._db.find(Task, 1)
        self.assertEqual(task.created_by, os.getlogin())

    def test_a_saved_task_has_an_updated_by(self):
        task = self._db.find(Task, 1)
        self.assertEqual(task.updated_by, os.getlogin())

    def test_a_completed_task_has_a_completed_at_timestamp(self):
        task = self._db.find(Task, 1)
        self._db.complete(Task, task.id)
        task = self._db.find(Task, 1)
        self.assertIsNotNone(task.completed_at)

    def test_an_incomplete_task_does_not_have_a_completed_at_timestamp(self):
        task = self._db.find(Task, 1)
        self._db.incomplete(Task, task.id)
        task = self._db.find(Task, 1)
        self.assertIsNone(task.completed_at)

    def test_a_task_can_be_edited(self):
        task = self._db.find(Task, 1)

        data = {"description": "a task"}
        self._db.edit(Task, task.id, data)
        edited = self._db.find(Task, task.id)

        self.assertEqual(data["description"], edited.description)
Example #23
0
 def create(task, completed, task_due_date, task_goal, user_first_name):
     user = UserRepository.read(first_name=user_first_name)
     task = Task(task=task,
                 completed=completed,
                 task_goal=task_goal,
                 task_due_date=task_due_date,
                 assigne=user)
     return task.put()
Example #24
0
 def add_task():
     if request.method == 'POST':
         data = request.json
         new_task = Task(data['task'], data['category'], data['completed'])
         session.add(new_task)
         session.commit()
         print(new_task, 'New task was added.')
         return 'New task was added.'
Example #25
0
 def get_task(self, task_id):
     """
     :param task_id:
     :return: task object
     """
     url = "{}/tasks/{}/".format(BASE_URL, task_id)
     results = self.r.get(url, headers=self._get_auth_header()).json()
     return Task(**results['tasks'])
Example #26
0
def select(id):
    task = None
    sql = "SELECT * FROM tasks WHERE id = %s"  
    values = [id] 
    result = run_sql(sql, values)[0]
    
    if result is not None:
        task = Task(result['description'], result['assignee'], result['duration'], result['completed'], result['id'] )
    return task
def update(id):
    description = request.form["description"]
    duration = request.form["duration"]
    completed = request.form["completed"]
    user_id = request.form["user_id"]
    user = user_repository.select(user_id)
    updated_task =Task(description, user, duration, completed, id)
    task_repository.update(updated_task)
    return redirect("/tasks")
Example #28
0
def add_task():
    task_description = request.form.get("task_description")

    new_task = Task(task_description)
    database = TaskDB(g.mysql_db, g.mysql_cursor)

    database.insert_task(new_task)

    return redirect('/')
Example #29
0
def create():
    description = request.form['description']
    duration = request.form['duration']
    completed = request.form['completed']
    user_id = request.form['user_id']
    user = user_repository.select(user_id)
    new_task = Task(description, user, duration, completed)
    task_repository.save(new_task)
    return redirect("/tasks")
def update_task(id):
    description = request.form['description']
    user_id = request.form['user_id']
    duration = request.form['duration']
    completed = request.form['completed']
    user = user_repository.select(user_id)
    task = Task(description, user, duration, completed, id)
    task_repository.update(task)
    return redirect('/tasks')