Ejemplo n.º 1
0
def test_daily_plan_creation():
    """Check if tasks are added to the Daily Plan
    in respective order"""
    task_1 = tasks.Task("one", 20)
    task_2 = tasks.Task("two", 25)
    day_plan_obj = day_plan.DailyPlan()
    day_plan_obj.create_plan(task_1, task_2)
    assert (day_plan_obj.get_plan()) == [('one', 20), ('two', 25)]
Ejemplo n.º 2
0
def test_tasks_assignment_from_daily_plan():
    t1 = tasks.Task("one", 20)
    t2 = tasks.Task("two", 25)
    d = tasks.DailyPlan()
    d.create_plan(t1, t2)
    w1 = tasks.Worker("John")
    w1.get_task_from_dp(d)
    assert (w1.get_current_task()) == ('two', 25)
    assert (d.get_plan()) == [('one', 20)]
Ejemplo n.º 3
0
def test_report_three():
    log1 = tasks.Log()
    worker1 = tasks.Worker("Dima")
    worker2 = tasks.Worker("John")
    task1 = tasks.HourlyPaymentTask("Homework", 10, 3)
    task2 = tasks.Task("Take cup of tea", 5)
    task3 = tasks.Task("Web serfing", 25)
    worker1.take_task(task1, log1)
    worker2.take_task(task2, log1)
    worker1.take_task(task3, log1)
    assert log1.report() == 'Dima\t$55\nJohn\t$5'
Ejemplo n.º 4
0
def test_tasks_assignment_from_daily_plan():
    """Check if tasks are properly assigned from Daily Plan to worker
    and if Daily Plan is properly updated"""
    task_1 = tasks.Task("one", 20)
    task_2 = tasks.Task("two", 25)
    day_plan_obj = day_plan.DailyPlan()
    day_plan_obj.create_plan(task_1, task_2)
    worker_1 = worker.Worker("John")
    worker_1.get_task_from_dp(day_plan_obj)
    assert (worker_1.get_current_task()) == ('two', 25)
    assert (day_plan_obj.get_plan()) == [('one', 20)]
Ejemplo n.º 5
0
def test_unique_id_2():
    """unique_id() should return an unused id."""
    ids = []
    ids.append(tasks.add(tasks.Task('one')))
    ids.append(tasks.add(tasks.Task('two')))
    ids.append(tasks.add(tasks.Task('three')))

    # Grab a unique id
    uid = tasks.unique_id()

    # Make sure it isn't the list of existing ids
    assert uid not in ids
Ejemplo n.º 6
0
def test_report_one():
    log = tasks.Log()
    worker_artem = tasks.Worker("Artem")
    worker_alex = tasks.Worker("Alex")
    worker_masha = tasks.Worker("Masha")
    masha_fixet_task = tasks.Task("Task1", 300)
    fixet_task = tasks.Task("Task2", 100)
    hoyrly_task = tasks.HourlyTask("Task3", 200, 3)
    worker_masha.get_task(masha_fixet_task, log)
    worker_artem.get_task(fixet_task, log)
    worker_alex.get_task(hoyrly_task, log)
    assert log.report() == 'Masha\t$300\nArtem\t$100\nAlex\t$600'
Ejemplo n.º 7
0
def test_tasks_reporting():
    logg = tasks.Log()
    t1 = tasks.Task("one", 20)
    t2 = tasks.Task("two", 70)
    d = tasks.DailyPlan()
    d.create_plan(t1, t2)
    w1 = tasks.Worker("John")
    w2 = tasks.Worker("Mary")
    w2.get_task_from_dp(d)
    w2.log_task(logg, w2.get_current_task())
    w1.get_task_from_dp(d)
    w1.log_task(logg, w1.get_current_task(), 5)
    assert (logg.get_report()) == """Mary earned $70
Ejemplo n.º 8
0
    def test_tasks(self):
        task0 = tasks.Task(lambda: print('exec8'),
                           id='task0',
                           priority='on-idle')
        task1 = tasks.Task(lambda: print('exec4'), id='task1', priority=8)
        task2 = tasks.Task(lambda: print('exec1'),
                           id='task2',
                           priority='immediate')
        task3 = tasks.Task(lambda: print('exec5'),
                           id='task3',
                           priority='normal')
        task4 = tasks.Task(lambda: print('exec7'),
                           id='task4',
                           priority='inferior')
        task5 = tasks.Task(lambda: print('exec6'), id='task5', priority=-16)
        task6 = tasks.Task(lambda: print('exec3'),
                           id='task6',
                           priority='superior')
        task7 = tasks.Task(lambda: print('exec2'), id='task7', priority='next')

        task_manager = tasks.TaskManager(logging)
        task_manager.add_task(task1)
        task_manager.add_task(task2)
        task_manager.add_task(task0)
        task_manager.add_task(task3)
        task_manager.add_task(task4)
        task_manager.add_task(task4, ignore_if_duplicate=False)
        task_manager.add_task(task5)
        task_manager.add_task(task6)
        task_manager.add_task(task7)

        task_manager.run()
        time.sleep(1)
        task_manager.stop()
Ejemplo n.º 9
0
def test_tasks_reporting():
    """Check if tasks are properly logged and reported"""
    logg = log.Log()
    task_1 = tasks.Task("one", 20)
    task_2 = tasks.Task("two", 70)
    day_plan_obj = day_plan.DailyPlan()
    day_plan_obj.create_plan(task_1, task_2)
    worker_1 = worker.Worker("John")
    worker_2 = worker.Worker("Mary")
    worker_2.get_task_from_dp(day_plan_obj)
    worker_2.log_task(logg, worker_2.get_current_task())
    worker_1.get_task_from_dp(day_plan_obj)
    worker_1.log_task(logg, worker_1.get_current_task(), 5)
    assert (logg.get_report()) == """Mary earned $70
Ejemplo n.º 10
0
 def enter_all(self, task=None):
     """Obtain user-supplied info for task"""
     title = self.enter_title(task)
     date = self.enter_date(task)
     minutes = self.enter_minutes(task)
     notes = self.enter_notes(task)
     return tasks.Task(title, minutes, date, notes)
Ejemplo n.º 11
0
 def test_bad_id(self):
     """
     A non-int id should raises an exceptions.
     """
     with pytest.raises(TypeError):
         tasks.update(task_id={"dict insted": 1},
                      task=tasks.Task())
Ejemplo n.º 12
0
    def run_in_ship(self, ship):
        #print "called in ship"
        def _internalab(t, r):
            t.data[0].play()
            t.data[0].blit(r.screen, (t.data[1][0], t.data[1][1]))

        def _internalde(t, r):
            if t.delete:
                tasks.add_task(
                    self.root, "render_after_entities",
                    tasks.Task(self.root, _internalab,
                               self.config["style"]["sum_duration"], t.data))

        ax = ship.rotated_rect.centerx + random.choice(
            xrange(int(-ship.rotated_rect.size[0] / 2),
                   int(ship.rotated_rect.size[0] /
                       2))) - self.config["style"].get("offset", [0, 0])[0]
        ay = ship.rotated_rect.centery + random.choice(
            xrange(int(-ship.rotated_rect.size[1] / 2),
                   int(ship.rotated_rect.size[1] /
                       2))) - self.config["style"].get("offset", [0, 0])[1]

        built_array = []
        for i in self.config["style"]["frames"]:
            built_array.append([self.root.gamedb(i[0]), i[1]])
        animation = pyganim.PygAnimation(built_array, loop=0)
        #animation.play()

        tasks.add_task(
            self.root, "render_last",
            tasks.Task(self.root, _internalde, self.config["time"],
                       (animation, [ax, ay])))
Ejemplo n.º 13
0
def test_after_add():
    """tasks's count should add 1 after tasks.add()"""
    count_before = tasks.count()
    task = tasks.Task('do something')
    tasks.add(task)
    count_after = tasks.count()
    assert count_after == count_before + 1
Ejemplo n.º 14
0
def main():
    updater = Updater(conf.TELEGRAM_API_KEY)

    dp = updater.dispatcher

    dp.add_handler(handlers.main_conv_handler)
    dp.add_handler(handlers.callback_query_handler)
    dp.add_error_handler(handlers.error)

    for t in database.tasks.get_all():
        id, chat_id, text, time = t

        utc_now = int(datetime.datetime.utcnow().timestamp())
        if time - utc_now < 0:
            database.tasks.delete(id, chat_id)
            continue
        job = dp.job_queue.run_once(handlers.alarm, time - utc_now, context=(id, chat_id, text))
        task = tasks.Task(id, text, time, job)

        chat_data = dp.chat_data[chat_id]
        if 'TASKS' not in chat_data:
            chat_data['TASKS'] = []
        chat_data['TASKS'].append(task)

    updater.start_polling()
    updater.idle()

    print('End')
Ejemplo n.º 15
0
 def test_Task_ShouldGetUid(self, mock_getUid):
     t = tasks.Task(startCb=TestTasks._dummyCb1,
                    completedCb=TestTasks._dummyCb2,
                    failedCb=TestTasks._dummyCb3)
     self.assertEqual(self.EXPECTED_UID_FROM_GET_UID, t.uid)
     self.assertEqual(TestTasks._dummyCb1, t.startCb)
     self.assertEqual(TestTasks._dummyCb2, t.completedCb)
Ejemplo n.º 16
0
def test_after_del():
    """tasks'count should sub 1 after tasks.del()"""
    task_id = tasks.add(tasks.Task('something'))
    count_before = tasks.count()
    tasks.delete(task_id)
    count_after = tasks.count()
    assert count_after == count_before - 1
Ejemplo n.º 17
0
def test_added_task_has_id_set():
    """Make sure the task_id field is set by tasks.add()."""

    new_task = tasks.Task("sit in chair", owner='me', done=True)
    task_id = tasks.add(new_task)

    task_from_db = tasks.get(task_id)
    assert task_from_db.id == task_id
Ejemplo n.º 18
0
    def run_in_ship(self, ship):
        def _internal(t, r):
            r.screen.blit(t.data[1], t.data[0])

        tasks.add_task(
            self.root, "render_before_particles",
            tasks.Task(self.root, _internal, self.config["time"],
                       (ship.rotated_rect.copy(), ship.rotated_image.copy())))
Ejemplo n.º 19
0
    def run(self):
        def _internalsx(t, r):
            if t.delete:
                r.gamedb.get_asset(t.data).play()

        tasks.add_task(
            self.root, "render_last",
            tasks.Task(self.root, _internalsx, self.config["time"],
                       self.config["sound"]))
Ejemplo n.º 20
0
	def do_screen_flash_end(self):
		DURATION=0.4
		EXPONENT=2.2
		def _internal(t, r):
			surf=pygame.Surface((1300,700))
			surf.fill(pygame.Color(255,255,255))
			surf.set_alpha(255-((t.curr_time**EXPONENT)*(255/DURATION**EXPONENT)))
			r.screen.screen.blit(surf, (0,0))
		tasks.add_task(self.root, "render_last", tasks.Task(self.root, _internal, DURATION))
Ejemplo n.º 21
0
 def test_multipleCalls(self):
     N = 5
     expected = [('r', 2 * x) for x in xrange(N)]
     worker = workers.AsyncWorker()
     for k in self.multiplerator(N, expected):
         task = tasks.Task(self._twistyTask, (k, ), {}, 0, None)
         self.d = task.d
         worker.run(task)
     return self.dm.addCallback(lambda _: worker.stop())
Ejemplo n.º 22
0
def test(r, n, p):
    def _internal(t, r):
        p = t.data[1]
        n = t.data[0]
        r.screen.draw_line(n["color"], p.get_center(),
                           ship2.rotated_rect.center, n["thickness"])

    tasks.add_task(r, "render_last",
                   tasks.Task(_internal, n["duration"], (n, p)))
    return True
Ejemplo n.º 23
0
    def test_Task_UidAndCbsShouldBeReadOnly(self):
        t = tasks.Task(TestTasks._dummyCb1)

        with self.assertRaises(AttributeError):
            t.startCb = 1

        with self.assertRaises(AttributeError):
            t.completedCb = 1

        with self.assertRaises(AttributeError):
            t.uid = 1
Ejemplo n.º 24
0
def read_generated_task(task_id, token):
    if type(task_id) is not int:
        raise tasks.TaskNotFoundError(task_id)
    task_dir = os.path.join(configuration['tasks_path'], str(task_id),
                            'generated', str(token))
    task_file = os.path.join(task_dir, 'task.json')
    try:
        with open(task_file) as f:
            task_str = f.read()
        task = json.loads(task_str)
        return tasks.Task(task_id, task)
    except FileNotFoundError:
        raise tasks.TaskNotFoundError(task_id)
Ejemplo n.º 25
0
	def do_screen_flash(self):
		DURATION=0.4
		EXPONENT=2.2
		def _internal(t, r):
			surf=pygame.Surface((1300,700))
			surf.fill(pygame.Color(255,255,255))
			surf.set_alpha((t.curr_time**EXPONENT)*(255/DURATION**EXPONENT))
			r.screen.screen.blit(surf, (0,0))
		tasks.add_task(self.root, "render_last", tasks.Task(self.root, _internal, DURATION))
		def _internalt(t, r):
			self=t.data
			if t.delete:
				self.xwd_charge_status=0
				self.xwd_is_charging=0
				self.xwd_at_warp=1
				self.xwd_orig_speed=self.parent.max_speed
				if self.xwd_warp_factor:
					self.parent.max_speed*=self.xwd_warp_factor
				else:
					self.parent.max_speed=self.xwd_warp_speed
				self.parent.rigidbody._vector.magnitude=self.parent.max_speed
		tasks.add_task(self.root, "render_last", tasks.Task(self.root, _internalt, DURATION, self))
Ejemplo n.º 26
0
    def run_in_item(self, item):
        def _internal(t, r):
            p = t.data[1]
            n = t.data[0]
            try:
                r.screen.draw_line(
                    n["color"], t.data[1].get_center(),
                    t.data[1].parent.targeted.rotated_rect.center,
                    n["thickness"])
            except BaseException:
                pass

        tasks.add_task(
            self.root, "render_last",
            tasks.Task(self.root, _internal, self.config["duration"],
                       (self.config, item)))
Ejemplo n.º 27
0
    def event_state(self, state, event):
        if event.type == pygame.USEREVENT:
            if event.sg_type == triggers.UE_SHL_DAMAGE_DEALT:
                if event.system.shields > 30:
                    if not event.x:
                        event.x, event.y = event.source.rotated_rect.center

                    # dx =  - event.source.rotated_rect.centerx - event.x
                    # dy =  - event.source.rotated_rect.centery - event.y

                    angle = get_angle(event.system.ship.rotated_rect.centerx,
                                      event.x,
                                      event.system.ship.rotated_rect.centery,
                                      event.y)

                    orig_image = pygame.transform.scale(
                        absroot.gamedb("image_shield_hit_default"),
                        (event.system.ship.rotated_rect.width + 30,
                         event.system.ship.rotated_rect.height + 30))

                    def _(t, r):
                        orig_rect = pygame.Rect((0, 0), orig_image.get_size())
                        orig_rect.center = (
                            event.system.ship.rotated_rect.centerx,
                            event.system.ship.rotated_rect.centery)

                        rot_image, rot_rect = rot_center(
                            orig_image, orig_rect, angle)
                        absroot.screen.blit(rot_image, rot_rect)

                    tasks.add_task(self.root, "render_after_entities",
                                   tasks.Task(absroot, _, 2))
            if event.sg_type == triggers.UE_SHIELDS_DOWN:
                if absroot.game_time - self.last_shields_warning > 10:
                    self.last_shields_warning = absroot.game_time
                    if (event.system.ship ==
                            absroot.state_manager.getcurr().player):
                        absroot.gamedb("snd_shelds_down_warning_player").play()
            if event.sg_type == triggers.UE_HUL_DAMAGE_DEALT:
                if absroot.game_time - self.last_hull_warning > 10:
                    if event.system.hull < 20:
                        self.last_hull_warning = absroot.game_time
                        if (event.system.ship ==
                                absroot.state_manager.getcurr().player):
                            absroot.gamedb("snd_hull_breach_player").play()
Ejemplo n.º 28
0
    def run_in_impact(self, item, impacted, projectile):
        def _internal(t, r):
            t.data[0].blit(r.screen, (t.data[1][0], t.data[1][1]))

        built_array = []
        for i in self.config["style"]["frames"]:
            built_array.append([self.root.gamedb(i[0]), i[1]])
        animation = pyganim.PygAnimation(built_array, loop=0)
        animation.play()
        x = projectile.rigidbody.x - self.config["style"].get(
            "offset", [0, 0])[0]
        y = projectile.rigidbody.y - self.config["style"].get(
            "offset", [0, 0])[1]
        tasks.add_task(
            self.root, "render_after_entities",
            tasks.Task(self.root, _internal,
                       self.config["style"]["sum_duration"],
                       (animation, [x, y])))
Ejemplo n.º 29
0
    def run_in_ship(self, ship):
        def _internalde(t, r):
            if t.delete:
                t.root.particlemanager.add_particles(
                    particles.make_explosion_cfg(t.root, t.data[0], t.data[1],
                                                 t.data[2]))

        ax = ship.rotated_rect.centerx + random.choice(
            xrange(int(-ship.rotated_rect.size[0] / 2),
                   int(ship.rotated_rect.size[0] / 2)))
        ay = ship.rotated_rect.centery + random.choice(
            xrange(int(-ship.rotated_rect.size[1] / 2),
                   int(ship.rotated_rect.size[1] / 2)))

        tasks.add_task(
            self.root, "render_last",
            tasks.Task(self.root, _internalde, self.config["time"],
                       (ax, ay, self.config["style"])))
Ejemplo n.º 30
0
def get_task(message):
    if message.chat.id != vip_chat_id and message.chat.id != debug_chat_id:
        bot.send_message(message.chat.id,
                         "ПО ЛИЧКАМ ШУШУКАЕТЕСЬ? НЕ ТОТ ЧЯТИК!",
                         reply_to_message_id=message.message_id)
    else:
        player = findplayer(message.from_user)
        if time.time() - player.last_task_time > config.seconds_in_day:
            player.task_status = 0
        if player.task_status == 1:
            bot.send_message(message.chat.id,
                             "ТЫ УЖЕ ЧТО-ТО ДЕЛАЕШЬ!",
                             reply_to_message_id=message.message_id)
        elif player.task_status == 2:
            bot.send_message(message.chat.id,
                             "ТЫ УЖЕ НЕ СМОГ!",
                             reply_to_message_id=message.message_id)
        elif player.task_status == 0:
            if time.time() - player.last_task_time < config.seconds_in_day:
                bot.send_message(message.chat.id,
                                 "НОВОЕ ЗАДАНИЕ БУДЕТ НЕСКОРО!",
                                 reply_to_message_id=message.message_id)
            else:
                player.task_status = 1
                player.last_task_time = time.time()
                player.last_task_mssg = message.message_id
                rand = random.randint(1, 500)
                if rand == 237:
                    task = [
                        'CAADAgADaQADP_vRD78igQttLbufAg',
                        'КОЛДУЮ, КОЛДУЮ... ВЖУХ! И ТЫ ПИДОР ДНЯ.', 0, 0
                    ]
                else:
                    task = random.choice(config.tasks)
                bot.send_sticker(message.chat.id, task[0])
                if player.task_completed < 40:
                    bot.send_message(message.chat.id, task[1])
                else:
                    bot.send_message(message.chat.id,
                                     "ТЫ УЖЕ БОЛЬШОЙ, САМ РАЗБРЕШЬСЯ")
                player.task = tasks.Task(*task)
                player.informed = False
                player.mess_sended = False
                backup(None)