Пример #1
0
 def testUpdate(self):
     """test the model function to update the timer"""
     userId = 1
     title = "test"
     description = "test"
     zoomLink = ""
     startTime = ""
     duration = 25
     breakTime = 5
     round = 1
     newTimer = Timer(userId=str(userId),
                      title=str(title),
                      description=str(description),
                      zoomLink=str(zoomLink),
                      startTime=str(startTime),
                      duration=str(duration),
                      breakTime=str(breakTime), round=str(round))
     data = {'id': None,
             'userId': '2',
             'title': 'test2',
             'description': 'test2',
             'zoomLink': '',
             'startTime': '',
             'duration': '30',
             'breakTime': '10',
             'round': '2'}
     newTimer.update(data)
     self.assertEqual(data,newTimer.toDict())
Пример #2
0
class TestTimer(unittest.TestCase):
    '''
    Test class to test the behaviour of the Timer Class
    '''
    def setUp(self):
        self.user_John_Doe = User(
            username='******',
            password='******',
            email='*****@*****.**',
            bio='I love coding',
            profile_pi_path='https://image.tmdb.org/t/p/w500/jdjdjdjn',
            pitch='talk is cheap show me the codes')
        self.new_timer = Timer(username='******',
                               pomodoro_interval='1hr',
                               break_interval='5min')

    def tearDown():
        Timer.Clear_timer()

    def test_instance(self):
        self.assertTrue(isinstance(self.new_timer, Timer))

    def test_check_instance_variables(self):
        self.asserEquals(self.new_timer.username, 'John Doe')
        self.assertEquals(self.new_timer.pomodoro_interval, '1hr')
        self.assertEquals(self.new_timer.break_interval, '5min')

    def test_save_timer(self):
        self.new_timer.save_timer()
        self.assertTrue(len(Timer.query.all() > 0))
Пример #3
0
 def testToDict(self):
     '''test the function to transfer a model to a dicionary'''
     userId = 1
     title = "test"
     description = "test"
     zoomLink = ""
     startTime = ""
     duration = 25
     breakTime = 5
     round = 1
     newTimer = Timer(userId=str(userId),
                      title=str(title),
                      description=str(description),
                      zoomLink=str(zoomLink),
                      startTime=str(startTime),
                      duration=str(duration),
                      breakTime=str(breakTime),
                      round=str(round))
     result = newTimer.toDict()
     expectedResult = {'id': None,
                       'userId': '1',
                       'title': 'test',
                       'description': 'test',
                       'zoomLink': '',
                       'startTime': '',
                       'duration': '25',
                       'breakTime': '5',
                       'round': '1'}
     self.assertEqual(result,expectedResult)
Пример #4
0
 def setUp(self):
     self.user_John_Doe = User(
         username='******',
         password='******',
         email='*****@*****.**',
         bio='I love coding',
         profile_pi_path='https://image.tmdb.org/t/p/w500/jdjdjdjn',
         pitch='talk is cheap show me the codes')
     self.new_timer = Timer(username='******',
                            pomodoro_interval='1hr',
                            break_interval='5min')
Пример #5
0
def time_to_db(user, time, dataset):
    logging.info(f"writing user labels to db {current_user.username}")

    label = Timer(dataset=dataset, user_id=user, time=time)

    db.session.add(label)
    db.session.commit()
Пример #6
0
def handle(req, res):
    try:
        # Эта функция обрабатывает запросы пользователя.
        if req["request"]["nlu"]["tokens"][0].lower() in [
                'включи', 'включить'
        ] and req["request"]["nlu"]["tokens"][1].lower() in ['лампу']:
            name = req["request"]["nlu"]["tokens"][2].lower()
            device = Devices.query.filter_by(dev_name=name,
                                             type='lamp').first()
            device.state = True
            res['response']['text'] = 'Включаю'
            db.session.commit()
        if req["request"]["nlu"]["tokens"][0].lower() in [
                'выключи', 'выключить'
        ] and req["request"]["nlu"]["tokens"][1].lower() in ['лампу']:
            res['response']['text'] = 'Выключаю'
            name = req["request"]["nlu"]["tokens"][2].lower()
            device = Devices.query.filter_by(dev_name=name).first()
            device.state = False
            db.session.commit()
        if req["request"]["nlu"]["tokens"][0].lower() in ['таймер']:
            dev_name = req["request"]["nlu"]["tokens"][2].lower()
            on_hour = req["request"]["nlu"]["entities"][0]['value']['hour']
            on_minute = req["request"]["nlu"]["entities"][0]['value']['minute']
            off_hour = req["request"]["nlu"]["entities"][1]['value']['hour']
            off_minute = req["request"]["nlu"]["entities"][1]['value'][
                'minute']
            timer = Timer(dev_name=dev_name,
                          on_minute=on_minute,
                          on_hour=on_hour,
                          off_hour=off_hour,
                          off_minute=off_minute)
            db.session.add(timer)
            db.session.commit()
    except BaseException:
        res['response']['text'] = "Неправильный запрос"
Пример #7
0
def set_up_timers_form(number_timers):
    error = None
    number_timers = int(number_timers)
    attribute_dict = {
        'name': None,
        'hours': None,
        'minutes': None,
        'seconds': None
    }

    for timer in range(number_timers):
        for attribute_name in attribute_dict:
            attribute = "timer_{}_{}".format(timer, attribute_name)
            if attribute_name == 'name':
                setattr(SetUpTimers, attribute,
                        StringField(attribute, validators=[DataRequired()]))
            else:
                setattr(
                    SetUpTimers, attribute,
                    StringField(
                        attribute,
                        validators=[
                            DataRequired(),
                            Regexp("^(\d?[0-9]|[0-9]0)$",
                                   message='must be whole number between 1-99')
                        ]))

    form = SetUpTimers()
    object_list = []
    for timer in range(number_timers):
        form_dict = attribute_dict.copy()

        for attribute_name in attribute_dict:
            attribute = "timer_{}_{}".format(timer, attribute_name)
            form_dict[attribute_name] = getattr(form, attribute)

        object_list.append(form_dict)

    if form.validate_on_submit():
        user = User.query.filter_by(id=current_user.get_id()).first()
        if Configuration.query.filter_by(
                name=form.configuration.data).first() != None:
            error = 'Configuration with same name already exits'

        else:
            configuration = Configuration(name=form.configuration.data,
                                          user=user)
            db.session.add(configuration)
            db.session.commit()

            arg_dict = attribute_dict.copy()
            for form_dict in object_list:
                for key in arg_dict:
                    arg_dict[key] = getattr(form_dict[key], "data")
                    if not key == 'name':
                        if len(arg_dict[key]) == 1:
                            arg_dict[key] = "0" + arg_dict[key]
                timer = Timer(name=arg_dict['name'],
                              hours=arg_dict['hours'],
                              minutes=arg_dict['minutes'],
                              seconds=arg_dict['seconds'],
                              configuration=configuration)
                db.session.add(timer)
                db.session.commit()

            return redirect(
                url_for('timer_array', configuration=configuration.name))
    return render_template('set_up_timers_form.html',
                           logged_in=current_user.is_authenticated,
                           form=form,
                           timer=timer,
                           object_list=object_list,
                           error=error)
Пример #8
0
 def tearDown():
     Timer.Clear_timer()
Пример #9
0
    def testCreateTasksToTimers(self):
        """Test create a relation between task and timers"""
        testTimerId = -100
        testTaskid = -100
        testTimer = Timer.query.get(testTimerId)
        testTask = Task.query.get(testTaskid)
        testUser = 0
        change = False
        if not testTimer:
            testTimer = Timer(id=testTimerId,
                              userId=testUser,
                              title="test timer",
                              description="test timer description",
                              zoomLink="",
                              startTime=datetime.now().isoformat(),
                              duration=5,
                              breakTime=5,
                              round=1)
            db.session.add(testTimer)
            change = True
        if not testTask:
            testTask = Task(id=testTaskid,
                            userId=testUser,
                            name="test task",
                            status=0)
            db.session.add(testTask)
            change = True

        if change:
            db.session.commit()

        response = self.testApp.post('/task_timers/',
                                     json={
                                         "taskId": 167,
                                         "timerId": 106,
                                         "userId": '106511126518215594731'
                                     })

        responseBody = response.get_json()
        self.assertEqual(responseBody['code'], 201)
        self.assertEqual(str(responseBody['data']['taskId']), str(167))
        self.assertEqual(str(responseBody['data']['timerId']), str(106))
        # newTaskTestId = int(responseBody['data']['id'])

        # test duplicate with the same task and timer id, which will cause exception
        response = self.testApp.post('/task_timers/',
                                     json={
                                         "taskId": 167,
                                         "timerId": 106,
                                         "userId": '106511126518215594731'
                                     })
        responseBody = response.get_json()
        self.assertEqual(responseBody['code'], 500)

        response = self.testApp.post('/task_timers/',
                                     json={
                                         "taskId": testTaskid,
                                         "timerId": testTaskid,
                                     })
        responseBody = response.get_json()
        self.assertEqual(responseBody['code'], 400)
Пример #10
0
def createTimers():
    """This function is for the server to create new timers"""
    data =  request.get_json()
    postAttrs = ['userId', 'title', 'startTime', 'duration', 'breakTime', 'round']
    code, msg, result = 0, "", {"data": None}
    if not judgeKeysExist(data, postAttrs):
        code, msg = 400, apiStatus.getResponseMsg(400)
    else:
        if not judgeInputValid(data) :
            code, msg = 400, apiStatus.getResponseMsg(400)
            result["code"] = code
            result["message"] = msg
            return jsonify(result)
        userId = data['userId']
        title = data['title']
        description = data['description'] if 'description' in data else None
        zoomLink = data['zoomLink'] if 'zoomLink' in data else None
        startTime = data['startTime']
        # formatStartTime = parser.parse(startTime)
        # testFormStartTime = datetime.datetime.fromisoformat(startTime)
        # print(formatStartTime, testFormStartTime)
        duration = int(data['duration'])
        breakTime = int(data['breakTime'])
        round = int(data['round'])

        oldTimers = Timer.query.filter_by(userId=userId).all()
        if oldTimers is not None:
            for oldTimer in oldTimers:
                totalDuration = (oldTimer.duration + oldTimer.breakTime) * oldTimer.round
                totalDuration = datetime.timedelta(minutes=totalDuration)
                endTime =  parser.parse(oldTimer.startTime) + totalDuration
                # sTime = datetime.datetime.strptime(startTime, "%Y-%m-%d %H:%M:%S")
                sTime = parser.parse(startTime)
                newDuration = (duration + breakTime) * round
                newDuration = datetime.timedelta(minutes=newDuration)
                eTime = sTime + newDuration
                if parser.parse(oldTimer.startTime) <= sTime < endTime or parser.parse(oldTimer.startTime) < eTime <= endTime:
                    code, msg = 403, apiStatus.getResponseMsg(403)
                    result["code"] = code
                    result["message"] = msg
                    return jsonify(result)
                if sTime < parser.parse(oldTimer.startTime) and eTime > endTime:
                    code, msg = 403, apiStatus.getResponseMsg(403)
                    result["code"] = code
                    result["message"] = msg
                    return jsonify(result)
        try:
            newTimer = Timer(userId=str(userId), title=str(title),
                             description=str(description), zoomLink=str(zoomLink),
                             startTime=startTime, duration=str(duration),
                             breakTime=str(breakTime), round=str(round))
            db.session.add(newTimer)
            newTimerTwo = Timer.query.filter_by(userId=userId).all()
            # print(newTimerTwo)

            newTimerToUser = TimerToUser(timerId=newTimer.id, userId=userId, status=1)
            db.session.add(newTimerToUser)
            db.session.commit()

            result["data"] = newTimer.toDict({
                "added": True,
                "isCreator": True,
                "timerToUserId": userId,
            })
            # result["data"]["startTime"] = startTime # remain to be string for the frontend consistent, or change to utcstring
            code, msg = 201, apiStatus.getResponseMsg(201)
        except:
            code, msg = 500, apiStatus.getResponseMsg(500)
    result["code"] = code
    result["message"] = msg
    return jsonify(result)