Ejemplo n.º 1
0
def client():
    """ My custom test client.
    """
    app.config['TESTING'] = True
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
    # app.config['SQLALCHEMY_DATABASE_URI'] = \
    #     'mysql+mysqlconnector://test:Test12345678!@localhost/iot_test'

    with app.app_context():
        db.drop_all()
        db.create_all()

        # Add test user
        user = User(username='******', email='*****@*****.**')
        user.set_password('test')
        db.session.add(user)
        db.session.commit()

        # Add test device
        device = Device(name='test', display_name='test', user=user)
        db.session.add(device)
        db.session.commit()

        schema = {
            'test1': ['test1', 2, 1, 0],
            'test2': ['test2', 2, 1, 0],
            'control': ['control', 3, 1, 1],
        }
        device.set_schema(schema)

        # Add test data
        new_data = DeviceData(time=datetime.utcfromtimestamp(1500000000),
                              data={
                                  'test1': 10.0,
                                  'test2': 12.0,
                                  'control': False,
                              },
                              device=device)
        db.session.add(new_data)
        db.session.commit()

        # Get token
        access_token = create_access_token(identity=user.username)
        refresh_token = create_refresh_token(identity=user.username)

        my_client = MyTestClient(access_token,
                                 refresh_token,
                                 default_auth=TokenType.access)

    yield my_client

    with app.app_context():
        db.session.remove()
        db.drop_all()
 def test_final(self):  #Check if game.html has been created
     with app.app_context():
         response = self.app.get("/final",
                                 data=dict(highscore="test",
                                           user="******",
                                           score=2))
         self.assertIn("displayed on top of the page", str(response.data))
Ejemplo n.º 3
0
 def test_db_access_created_collection(self):
     with app.app_context():
         c_obj = self.mock.collection()
         self.db.set_collection(c_obj)
         self.assertEqual(
             json.dumps(c_obj),
             json.dumps(self.db.get_collection(c_obj.id).pop()))
Ejemplo n.º 4
0
    def save_class_data(self, class_data):

        one_class = JingFenClass.query.filter_by(
            jd_uid=class_data['jd_uid']).first()
        name = class_data['name'],
        pic_url = class_data['pic_url'],
        url = class_data['url'],
        content_skus = class_data['product_sku_ids'],
        sub_name = class_data['sub_name'],
        jd_uid = class_data['jd_uid'],
        type = class_data['type']
        if one_class:
            one_class.name = name
            one_class.pic_url = pic_url
            one_class.url = url
            one_class.content_skus = content_skus
            one_class.sub_name = sub_name
            one_class.type = type
        else:
            one_class = JingFenClass(name)
            one_class.name = name
            one_class.pic_url = pic_url
            one_class.content_skus = content_skus
            one_class.sub_name = sub_name
            one_class.jd_uid = jd_uid
            one_class.url = url
            one_class.type = type
        with app.app_context():
            db.session.add(one_class)
            db.session.commit()
Ejemplo n.º 5
0
 def test_get_ship_data(self):
     with app.app_context():
         psa = PixelStarshipsApi()
         id = psa.get_user_id('adam')
         data = psa.inspect_ship(id)
         pprint(data)
     assert True
Ejemplo n.º 6
0
def client():
    with app.test_client() as client:
        with app.app_context():
            app.init_app()
        yield client
        db.session.remove()
        db.drop_all()
Ejemplo n.º 7
0
 def test_ldp_delete_created_collection(self):
     with app.app_context():
         c_obj = self.mock.collection()
         self.db.set_collection(c_obj)
         self.db.del_collection(c_obj.id)
         with self.assertRaises(NotFoundError) as context:
             self.db.get_collection(c_obj.id)
Ejemplo n.º 8
0
    def test_if_verification_unssuccessul(self):
        with app.app_context():
            email = '*****@*****.**'
            expires = int(time.time()) + 86400
            fake_expire = int(time.time()) + 3600
            verification_code = generate_verification_code(
                "{email}{expires}".format(email=email, expires=expires))

            response = app.test_client().get(
                '/verify/{email}/{verification_code}/{expires}'.format(
                    email='*****@*****.**',
                    verification_code=verification_code,
                    expires=expires),
                follow_redirects=True)
            self.assertIn(b'Verification failed!', response.data)

            response = app.test_client().get(
                '/verify/{email}/{verification_code}/{expires}'.format(
                    email=email,
                    verification_code='wrong-code',
                    expires=expires),
                follow_redirects=True)
            self.assertIn(b'Verification failed!', response.data)

            response = app.test_client().get(
                '/verify/{email}/{verification_code}/{expires}'.format(
                    email=email,
                    verification_code=verification_code,
                    expires=fake_expire),
                follow_redirects=True)
            self.assertIn(b'Verification failed!', response.data)
Ejemplo n.º 9
0
 def test_ldp_access_created_collection(self):
     with app.app_context():
         # todo: post collection to sparql, retrieve via LDP and compare
         c_obj = self.mock.collection()
         self.db.set_collection(c_obj)
         r_obj = self.db.get_collection(c_obj.id).pop()
         self.assertDictEqual(c_obj.dict(), r_obj.dict())
Ejemplo n.º 10
0
def insert_project(num):
    """插入数据库数据"""
    with app.app_context() as ctx:
        for i in range(num):
            project = ProjectInfo(project_name=f'Project {i}')
            db.session.add(project)
        db.session.commit()
Ejemplo n.º 11
0
 def test_db_create_service_on_filesystem(self):
     with app.app_context():
         s_obj = self.mock.service()
         self.db.set_service(s_obj)
         self.assertTrue(
             os.path.isfile(os.path.join(self.db.d_data,
                                         self.db.d_service)))
Ejemplo n.º 12
0
def courses():
    with app.app_context():
        data = [
            course.description
            for course in Course.query.order_by(Course.id).all()
        ]

    courses = pool.map(tokenize, data)

    d = corpora.Dictionary(courses)
    d.save("gensim/courses.dict")

    corpus = pool.map(d.doc2bow, courses)
    corpora.MmCorpus.serialize("gensim/courses.mm", corpus)

    corpus = corpora.MmCorpus("gensim/courses.mm")

    tfidf = models.TfidfModel(corpus)
    tfidf.save("gensim/courses.tfidf")
    corpus = tfidf[corpus]

    model = models.LsiModel(corpus, id2word=d, num_topics=64)
    model.save("gensim/courses.lsi")
    sims = similarities.MatrixSimilarity(model[corpus])

    sims.save("gensim/courses.sim")
 def tearDown(self):
     """
     Blanks database
     """
     with app.app_context():
         db.session.remove()
         db.drop_all()
Ejemplo n.º 14
0
def add_project(nums):
    # 推入上下文
    with app.app_context() as ctx:
        for i in range(nums):
            project = ProjectInfo(project_name=f'project{i}',
                                  simple_desc=f'project{i},简介')
            db.session.add(project)
        db.session.commit()
Ejemplo n.º 15
0
 def test_category_view_dishes(self):
     """
     Testing response for displaying categories
     """
     with app.app_context():
         resp = self.app.get('/category_view/dishes')
         self.assertEqual(resp.status_code, 200)
         self.assertIn('Main', str(resp.data))
Ejemplo n.º 16
0
 def test_get_recipes(self):
     """
     Testing displaying recipes
     """
     with app.app_context():
         resp = self.app.get('/get_recipes')
         self.assertEqual(resp._status_code, 200)
         self.assertIn('displaying ', str(resp.data))
Ejemplo n.º 17
0
 def validate_email(self, email):
     with app.app_context():
         cursor = mysql.connection.cursor()
         cursor.callproc("RecoverCredentials", [self.email.data])
         found = cursor.fetchone()
         cursor.close()
     if found is None:
         raise ValidationError('There is no account with that email.')
Ejemplo n.º 18
0
 def test_summarise(self):
     """
     This test checks rendering template in summarise view
     """
     with app.app_context():
         resp = self.app.get('/summarise')
         self.assertEqual(resp._status_code, 200)
         self.assertIn('What would you like to summarise:', str(resp.data))
Ejemplo n.º 19
0
def client():
    app.config['TESTING'] = True
    client = app.test_client()

    with app.app_context():
        create_tables()

    yield client
Ejemplo n.º 20
0
 def test_category_view_cuisines(self):
     with app.app_context():
         """
         Testing response for displaying categories
         """
         resp = self.app.get('/category_view/cuisines')
         self.assertEqual(resp.status_code, 200)
         self.assertIn('American', str(resp.data))
Ejemplo n.º 21
0
 def test_db_access_multiple_collections(self):
     with app.app_context():
         c_objs = [self.mock.collection() for _ in range(randint(2, 5))]
         for c in c_objs:
             self.db.set_collection(c)
         self.assertSetEqual(
             set([json.dumps(c) for c in c_objs]),
             set([json.dumps(c) for c in self.db.get_collection()]))
Ejemplo n.º 22
0
 def test_db_create_collection_on_filesystem(self):
     with app.app_context():
         c_obj = self.mock.collection()
         self.db.set_collection(c_obj)
         self.assertTrue(
             os.path.isfile(
                 os.path.join(self.db.d_data, c_obj.id.replace('/', '∕'),
                              self.db.d_collection)))
 def setUp(self):
     """
     Checks if database exists
     Runs for each test method
     """
     with app.app_context():
         db.create_all()
     self.app = app.test_client
     self.app_context = app.app_context
 def setUpClass(cls):
     """
     Runs once for each test case
     """
     app.config[
         "SQLALCHEMY_DATABASE_URI"] = BaseTest.SQLALCHEMY_DATABASE_URI
     app.config["DEBUG"] = False
     with app.app_context():
         db.init_app(app)
Ejemplo n.º 25
0
def add_project(nums):
    with app.app_context() as ctx:
        for i in range(nums):
            project = ProjectInfo(project_name=F"project{i}",
                                  simple_desc=F"project{i},简介")
            db.session.add(project)
            # 此时如果直接进行db的操作的话不会成功,因为没有推入上下文
            # 使用with as 打开上下文环境,将其推入
        db.session.commit()
Ejemplo n.º 26
0
 def test_ldp_access_with_ldp(self):
     with app.app_context():
         # todo: post collection to sparql, retrieve via LDP and compare
         c_obj = self.mock.collection()
         self.db.set_collection(c_obj)
         g = Dataset().parse(self.db.marmotta.ldp(encoder.encode(c_obj.id)),
                             format="n3")
         r_obj = self.db.RDA.graph_to_object(g).pop()
         self.assertDictEqual(c_obj.dict(), r_obj.dict())
Ejemplo n.º 27
0
 def test_db_delete_created_collection(self):
     with app.app_context():
         c_obj = self.mock.collection()
         self.db.set_collection(c_obj)
         self.db.del_collection(c_obj.id)
         self.assertFalse(
             os.path.isfile(
                 os.path.join(self.db.d_data, c_obj.id,
                              self.db.d_collection)))
Ejemplo n.º 28
0
def add_admin():
    with app.app_context():
        db.create_all()
        user = Users(id='user',
                     name='Super User',
                     password=generate_password_hash('pass', method='sha256'),
                     admin_user=True)
        db.session.add(user)
        db.session.commit()
Ejemplo n.º 29
0
 def test_db_overwrite_service(self):
     with app.app_context():
         s_obj = self.mock.service()
         t_obj = self.mock.service()
         t_obj.providesCollectionPids = not s_obj.providesCollectionPids
         self.db.set_service(s_obj)
         self.db.set_service(t_obj)
         self.assertNotEqual(json.dumps(s_obj),
                             json.dumps(self.db.get_service()))
Ejemplo n.º 30
0
def send_async_email(email, subject, link):
    """Background task to send an email with Flask-Mail."""
    msg = Message(subject,
                  sender=app.config['MAIL_DEFAULT_SENDER'],
                  recipients=[email],
                  html=link)
    msg.body = "Your confirmation link is here: "
    with app.app_context():
        mail.send(msg)
Ejemplo n.º 31
0
 def _ts(self, audio_path):
     """线程内执行task
      第2步
     """
     if self.task_id is None:  # 没有任务模式
         self.send(audio_path=audio_path)
     else:  # 需要记录结果的任务模式
         self.send(audio_path=audio_path)
         print('_ts:111111111111')
         self.task_join()
         with app.app_context():  # 在新开辟的线程内新建app上下文
             print('_ts:222222222')
             # task = Task.query.get(self.task_id)
             # self.article.finishing_symbols()
             # task.status = True  # 更改任务状态
             # task.content = self.article.__repr__()  # 记录结果
             # task.commit()  # 提交
             db.mn.task.filter(id=self.task_id).update(status=2)  #表示转完了.
             #正常完成后清空redis
             taskRedis.delete(f'manu_xf_task-{self.task_id}')
Ejemplo n.º 32
0
def main():
    """Main entry point for script."""
    with app.app_context():
        db.metadata.create_all(db.engine)
        if User.query.all():
            print('A user already exists! Create another? (y/n):', )
            create = input()
            if create == 'n':
                return
        print('Enter name: ', )
        name = input()
        print('Enter email: ', )
        email = input()
        print('Enter login: '******'Password (again):')

        user = User(name=name, login=login, email=email,
                    password=generate_password_hash(password), admin=True)
        db.session.add(user)
        db.session.commit()
        print('User added.')
Ejemplo n.º 33
0
    shammu_post1.user_id = shammu.id
    db.session.add(shammu_post1)
    db.session.commit()

    #create comments
    share_t_post1_comment = Comment('Obvio que sim querido, anoes sao para todos!')
    share_t_post1_comment.user_id = bolovo.id
    share_t_post1_comment.post_id = share_t_post1.id
    db.session.add(share_t_post1_comment)
    db.session.commit()

    #create rules
    only_woman = Rule('gender', RuleOperands.OPERAND_EQUAL, 'female', 'str', shammu)
    shammu.rules.append(only_woman)
    db.session.add(only_woman)
    db.session.commit()

        #create rules
    only_male = Rule('gender', RuleOperands.OPERAND_EQUAL, 'male', 'str', shammu)
    share_c.rules.append(only_male)
    db.session.add(only_male)
    db.session.commit()



from run import app
from database import db

with app.app_context():
    create_data()