Esempio n. 1
0
    def test_endpoints__success(self):
        with app.test_client() as c:
            response = c.post('/calculate', json={'first_number': 3.5, 'second_number': 1.59})
            task_id = response.data.decode()

        with app.test_client() as c:
            response = c.get('/callback/{}'.format(task_id))
            self.assertEqual(float(response.data.decode()), 3.5 * 1.59)
Esempio n. 2
0
    def test_endpoints__failure(self):
        with app.test_client() as c:
            response = c.post('/calculate', json={'first_number': "asd", 'second_number': 1.59})
            task_id = response.data.decode()

        with app.test_client() as c:
            response = c.get('/callback/{}'.format(task_id))
            with self.assertRaises(ValueError):
                # it will return error details, so converting to float will raise an error
                float(response.data.decode())
Esempio n. 3
0
 def setUp(self):
     """Set up a blank temp database before each test."""
     basedir = os.path.abspath(os.path.dirname(__file__))
     app.config['TESTING'] = True
     app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, TEST_DB)
     self.app = app.test_client()
     db.create_all()
    def test_it_should_return_the_correct_phonenumber_when_user_is_successfully_created(
            self):
        try:
            if 'aws_region' in os.environ:
                os.environ.pop("aws_region")
            response = app.test_client().post('/v1/users',
                                              data=json.dumps({
                                                  "email":
                                                  "*****@*****.**",
                                                  "phone_number":
                                                  "233-323-2332",
                                                  "full_name":
                                                  "B Sokhi",
                                                  "password":
                                                  "******",
                                                  "metadata":
                                                  "age 34, female, phd"
                                              }),
                                              content_type='application/json')

            response_obj = json.loads(response.data.decode('utf8'))
            expected_value = "233-323-2332"
            real_value = response_obj['phone_number']

            nose.tools.assert_equal(
                expected_value, real_value,
                'it should have returned {} but returned {} instead'.format(
                    expected_value, real_value))

        except Exception as ex:
            print(ex)
            nose.tools.assert_false(True)
Esempio n. 5
0
 def setUp(self):
     print("inside setUp the Test")
     self.ctx = app.app_context()
     self.ctx.push()
     db.drop_all()  # just in case
     db.create_all()
     self.client = app.test_client()
Esempio n. 6
0
    def test_microservice(self):
        models = {
            'reading-comprehension': DemoModel(TEST_ARCHIVE_FILES['reading-comprehension'],
                                               'machine-comprehension',
                                               LIMITS['reading-comprehension'])
        }

        app = make_app(build_dir=self.TEST_DIR, models=models)
        app.testing = True


        client = app.test_client()

        # Should have only one model
        response = client.get("/models")
        data = json.loads(response.get_data())
        assert data["models"] == ["reading-comprehension"]

        # Should return results for that model
        response = client.post("/predict/reading-comprehension",
                               content_type="application/json",
                               data="""{"passage": "the super bowl was played in seattle",
                                        "question": "where was the super bowl played?"}""")
        assert response.status_code == 200
        results = json.loads(response.data)
        assert "best_span" in results

        # Other models should be unknown
        response = client.post("/predict/textual-entailment",
                               content_type="application/json",
                               data="""{"premise": "the super bowl was played in seattle",
                                        "hypothesis": "the super bowl was played in ohio"}""")
        assert response.status_code == 400
        data = response.get_data()
        assert b"unknown model" in data and b"textual-entailment" in data
Esempio n. 7
0
 def setUp(self):
     self.app = app.test_client()
     self.entry = json.dumps({"user_id": "007"})
     self.todo = json.dumps({"to-do": "Going to cinema with my friends"})
     self.existing_diary = self.app.post('/api/v1/entries',
                                         data=self.entry,
                                         content_type='application/json')
Esempio n. 8
0
    def setUp(self):
        # app.config['TESTING'] = True
        # app.config['WTF_CSRF_ENABLED'] = False
        app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(BASE_DIR, 'app.db')

        self.app = app.test_client()
        db.drop_all()
        db.create_all()
Esempio n. 9
0
 def setUp(self):
                                           # creates a test client
     app.config['TESTING'] = True
     app.config['WTF_CSRF_ENABLED'] = False
     app.config['DEBUG'] = False
     app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + \
         os.path.join(UPLOAD_FOLDER, TEST_DB)
     self.app = app.test_client()
Esempio n. 10
0
 def setUp(self):
     app.config['TESTING'] = True
     app.config['WTF_CSRF_ENABLED'] = False
     app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///testing.db'
     self.app = app.test_client()
     db.create_all()
     user1 = User(username="******", password="******")
     db.session.add(user1)
     db.session.commit()
Esempio n. 11
0
    def setUp(self):
        super().setUp()

        admin = User(username=Users.ADMIN['username'], email=Users.ADMIN['email'], admin=True)
        admin.set_password(Users.ADMIN['password'])

        db.session.add(admin)
        db.session.commit()
        self.client = app.test_client()
Esempio n. 12
0
 def test_post_incorrect_user_by_email(self):
     """
     Testing POST without all of the required data for successful login
     """
     with app.test_client() as client:
         sent = {'password': '******'}
         result = client.post('/auth',
                              data=json.dumps(sent),
                              content_type='application/json')
         self.assertFalse(result.json['login'])
Esempio n. 13
0
 def test_post_user_by_email(self):
     """
     Testing POST request to determine if login is successful.
     """
     with app.test_client() as client:
         sent = {'email': '*****@*****.**', 'password': '******'}
         result = client.post('/auth',
                              data=json.dumps(sent),
                              content_type='application/json')
         self.assertTrue(result.json['login'])
Esempio n. 14
0
    def setUp(self):
        super().setUp()

        admin = User(username=Users.ADMIN['username'],
                     email=Users.ADMIN['email'],
                     admin=True)
        admin.set_password(Users.ADMIN['password'])

        db.session.add(admin)
        db.session.commit()
        self.client = app.test_client()
    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.assertEqual(app.debug, False)
Esempio n. 16
0
    def setUp(self):

        app.config['TESTING'] = True
        app.config['WTF_CSRF_ENABLED'] = False
        app.config['DEBUG'] = False
        app.config[
            'SQLALCHEMY_DATABASE_URI'] = 'mysql://root:@localhost/testdb'
        self.app = app.test_client()
        db.drop_all()
        db.create_all()

        self.assertEqual(app.debug, False)
Esempio n. 17
0
def client():
    app = app.create_app()
    db_fd, app.config['DATABASE'] = tempfile.mkstemp()
    app.config['TESTING'] = True

    with app.test_client() as client:
        with app.app_context():
            app.init_db()
        yield client

    os.close(db_fd)
    os.unlink(app.config['DATABASE'])
Esempio n. 18
0
def client():
    db_fd, db_fname = tempfile.mkstemp()
    app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///" + db_fname
    app.config["TESTING"] = True

    db.create_all()
    _populate_db()

    yield app.test_client()

    db.session.remove()
    os.close(db_fd)
    os.unlink(db_fname)
Esempio n. 19
0
 def setUp(self):
     self.tester = app.test_client(self)
     self.login_data = {
         'email': '*****@*****.**',
         'password': '******'
     }
     self.category_data = {
         'category_name': 'Breakfast',
         'category_description': 'Awesome Breakfast'
     }
     self.registration_data = {
         'username': '******',
         'email': '*****@*****.**',
         'password': '******'
     }
     app.config.from_pyfile('testconf.cfg')
     db.create_all()
Esempio n. 20
0
def admin_client(request):
    try:
        setup_admin()
    except Exception as ex:
        # If running in dev mode, admin may already exist
        # So it's possibly okay if this fails.
        print(ex)

    administrator = app.test_client()
    administrator.get("/account/login")
    administrator.post('/account/login', data={
        'email': TEST_ADMIN.email,
        'password': TEST_ADMIN.password,
        '_csrf_token': list(session._csrf)[-1]
    }, follow_redirects=True)

    def admin_teardown():
        remove_admin()
    request.addfinalizer(admin_teardown)

    return administrator
Esempio n. 21
0
def logged_client(request):
    try:
        setup_user()
    except Exception as ex:
        # If running in dev mode, user may already exist
        # So it's possibly okay if this fails.
        print(ex)

    user_client = app.test_client()
    user_client.get("/account/login")
    user_client.post('/account/login', data={
        'email': TEST_USER.email,
        'password': TEST_USER.password,
        '_csrf_token': list(session._csrf)[-1]
    }, follow_redirects=True)

    def user_teardown():
        remove_user()
    request.addfinalizer(user_teardown)

    return user_client
Esempio n. 22
0
    def setUp(self):

        self.app = app.test_client()
        self.data = json.dumps({
            "username": "******",
            "email": "*****@*****.**",
            "password": "******",
            "confirm_password": "******"
        })
        self.existing_user = self.app.post('/api/v1/auth/signup',
                                           data=self.data,
                                           content_type='application/json')

        self.data2 = json.dumps({
            "username": "******",
            "email": "*****@*****.**",
            "password": "******",
            "confirm_password": "******"
        })
        self.existing_user = self.app.post('/api/v1/auth/signup',
                                           data=self.data2,
                                           content_type='application/json')
Esempio n. 23
0
    def test_routes_user_all_post_success(self):
        """
        Testing if register of new user is successful through the API, new registered user is then checked in the
        database to see if the names match.
        """
        with app.test_client() as client:
            # Send data as POST form to endpoint
            user = {
                'email': '*****@*****.**',
                # Converting byte hash to str for formatting as json
                'password': str(bcrypt.generate_password_hash('sammypwd'))
            }
            result = client.post('/user',
                                 data=json.dumps(user),
                                 content_type='application/json')
            # check result from server response.
            api_response = json.loads(result.data.decode())['response']

            self.assertEqual('Successfully Registered', api_response)
            # Testing if last object registered has the same name as the one just added to it.
            self.assertEqual(
                list(User.objects.all())[-1].email, '*****@*****.**')
Esempio n. 24
0
 def setUp(self):
     app.testing = True
     self.app = app.test_client()
     self.data = {
         "username": "******",
         "email": "*****@*****.**",
         "password": "******"
     }
     self.data2 = {
         "username": "******",
         "email": "*****@*****.**",
         "password": "******"
     }
     self.data3 = {
         "username": "******",
         "email": "*****@*****.**",
         "password": "******"
     }
     self.data4 = {
         "username": "******",
         "email": "*****@*****.**",
         "password": "******"
     }
     self.data5 = {
         "username": "******",
         "password": "******",
         "resetpassword": "******"
     }
     self.data6 = {
         "username": "******",
         "email": "*****@*****.**",
         "password": "******"
     }
     with app.app_context():
         # create all tables
         db.session.close()
         db.drop_all()
         db.create_all()
Esempio n. 25
0
    def test_incorrect_order(self):
        with app.test_client() as client:
            q = Queue(len(os.listdir("tests/invalid")))

            def send_request():
                order = q.get()
                data = json.dumps(order)
                result = client.post('order', json=data)
                self.assertEqual('400 BAD REQUEST', result.status)
                q.task_done()

            for _ in range(self.max_requests):
                t = Thread(target=send_request)
                t.daemon = True
                t.start()

            for entry in os.scandir("tests/invalid"):
                if entry.path.endswith(".json"):
                    with open(entry.path, "r") as incorrect_order:
                        order = json.loads(incorrect_order.read())
                        q.put(order)

            q.join()
Esempio n. 26
0
def client(app):
    return app.test_client()
Esempio n. 27
0
 def setUp(self):
     self.app = app.test_client()
     self.app.testing = True
Esempio n. 28
0
def test_when_server_starts_then_load_up_words(app):
    with app.test_client() as test_client:
        response = test_client.get('/words/aht')
        assert 200 == response.status_code
        response_string = response.get_data().decode()
        assert ['hat', 'at'] == json.loads(response_string)['words']
Esempio n. 29
0
 def test_update(self):
      tester = app.test_client(self)
      response = tester.get('/update')
      statuscode = response.status_code
      self.assertEqual(statuscode, 200)
      self.assertIn(b'Update', response.data)
Esempio n. 30
0
 def test_complaint(self):
      tester = app.test_client(self)
      response = tester.get('/complaint')
      statuscode = response.status_code
      self.assertEqual(statuscode, 200)
      self.assertIn(b'Lodge a compliant', response.data)
Esempio n. 31
0
 def test_service(self):
     tester = app.test_client(self)
     response = tester.get('/service')
     statuscode = response.status_code
     self.assertEqual(statuscode, 200)
     self.assertIn(b'Type of Service', response.data)
 def setUp(self):
     self.app = app.test_client()
     self.test_data_zip = str(open(os.path.join(os.path.dirname(__file__), 'data/BII-I-1.zip'), 'rb').read())
     self.test_data_json = open(os.path.join(os.path.dirname(__file__), 'data/BII-I-1.json'), 'rb').read()