Esempio n. 1
0
 def testCreateTable(self):
     """
     测试创建表单
     :return: 
     """
     from model.task import Task
     Task.create_table()
def update_task(id_task):

    if request.method == "POST":

        # query for check id task
        query_db = db.read("tasks", "id", id_task)
        task = query_db[0] if len(query_db) == 1 else None
        if task == None:
            return jsonify(error(404, "Task not exists"))

        else:
            json = request.get_json()

            id = task["id"]
            title = json["title"]
            description = json["description"]
            date = task["date"]
            id_list = task["id_list"]
            status = json["status"]

            task = Task(
                id=id,
                id_list=id_list,
                title=title,
                description=description,
                date=date,
                status=status,
            )

            if db.update("tasks", id_task, task.to_dict()):
                return jsonify(task.to_dict())

            else:
                return jsonify(error(203, "Not Allowed"))
    def testValidDescriptionProvided(self):
        task = Task("task a")

        task.setDescription("task b")

        self.assertEqual("task b", task.getDescription(),
                         "checking description")
def get_task(id):
    try:
        if (id): task = Task.find_task(Task, id).json()
        else: task = Task.find_task(Task, request.json.get("id")).json()
        return {'sucess': True, 'erro': False, 'response': task}
    except Exception as e:
        return {'sucess': False, 'erro': True, 'response': str(e)}
Esempio n. 5
0
 def set_task(self, list_task):
     self.m_dictTasks = dict()
     for task in list_task:
         if task["taskstate"] == "1":
             t = Task()
             t.handle_info(task)
             self.m_dictTasks[t.type] = t
    def testServiceVisitWithOneTaskThatDoesNotHaveTheSpecifiedId(self):
        task1 = Task("task a")
        task2 = Task("task b")
        visit = ServiceVisit("name", "address", "customer", [task1])

        with self.assertRaises(ValueError):
            visit.getTaskById(task2.getTaskId())
    def testServiceVisitWithOneTaskWithSpecifiedId(self):
        task1 = Task("task a")
        visit = ServiceVisit("name", "address", "customer", [task1])

        result = visit.getTaskById(task1.getTaskId())

        self.assertEqual(task1, result, "checking result")
    def testValidStatusProvided(self):
        task = Task("task a")

        task.setStatus(TaskStatus.COMPLETE)

        self.assertEqual(TaskStatus.COMPLETE, task.getStatus(),
                         "checking status")
Esempio n. 9
0
    def setUp(self):
        super(TestTasks, self).setUp()
        self.resource_name = 'task'
        self.resources_uri = self.root_uri + 'projects/1/sprints/1/stories/1/tasks'
        self.single_resource_uri = self.resources_uri + '/1'
        self.example_resource = Task(nr=1,
                                     description='some description',
                                     comment='some comment',
                                     status=1,
                                     progress=50,
                                     completion_date=None,
                                     owner=1,
                                     story_id=1,
                                     assigned_devs=[],
                                     id_=2)

        self.update_resource = Task(nr=7,
                                    description='some updated description',
                                    comment='some updated comment',
                                    status=2,
                                    progress=100,
                                    completion_date=None,
                                    owner=2,
                                    story_id=1,
                                    assigned_devs=[],
                                    id_=2)
    def testValidMaterialProvidedToTaskWithOneMaterial(self):
        task = Task("task a", materials=["splitter"])

        task.removeMaterial("splitter")

        self.assertEqual(0, len(task.getMaterials()),
                         "checking number of materials")
Esempio n. 11
0
	def test_merge(self):
		tree = ElementTree.fromstring(
			'<omnifocus xmlns="http://www.omnigroup.com/namespace/OmniFocus/v1" app-id="com.omnigroup.OmniFocus.iPad" app-version="79.4.0.175422" os-name="iPhone OS" os-version="6.1" machine-model="iPad">' +
			'<task id="l5FczgWVl2S">' +
			'<task idref="gZW06uIszyr"/>' +
			'<added>2012-08-28T04:55:12.824Z</added>' +
			'<modified>2012-09-05T08:00:16.788Z</modified>' +
			'<name>Kill duplicates</name>' +
			'<rank>0</rank>' +
			'<order>parallel</order>' +
			'</task>' +
			'</omnifocus>')

		tree_upd = ElementTree.fromstring(
			'<omnifocus xmlns="http://www.omnigroup.com/namespace/OmniFocus/v1" app-id="com.omnigroup.OmniFocus.iPad" app-version="79.4.0.175422" os-name="iPhone OS" os-version="6.1" machine-model="iPad">' +
			'<task id="l5FczgWVl2S" op="update">' +
			'<task idref="gZW06uIszyr"/>' +
			'<added>2012-08-28T04:55:12.824Z</added>' +
			'<modified>2012-09-05T08:00:16.788Z</modified>' +
			'<name>Kill duplicates in bases</name>' +
			'<rank>0</rank>' +
			'<order>parallel</order>' +
			'</task>' +
			'</omnifocus>')

		task = Task()
		task.fromXmlNode(tree[0])
		task.merge(tree_upd[0])
		self.assertEquals(task.name, "Kill duplicates in bases")
def save_task():
    try:
        task = Task(request.json.get("nome"), request.json.get("descricao"),
                    'aberto')  #request.json.get("status"))
        task.save()
        return {'sucess': True, 'erro': False, 'response': task.json()}
    except Exception as e:
        return {'sucess': False, 'erro': True, 'response': str(e)}
def delete_task(id):
    try:
        #Task(request.json.get("id"), request.json.get("nome"), request.json.get("descricao"), request.json.get("status")).delete()
        if (id): Task.find_task(Task, id).delete()
        else: Task.find_task(Task, request.json.get("id")).delete()
        return {'sucess': True, 'erro': False, 'response': 'sucess'}
    except Exception as e:
        print(e)
        return {'sucess': False, 'erro': True, 'response': str(e)}
 def testAddValidTaskToServiceVisitWithSomeTasks(self):
     task1 = Task("task a")
     visit = ServiceVisit("name", "address", "description", [task1])
     task2 = Task("task b")
     
     visit.addTask(task2)
     
     self.assertEqual(2, len(visit.getTasks()), "checking number of tasks")
     self.assertTrue(task1 in visit.getTasks(), "checking for pre-existing task")
     self.assertTrue(task2 in visit.getTasks(), "checking for task added")
    def testServiceVisitWithMultipleTasksAndLastHasSpecifiedId(self):
        task1 = Task("task a")
        task2 = Task("task b")
        task3 = Task("task c")
        visit = ServiceVisit("name", "address", "customer",
                             [task1, task2, task3])

        result = visit.getTaskById(task3.getTaskId())

        self.assertEqual(task3, result, "checking result")
Esempio n. 16
0
def game():
    """
                  start  (path with dialog)
                  /   \
               w1 (m1) w2 (d1)
                  \   /
                   knot1
                 /  |  \
                w3  w4 w5  <- with task t1,t2,t3
                \   |
                  end <- task from dialog td1
    :return: game with described graph
    """
    #TODO, check interaction model in waypoint
    dialog = Dialog()
    dialog_start = Mail(dialog.graph, 'start sub', 'start body')
    m1 = Mail(dialog.graph, 'second sub', 'second body')
    td1 = Task(None, 'some task 1', 'some task', 'some solution')
    d1 = Speech(dialog.graph, 'content', task=td1)

    game = Game('test')
    start = Waypoint(game.graph, 'start')
    w1 = Waypoint(game.graph, 'w1')
    w2 = Waypoint(game.graph, 'w2')
    knot = Waypoint(game.graph, 'knot')
    w3 = Waypoint(game.graph, 'w3')
    t1 = Task(w3, 'some task 1', 'some task')
    w4 = Waypoint(game.graph, 'w4')
    t2 = Task(w4, 'some task 2', 'some task')
    w5 = Waypoint(game.graph, 'w5')
    t3 = Task(w5, 'some task 3', 'some task')
    end = Waypoint(game.graph, 'end')
    start.add_destination(w1, 1.1)
    start.add_destination(w2)
    w1.add_destination(knot)
    w2.add_destination(knot)
    knot.add_task(t1)
    knot.add_task(t2)
    knot.add_task(t3)
    w3.add_destination(end)
    w4.add_destination(end)
    game.set_start(start)

    dialog_end = Speech(dialog.graph, 'next content', destination=end)
    dialog.set_start(dialog_start)
    dialog_start.add_follow_up(d1)
    dialog_start.add_follow_up(m1)
    dialog_start.waypoints.append(start)
    d1.add_follow_up(dialog_end, None)

    game.add_non_playable_character(NonPlayableCharacter(
        'bob', 'test', dialog))

    return game
Esempio n. 17
0
def build_task(session,taskType,service,host,role,task):
    new_task = Task(taskType,service,host,role,task)
    if config.ansible_run == False :
        new_task.status = Task.STATUS_FINISH
        new_task.result = Task.RESULT_SUCCESS
        new_task.msg = "fade success"
    session.add(new_task)
    session.flush()
    newid = new_task.id
    session.commit()
    return newid
Esempio n. 18
0
def build_task(session, taskType, service, host, role, task):
    new_task = Task(taskType, service, host, role, task)
    if config.ansible_run == False:
        new_task.status = Task.STATUS_FINISH
        new_task.result = Task.RESULT_SUCCESS
        new_task.msg = "fade success"
    session.add(new_task)
    session.flush()
    newid = new_task.id
    session.commit()
    return newid
Esempio n. 19
0
	def create_task(self, args):
		try:
			title = self.format_title(args.title)
			description = args.description if args.description else ""
			date = self.deserialize_date(args.date)
			time = self.deserialize_time(args.time) if args.time else None
			project = self.deserialize_project(args.project) if args.project else None

			task = Task(title, description, date, time, project)
			self.task_handler.add_task(task)
			print("Added task '{}' for {}".format(task.get_title(), task.get_date().toString("dddd, d. MMMM yy.")))
		except Exception as e:
			print(e)
		return True
Esempio n. 20
0
def create_tables():
    """
    初始化表结构
    :return: 
    """
    Url.create_table()
    Task.create_table()
    User.create_table()
    UserTask.create_table()
    PluginInfo.create_table()
    Vulnerability.create_table()
    SystemConfig.create_table()
    PluginInfo.create_table()
    LdapConfig.create_table()
    NetWorkProxyConfig.create_table()
Esempio n. 21
0
    def set_step_completed_in_progress_ini(self, stack, step):
        """
        Look up the lookup up from the step. Check if the stack already exists,
        if not, insert, otherwise, update
        Args:
            stack: string of the stack you are working on
            step: current step

        Returns:
            nothing, just merges
        """
        try:
            lookup = self.session.query(ProgressLookup)\
                .filter(ProgressLookup.original_step == step)\
                .order_by(ProgressLookup.original_step.desc())\
                .limit(1).one()
        except NoResultFound:
            print('No lookup for {} so we will enter one.'.format(step))
        try:
            task = self.session.query(Task).filter(Task.lookup_id == lookup.id)\
                .filter(Task.prep_id == stack).one()
        except NoResultFound:
            print('No step for {}'.format(step))
            task = Task(stack, lookup.id, True)

        try:
            self.session.merge(task)
            self.session.commit()
        except:
            print('Bad lookup code for {}'.format(lookup.id))
            self.session.rollback()
Esempio n. 22
0
def createtasks(tasklistinput):
    """
    Creates one class Task for every task in the input file.
    :param tasklistinput: Tasks from the input file.
    :return: List of classes Task.
    """
    tasklist = []
    for taskinput in tasklistinput:
        if "dependencies" in taskinput:
            task = Task(taskinput["name"], taskinput["type"],
                        taskinput["arguments"], taskinput["dependencies"])
        else:
            task = Task(taskinput["name"], taskinput["type"],
                        taskinput["arguments"], None)
        tasklist.append(task)
    return tasklist
Esempio n. 23
0
 def __init__(self, config):
     self.config = config
     self.score_dir = config.get_argv().score_file
     self.benchmark_config = config.get_argv().benchmark_config
     self.task = Task(config)
     self.workspace = Workspace(config)
     self.ssh_user = config.get_value('User', 'SSH')
     self.ssh_passwd_file = config.get_value('PasswdFile', 'SSH')
     self.ssh_port = config.get_value('Port', 'SSH')
     self.subnet_ip = config.get_value('ip', 'Subnet')
     self.subnet_name = config.get_value('name', 'Subnet')
     self.mode = config.get_value('Mode')
     self.pwd = os.path.dirname(__file__)
     self.mq_tag = str(time.time()).replace('.', '_')
     self._benchmark_pressure_tag_id = None
     self.logs_dir = os.path.join(self.pwd, '../logs/')
     self.logger = logging.getLogger(__name__)
     self.lockfile = self.__lockfile()
     self.logger.setLevel(logging.DEBUG)
     handler = logging.FileHandler("log.txt")
     handler.setLevel(logging.DEBUG)
     formatter = logging.Formatter(
         '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
     handler.setFormatter(formatter)
     self.logger.addHandler(handler)
Esempio n. 24
0
    def test_create(self):
        task = Task.create('test task')

        self.assertIsNotNone(task)
        self.assertRegex(task.uuid, r'%s' % UUID4_REGEX)
        self.assertEqual('test task', task.description)
        self.assertEqual(0, task.done)
Esempio n. 25
0
    def test_upload_does_nothing_if_task_is_stale(self, mockDropbox,
                                                  mockUploadCursor):
        uploadSessionStarter = MagicMock()
        uploadSessionAppender = MagicMock()

        mockDropbox.return_value.files_upload_session_start = uploadSessionStarter
        mockDropbox.return_value.files_upload_session_finish = uploadSessionAppender

        testSecretData = b"secret test data"
        testFileHandle = BytesIO(testSecretData)
        testPartName = "testFile__1__1.enc"
        testClientModified = datetime.datetime(2020, 1, 1, 10, 5, 30)

        testFileData = {
            "userTimezone": "+0200",
            "utcModified": testClientModified.timestamp(),
            "path": "subDir"
        }
        testTask = Task(taskType=MessageTypes.UPLOAD_FILE,
                        data=testFileData,
                        stale=True)

        cloudAccount = DropboxAccountWrapper(self.testAccountData)
        result = cloudAccount.upload(testFileHandle, len(testSecretData),
                                     testPartName, testTask)

        self.assertEqual(uploadSessionStarter.call_count, 0)
        self.assertEqual(uploadSessionAppender.call_count, 0)
        self.assertIsNone(result)
Esempio n. 26
0
    def test_download_file_does_nothing_if_task_is_stale(self, mockRequest):
        secretData = b"secret test data"
        testEncoder = AES.new(self.testAccountData.cryptoKey.encode(),
                              AES.MODE_CFB)
        testIV = testEncoder.iv

        ivResponse = MagicMock()
        ivResponse.content = testIV

        encryptedDataResponse = MagicMock()
        encryptedDataResponse.content = testEncoder.encrypt(secretData)

        mockRequest.side_effect = [ivResponse, encryptedDataResponse]

        testDownloadFileHandle = BytesIO()
        testFilePartInfo = FilePart(
            filename="apple.txt__1__1.enc",
            modified=int(
                datetime.datetime(2020, 1, 1, 10, 10, 30).timestamp()),
            size=len(encryptedDataResponse.content) + len(testIV),
            path="",
            fullPath="apple.txt__1__1.enc",
            storingAccountID=self.testAccountData.id,
            extraInfo={})

        testDownloadFileTask = Task(taskType=MessageTypes.DOWNLOAD_FILE,
                                    stale=True)
        cloudAccount = DropboxAccountWrapper(self.testAccountData)
        cloudAccount.download(testDownloadFileHandle, testFilePartInfo,
                              testDownloadFileTask)

        testDownloadFileHandle.seek(0)

        self.assertEqual(b"", testDownloadFileHandle.read())
Esempio n. 27
0
    def test_upload_writes_iv_and_encrypts_file_data(self, mockDropbox,
                                                     mockUploadCursor):
        uploadSessionStarter = MagicMock()
        uploadSessionAppender = MagicMock()

        mockDropbox.return_value.files_upload_session_start = uploadSessionStarter
        mockDropbox.return_value.files_upload_session_finish = uploadSessionAppender

        testSecretData = b"secret test data"
        testFileHandle = BytesIO(testSecretData)
        testPartName = "testFile__1__1.enc"
        testClientModified = datetime.datetime(2020, 1, 1, 10, 5, 30)

        testFileData = {
            "userTimezone": "+0200",
            "utcModified": testClientModified.timestamp(),
            "path": "subDir"
        }
        testTask = Task(taskType=MessageTypes.UPLOAD_FILE, data=testFileData)

        cloudAccount = DropboxAccountWrapper(self.testAccountData)
        result = cloudAccount.upload(testFileHandle, len(testSecretData),
                                     testPartName, testTask)

        cipher = AES.new(self.testAccountData.cryptoKey.encode(),
                         AES.MODE_CFB,
                         iv=uploadSessionStarter.call_args[0][0])
        encoded = mockDropbox.return_value.files_upload_session_finish.call_args[
            0][0]

        self.assertNotEqual(encoded, testSecretData)
        self.assertEqual(cipher.decrypt(encoded), testSecretData)
Esempio n. 28
0
    def parse(self, task: Task, content: str):
        data = json.loads(content)
        if data['code'] != 200:
            raise Exception(f'Failed to parse response {content}')

        content = data['content']
        keyword = content['keyword']
        news_items = content.get('results', [])

        need_next_page = False
        items = []
        for news_item in news_items:
            item = XinHuaNewsItem()
            item.url = news_item['url']
            item.keyword = keyword
            item.title = news_item['title']
            item.abstract = news_item['des']
            item.publish = datetime.datetime.strptime(news_item['pubtime'], '%Y-%m-%d %H:%M:%S')
            items.append(item)
            if item.publish >= config.BEGIN_DATE:
                need_next_page = True

        if need_next_page:
            params = task.params
            params['curPage'] += 1
            yield Task(task.url, '', '', params=params, metadata=task.metadata)

        for item in items:
            yield item
Esempio n. 29
0
def test_comment_parser():
    with open('./test_files/shop_reviews.html', 'r') as html_file:
        data = html_file.read()
    url = 'https://www.dianping.com/shop/90556783/review_all'
    task = Task(url, '', '')
    parser = get_parser(url)
    _parse(parser, task, data)
Esempio n. 30
0
    def dispatchIncomingMessage(self, message):
        messageType = message.header.messageType
        task = Task(taskType=messageType, stale=False, uuid=message.header.uuid, data=message.data)

        if messageType in self.__INSTANT_TASK_TYPES:
            if messageType == MessageTypes.DELETE_FILE:
                path = message.data["fullPath"]
                self.__longFileTaskArchive.cancelTask(path)
                self.__longFileTaskArchive.removeTask(path)
            elif messageType == MessageTypes.MOVE_FILE:
                self.__longFileTaskArchive.cancelTask(message.data["source"])
                self.__longFileTaskArchive.cancelTask(message.data["target"]["fullPath"])

                self.__longFileTaskArchive.removeTask(message.data["source"])
                self.__longFileTaskArchive.removeTask(message.data["target"]["fullPath"])
            self.incoming_instant_task_queue.put(task)
        elif messageType in self.__SLOW_TASK_TYPES:
            key = task.data["fullPath"]
            self.__longFileTaskArchive.addTask(key, task)
            self.incoming_task_queue.put(task)
        elif messageType == MessageTypes.FILE_TASK_CANCELLED:
            self._logger.debug(f"Cancelling task for file: {message.data['fullPath']}")
            self.__longFileTaskArchive.cancelTask(message.data["fullPath"])
            self.__longFileTaskArchive.removeTask(message.data["fullPath"])
        else:
            self._logger.warning(f"Unknown message: {message}")
    def test_handler_retrieves_accounts_from_database_and_sends_response(
            self, dispatchResponseMock):
        testAccounts = [
            AccountData(id=1,
                        identifier="testAccountID",
                        accountType=AccountTypes.Dropbox,
                        cryptoKey="sixteen byte key",
                        data={"apiToken": "testApitoken"})
        ]
        testTask = Task(taskType=MessageTypes.GET_ACCOUNT_LIST,
                        uuid=uuid4().hex)

        self.fakeDB.getAllAccounts.return_value = testAccounts

        self.testHandler.setTask(testTask)
        self.testHandler.handle()

        self.assertEqual(self.fakeDB.getAllAccounts.call_count, 1)

        self.assertEqual(dispatchResponseMock.call_count, 1)
        self.assertEqual(
            dispatchResponseMock.call_args[0][0].header.messageType,
            MessageTypes.RESPONSE)
        self.assertEqual(dispatchResponseMock.call_args[0][0].header.uuid,
                         testTask.uuid)

        self.assertEqual(
            type(dispatchResponseMock.call_args[0][0].data["accounts"]), list)
        self.assertEqual(
            len(dispatchResponseMock.call_args[0][0].data["accounts"]),
            len(testAccounts))

        self.assertEqual(
            dispatchResponseMock.call_args[0][0].data["accounts"][0],
            testAccounts[0].serialize())
Esempio n. 32
0
    def update_task(self, task_id: int, new_task: Task):
        """
        Update Task by id

        :param task_id: id of updating Task
        :param new_task: Task entity with updating info
        :return: True if entity was updated else
        >>> a = DataManager.load_from_file(test_suits_folder_path + "/test_suit3.json")
        >>> task = Task(1, "TEST val", "nothing", parser.parse("1999-08-28T21:03:05"), \
            parser.parse("1999-08-28T05:55:23"), True)
        >>> a.update_task(1, task)
        True
        >>> a.get_by_id(1) == task
        True
        >>> task.name = "TEst N2"
        >>> a.update_task(1, task)
        True
        >>> a.get_by_id(1) == task
        True
        """
        self.update_from_file(self.storage_path)
        new_task.task_id = task_id
        for i, task in enumerate(self.tasks):
            if task.task_id == task_id:
                self.tasks[i] = new_task
                self.save_to_file(self.storage_path)
                return True
        return False
Esempio n. 33
0
	def fromXml(self, tree):
		self._tree = tree
		root = tree
		self.tasks = dict()
		self.tasks_tree = dict()
		self.folders = dict()
		self.folders_tree = dict()
		self.contexts = dict()
		self.contexts_tree = dict()

		for e in root:
			tag = extract_tag(e.tag)
			if tag == 'task':
				task = Task()
				task.fromXmlNode(e)
				self.tasks[task.id] = task
				parent = task.parentRef or task.folderRef or "/"
				if not parent in self.tasks_tree:
					self.tasks_tree[parent] = []
				self.tasks_tree[parent].append(task)
			elif tag == 'folder':
				folder = Folder()
				folder.fromXmlNode(e)
				self.folders[folder.id] = folder
				parent_folder = folder.parentRef or "/"
				if not parent_folder in self.folders_tree:
					self.folders_tree[parent_folder] = []
				self.folders_tree[parent_folder].append(folder)
			elif tag == 'context':
				context = Context()
				context.fromXmlNode(e)
				self.contexts[context.id] = context
				parent_ctx = context.parentRef or "/"
				if not parent_ctx in self.contexts_tree:
					self.contexts_tree[parent_ctx] = []
				self.contexts_tree[parent_ctx].append(context)
Esempio n. 34
0
    def get(self):
        type_ = self.get_argument('type')
        li = Task.select().where(Task.type == type_).order_by(Task.index)
        li = [o.to_dict() for o in li]

        self.finish(dict(data=li))
Esempio n. 35
0
    def post(self):
        type_ = self.get_argument('type')
        title = self.get_argument('title')
        Task.create(type=type_, title=title)

        self.finish()
Esempio n. 36
0
	def post(self, workspace, action):
		#logging.info("hello world")
		##used for CRUD for tasks and dnd operations
		#if action not in self.__actions__:
		#	raise WrongActionException("Action %s is not supported" % action)
		#if action != "create" and not id:
		#	raise WrongActionException("Id should not be null for %s action" % action)
		logging.info("============= Doing %s ===============" % action)
		if action == "create":
			name = self.request.get("name")
			body = self.request.get("body")
			column = Column.gql("WHERE allow_create=TRUE").get()
			logging.info("column: %s, name: %s, body: %s" % (column, name, body))
			task = Task(column=column, name=unicode(name), body=unicode(body))
			task.put()
		if action == "dnd":
			task_id = self.request.get("task")
			dest_column_key = self.request.get("to")
			logging.info("task: %s" % task_id)
			logging.info("to: %s" % dest_column_key)

			task = Task.get(task_id)
			dest_column = Column.get(dest_column_key)
			task.column = dest_column
			task.put()
		if action == "delete":
		#	#delete task
			id = self.request.get("taskId")
			task = Task.get(id)
			db.delete(task)
		if action == "edit":
			id = self.request.get("taskId")
			name = self.request.get("name")
			body = self.request.get("body")
			task = Task.get(id)
			task.name = name
			task.body = body
			task.put()