Esempio n. 1
0
    def test_sign_up(self):
        app.test_client().post('/', data={'email': '*****@*****.**'})

        users = session().query(User.email).all()
        eq_(users, [('*****@*****.**',)])

        self.visit('/')
        self.browser.fill('email', '*****@*****.**')
        self.browser.find_by_name('go').click()
        assert self.browser.is_text_present('Thanks'), 'rude!'

        users = session().query(User.email).all()
        eq_(users, [('*****@*****.**',), ('*****@*****.**',)])
Esempio n. 2
0
    def test_similar(self):
        ctx = app.test_request_context()
        ctx.push()

        from engines import content_engine

        #content_engine.train('sample-data.csv')
        #content_engine.train('result.csv')

        data = {'item': 56753, 'num': NUM_DATA}
        headers = [('Content-Type', 'application/json'),
                   ('X-API-TOKEN', current_app.config['API_TOKEN'])]
        json_data = json.dumps(data)
        json_data_length = len(json_data)
        headers.append(('Content-Length', str(json_data_length)))
        print json_data
        response = app.test_client().post('/predict',
                                          headers=headers,
                                          data=json_data)
        print response
        response = json.loads(response.data)
        #fp=open("data_test.csv",'r')
        #content = fp.read()
        #fp.close()
        #cdata = content.split('\n')
        #print response
        print "search:56753"
        num = 10
        if num > len(response):
            num = len(response)

        for i in range(0, num):
            print response[i][0], response[i][1]
Esempio n. 3
0
def aggregrate_client():
    """Flask application fixture that includes b64data"""

    app.testing = True
    with open("../ext/input.csv", "rb") as f:
        data = base64.b64encode(f.read())
    return app.test_client(), data
Esempio n. 4
0
def client():
    from web import app


    result = app.test_client()
    app.testing = True
    return result
Esempio n. 5
0
def export_all(tar_name):
    client_app = app.test_client()
    tar = tarfile.open(tar_name, "w")

    save_file(client_app, '/index')
    index_json = get_json(client_app, '/index')
    tar.add("index.html")

    for user in index_json['users']:
        print('start to export user {uid}'.format(uid=user['uid']))
        export_status(client_app, user['uid'])
        export_gossip(client_app, user['uid'])
        export_albums(client_app, user['uid'])
        export_blogs(client_app, user['uid'])
        add_to_tar(tar, '{uid}'.format(uid=user['uid']))

    add_to_tar(tar, 'album')
    add_to_tar(tar, 'photo')
    add_to_tar(tar, 'blog')

    add_to_tar(tar, 'static')
    tar.close()

    os.remove('index.html')
    for user in index_json['users']:
        shutil.rmtree(str(user['uid']))
    shutil.rmtree('album', ignore_errors=True)
    shutil.rmtree('photo', ignore_errors=True)
    shutil.rmtree('blog', ignore_errors=True)
Esempio n. 6
0
def client():
    """Create client for testing
    Statements before 'yield client' set-up client
    Statements after 'yield client' tear-down client"""
    client = app.test_client()

    yield client
Esempio n. 7
0
def test_login_required_when_logged_out():
    with app.test_client() as client:
        response = client.get('/add')
        assert response.status_code == 302

        response = client.get('/user/lionel_messi')
        assert response.status_code == 302
Esempio n. 8
0
def test_createUser():
    payload = "{\n\"id\":223446,\"firstName\":\"Herman\",\"lastName\":\"Chen\",\"nationality\":\"Singapore\"\n}"
    headers = {'Content-Type': 'application/json'}
    response = app.test_client().post('/', headers=headers, data=payload)
    print(response.data)
    assert response.status_code == 200
    assert response.data == b'{"id": 223446, "firstName": "Herman", "lastName": "Chen", "nationality": "Singapore"}'
Esempio n. 9
0
 def setUpClass(cls):
     os.environ['TESTING'] = 'true'
     from web import app, db
     cls.app = app.test_client()
     db.create_all()
     # add default user
     db.session.add(User(email='*****@*****.**', name='tests', password=pw_hash('password1234')))
     db.session.commit()
Esempio n. 10
0
 def setUp(self):
     logging.disable(logging.CRITICAL)
     app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///:memory:"
     app.config['TESTING'] = True
     app.app_context().push()
     self.app = app.test_client()
     with app.app_context():
         setup_database(app)
Esempio n. 11
0
def client():
    db_fd, app.config['DATABASE'] = tempfile.mkstemp()
    app.config['TESTING'] = True
    client = app.test_client()

    yield client

    os.close(db_fd)
    os.unlink(app.config['DATABASE'])
Esempio n. 12
0
 def test_web_title_query(self):
     with app.test_client() as c:
         resp = c.get('/api?title=Золотая+рыбка&amount=5&type=TI')
         total, books = opac.get_book_list({'ti': 'Золотая рыбка'},
                                           length=5)
         self.assertGreater(len(resp.data), 0)
         self.assertEqual(total,
                          parse_response(resp)['amount_of_books_for_query'])
         self.assertEqual(books, parse_response(resp)['books'])
Esempio n. 13
0
def client():
    db_fd, app.config['DATABASE'] = tempfile.mkstemp()
    app.config['FLASK_ENV'] = 'test'
    client = app.test_client()

    yield client

    os.close(db_fd)
    os.unlink(app.config['DATABASE'])
Esempio n. 14
0
 def test_new_cat(self):
     with app.test_client() as c:
         with c.session_transaction() as sess:
             sess['user'] = 1
         rv = c.post('/ajax/category/new', data=dict(name='New note'))
         assert b'New note' in rv.data
         import json
         cid = json.loads(rv.data)['id']
         rv = c.delete('/ajax/category/' + str(cid))
         assert b'true' in rv.data
Esempio n. 15
0
    def setUp(self):
        app.config['TESTING'] = True
        app.config['WTF_CSRF_ENABLED'] = False
        app.config['DEBUG'] = False
        app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////' + \
            os.path.join(app.config['BASEDIR'], TEST_DB)
        self.app = app.test_client()
        db.drop_all()
        db.create_all()

        self.assertEquals(app.debug, False)
Esempio n. 16
0
 def setUp(self):
     app.config['TESTING'] = True
     app.config['CSRF_ENABLED'] = False
     app.config['DEBUG'] = False
     app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(
         BASE_DIR, TEST_DB)
     self.app = app.test_client()
     db.create_all()
     self.user = User('TestUser')
     self.user.save('testpassword')
     self.video = Video('TestVideo')
     self.video.save(hash='Teststring', user=self.user)
Esempio n. 17
0
def test_login_required_when_logged_in():
    with app.test_client() as client:
        username = '******'
        password = '******'
        data = dict(username=username, password=password)
        response = client.post('/login', data=data)
        assert response.status_code == 302
        assert 'tanhakate' in response.headers['Location']

        #response = client.get('/add')
        #assert response.status_code == 200

        response = client.get('/user/tanhakate')  #valid username
        assert response.status_code == 200
Esempio n. 18
0
def client():
    app.config.from_object(Config)
    app.config.TESTING = True
    client = app.test_client()

    db = DB(app.config['PG_CONNECTION_URI'])
    db.conn.autocommit = True

    cursor = db.conn.cursor()
    cursor.execute(open("tests/db-test.sql", "r").read())
    cursor.close()

    db.close()

    yield client
Esempio n. 19
0
    def setUp(self):
        logging.disable(logging.CRITICAL)

        app.config["TESTING"] = True
        app.app_context().push()
        self.app = app.test_client()

        db_session.commit()
        Base.metadata.drop_all(engine)
        db_session.commit()
        Base.metadata.create_all(engine)
        db_session.commit()

        logging.info("Setting up database")
        setup_database(app)
 def setUp(self):
     app.config['TESTING'] = True
     app.config['CSRF_ENABLED'] = False
     app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + TEST_DB_PATH
     self.client = app.test_client()
     db.create_all()
     self.user = User('TestUser')
     self.user.save('testpassword')
     self.video = Video('TestVideo')
     self.video.save(hash='Teststring', user=self.user)
     self.video_id = self.video.id
     self.comment = Comment('Text', self.video.id, self.user.id)
     self.comment.save()
     self.anonuser = Device()
     self.anonuser2 = Device()
     self.room = Room('roomname', self.anonuser.id)
     self.room.save(self.video.id)
Esempio n. 21
0
 def setUp(self):
     from config import Config
     app.config.from_object(Config)
     app.config['TESTING'] = True
     app.config[
         'SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:qwerty@localhost/lab_notes_test'
     app.config['CSRF_ENABLED'] = False
     self.app = app.test_client()
     from models import User
     user = User()
     user.id = 1
     user.name = 'Test'
     user.login = '******'
     from _md5 import md5
     user.password = md5('qwe'.encode('utf-8')).hexdigest()
     db.session.add(user)
     db.session.flush()
     db.session.commit()
Esempio n. 22
0
    def test_similar(self):
        ctx = app.test_request_context()
        ctx.push()

        from engine import content_engine

        content_engine.train('sample-data.csv')

        data = {'item': 1, 'num': 10}
        headers = [('Content-Type', 'application/json'), ('X-API-TOKEN', current_app.config['API_TOKEN'])]
        json_data = json.dumps(data)
        json_data_length = len(json_data)
        headers.append(('Content-Length', str(json_data_length)))

        response = app.test_client().post('/score', headers=headers, data=json_data)
        response = json.loads(response.data)
        self.assertEqual(len(response), 10)
        self.assertEqual(response[0][0], "19")
Esempio n. 23
0
def client():
    '''
	This is an extremely simplified configuration for testing. I spent some hours trying to learn how 
	this can be improved:
		1. Most configurations first rely on having a create_app function for the main app while we don't currently have one. 
		2. After applying that, it seems useful to separate the client creation from the db setup, and then define a session-level setting that allows each test to run with a separate db whereas it is not the case with this configuration. We basically use our app but change its config to use a temporary db.
		3. Also, using a temp file as it was before did not work for me, it kept using our original db or throw errors. 
		4. I am not sure the teardown is clean here, since os.unlink(app.config['SQL..']) did not work when this is set to theh in-memory DB. So that might be another point for importvement. 
		
	For now I proceeded with creating some tests until someone else gets to have a look or I manage to learn a bit more.
	'''

    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
    app.config['TESTING'] = True
    app.config['SECRET_KEY'] = 'test_key'

    with app.test_client() as client:
        db.create_all()
        yield client
        db.drop_all()
Esempio n. 24
0
    def test_similar(self,item,NUM_DATA):
        ctx = app.test_request_context()
        ctx.push()
	

        from engines import content_engine

        #content_engine.train('sample-data.csv')
       	#content_engine.train('result.csv')
	items=item.split('-')
	result=[]
	k={}
	for i in items:
       		data = {'item': i, 'num': int(NUM_DATA)}
        	headers = [('Content-Type', 'application/json'), ('X-API-TOKEN', current_app.config['API_TOKEN'])]
        	json_data = json.dumps(data)
        	json_data_length = len(json_data)
        	headers.append(('Content-Length', str(json_data_length)))
#	print json_data
        	response = app.test_client().post('/predict', headers=headers, data=json_data)
#		print response
        	response = json.loads(response.data)
		result = result+response
	for i,j in result:  
		if i not in k.keys():  
	            	k[i]=1
        	else:  
		        k[i]=k[i]+1
	s=sorted(k.items(),key=lambda item:item[1],reverse=True)
	#print s
	result=[]
	num=0
	for key in s:
		if key in items:
			continue
		result.append(int(key[0]))
		num = num +1
		if (num > int(NUM_DATA)):
			break
	print result
	return result
Esempio n. 25
0
 def setUp(self):
     self.app = app.test_client()
     app.config['TESTING'] = True
Esempio n. 26
0
from web import app
from unittest import mock
from base64 import b64encode
# from pytest import

client = app.test_client()


def test_homepage():
    resp = client.get("/")
    assert resp.status_code == 200


auth = {"authorization": {"password": "******"}}


def test_login_ok():
    cred = b64encode(b"test_user:password").decode('utf-8')
    headers = {"Authorization": f"Basic {cred}"}
    resp = client.get("/login", headers=headers)
    assert resp.status_code == 200


def test_login_failed():
    cred = b64encode(b"test_user:wrong_password").decode('utf-8')
    headers = {"Authorization": f"Basic {cred}"}
    resp = client.get("/login", headers=headers)
    assert resp.status_code == 401


@mock.patch('web.routes.jwt')
def client():
    """Generic Flask application fixture"""

    app.testing = True
    return app.test_client()
Esempio n. 28
0
 def setUp(self):
     app.config['TESTING'] = True
     app.config['DEBUG'] = False
     self.client = app.test_client()
     self.assertEqual(app.debug, False)
Esempio n. 29
0
def test_client():
    from web import app
    app.config['TESTING'] = True
    return app.test_client()
Esempio n. 30
0
def client():
    db.drop_all()
    db.create_all()
    client = app.test_client()

    yield client
Esempio n. 31
0
def test_getStudent():
    payload = "{\n\"id\":223446\n}"
    headers = {'Content-Type': 'application/json'}
    response = app.test_client().get('/', headers=headers, data=payload)
    assert response.status_code == 404
    assert response.data == b'{"status": "Not Found"}'
Esempio n. 32
0
def test_deleteStudent():
    payload = "{\n\"id\":223446\n}"
    headers = {'Content-Type': 'application/json'}
    response = app.test_client().delete('/', headers=headers, data=payload)
    assert response.status_code == 200
    assert response.data == b'{"status": "User removed"}'
Esempio n. 33
0
def test_getStudent():
    payload = "{\n\"id\":223446\n}"
    headers = {'Content-Type': 'application/json'}
    response = app.test_client().get('/', headers=headers, data=payload)
    assert response.status_code == 200
    assert response.data == b'{"id": 223446, "firstName": "Herman", "lastName": "Chen", "nationality": "Singapore"}'
Esempio n. 34
0
from web import app
from mock import patch
from nose.tools import assert_equals


client = app.test_client()


get_urls = [
    "/photos",
    "/photos/1",
    "/photos/1/sizes",
    "/photos/1/favorites",
    "/photos/1/comments",
    "/photos/1/people",
    "/photos/1/suggestions",
    "/photos/1/notes",
    "/photos/1/galleries",
    "/activity",
    "/favorites",
    "/photosets",
    "/photosets/1",
    "/photosets/1/comments",
    "/galleries",
    "/galleries/1",
    "/galleries/1/photos",
    "/galleries/1/photos/1",
    "/tags",
    "/blogs",
    "/blogs/1",
    "/collections",
Esempio n. 35
0
def client():
    result = app.test_client()
    app.testing = True
    return result
Esempio n. 36
0
 def setUp(self):
     self.connectToDB(dbHost=os.getenv('DB_PORT_27017_TCP_ADDR', '192.168.99.100'))
     self.app = app.test_client(self)
     self.cleanDB()