def setUp(self):
        """Do at the beginning of every test"""
        # Get the Flask test client
        self.client = app.test_client()

        # Show Flask errors that happen during tests
        app.config['TESTING'] = True

        # Connect to test database
        connect_to_db(app, "postgresql:///testdb")

        # Create tables from model
        db.create_all()

        # Import different types of data from seed file
        seed.load_users()
        seed.load_groups()
        seed.load_usergroups()
        seed.load_patterns()
        seed.load_invites()
        
        # Reset auto incrementing primary keys to start after seed data
        seed.set_val_user_id()
        seed.set_val_group_id()
        seed.set_val_usergroup_id()
        seed.set_val_pattern_id()
        seed.set_val_invite_id()

        with self.client as c:
                with c.session_transaction() as sess:
                    sess['user_id'] = 1
                c.set_cookie('localhost', 'MYCOOKIE', 'cookie_value')
Example #2
0
    def setUp(self):
        """Setup to do before every test."""

        # Get the Flask test client
        self.client = app.test_client()
        app.jinja_env.undefined = StrictUndefined
        app.jinja_env.filters['prettify_preference'] = prettify_preference

        # Show Flask errors that happen during tests
        app.config['TESTING'] = True

        # Connect to test database
        connect_to_db(app, db_uri="postgresql:///testdb")

        # start with empty db
        db.drop_all()
        # Create tables and add sample data
        db.create_all()
        # create db records for yarns, users, baskets, basket_yarns,
        #                       projects, and patterns
        create_example_data()
        # create db records for preferences and user_preferences
        load_preferences("test_data/preference_data.txt")
        load_user_preferences("test_data/user_preference_data.txt")
        load_group_events("test_data/group-events.csv")
Example #3
0
    def test_login(self):
        """Checks that a user is in session after login with correct credentials."""

        sys.stdout.write('Testing login handler...')
        with app.test_client() as c:
            self.login(c)
            assert User.query.filter(User.username=='janet').one().id == 1
    def setUp(cls):
        """Do once before all tests in this class"""
        # Get the Flask test client
        cls.client = app.test_client()

        # Show Flask errors that happen during tests
        app.config['TESTING'] = True

        # Connect to test database
        connect_to_db(app, "postgresql:///testdb")

        # Create tables from model
        db.create_all()

        # Import different types of data from seed file
        seed.load_users()
        seed.load_groups()
        seed.load_usergroups()
        seed.load_patterns()
        seed.load_invites()
        
        seed.set_val_user_id()
        seed.set_val_group_id()
        seed.set_val_usergroup_id()
        seed.set_val_pattern_id()
        seed.set_val_invite_id()

        with cls.client as c:
                with c.session_transaction() as sess:
                    sess['user_id'] = 1
                c.set_cookie('localhost', 'MYCOOKIE', 'cookie_value')
Example #5
0
    def setUp(self):
        """Stuff to do before every test."""

        # Get the Flask test client
        self.client = app.test_client()

        # Connect to test database
        connect_to_db(app)

        # Create tables and add sample data
        db.create_all()
        _example_data()

        app.config['TESTING'] = True
        app.config['SECRET_KEY'] = 'Aisling'
        self.client = app.test_client()
Example #6
0
    def setUp(self):
        """Do before every test."""

        # Get the Flask test client
        self.client = app.test_client()

        # Show Flask errors that happen during tests
        app.config['TESTING'] = True

        # Connect to test database
        connect_to_db(app, "postgresql:///testdb")
        db.create_all()

        # Make mocks
        def _mock_get_yelp_search_results(term, location, category_filter, limit):
            """Mocks search results of Yelp API call for one restaurant."""

            search_results = {"businesses": [{"rating": 4.5, "rating_img_url": "https://s3-media2.fl.yelpcdn.com/assets/2/www/img/99493c12711e/ico/stars/v1/stars_4_half.png", "review_count": 547, "name": "Saru Sushi Bar", "rating_img_url_small": "https://s3-media2.fl.yelpcdn.com/assets/2/www/img/a5221e66bc70/ico/stars/v1/stars_small_4_half.png", "url": "http://www.yelp.com/biz/saru-sushi-bar-san-francisco?utm_campaign=yelp_api&utm_medium=api_v2_search&utm_source=6XuCRI2pZ5pIvcWc9SI3Yg", "image_url": "https://s3-media2.fl.yelpcdn.com/bphoto/5-ugy01zjSvudVsfdhmCsA/ms.jpg", "display_phone": "+1-415-400-4510", "id": "saru-sushi-bar-san-francisco", "location": {"city": "San Francisco", "postal_code": "94114", "country_code": "US", "address": ["3856 24th St"], "coordinate": {"latitude": 37.751706, "longitude": -122.4288283}, "state_code": "CA"}}]}
            return search_results

        def _mock_is_open_now_true(keyword, location):
            """Mocks Google Places API call to return True for current open status."""

            return True

        self._old_is_open_now = process_results.is_open_now
        process_results.is_open_now = _mock_is_open_now_true

        self.old_get_yelp_search_results = server.yelp.search_query
        server.yelp.search_query = _mock_get_yelp_search_results
Example #7
0
    def setUp(self):
        """Stuff to do before every test."""

        # Get the Flask test client
        self.client = app.test_client()

        # Mock session

        # Connect to temporary database
        connect_to_db(app, "sqlite:///")

        # Create tables and add sample data
        db.create_all()
        sample_data()


        def _mock_grab_image_dimensions(filename):
            return (920, 764)

        self._old_grab_image_dimensions = server.grab_image_dimensions
        server.grab_image_dimensions = _mock_grab_image_dimensions

        def _mock_generate_thumb(filename, crop_thumb):
            return None

        self._old_generate_thumb = server.generate_thumb
        server.generate_thumb = _mock_generate_thumb
Example #8
0
    def test_homepage(self):
        self.client = app.test_client()
        result = self.client.get("/")
        print dir(result) #### status_code, content_type=HTML, data

        self.asserIn("here", result.data)
        self.assertEqual(result.status_code,200)
    def setUp(self):
        # Get the Flask test client
        self.client = app.test_client()

        # Show Flask errors that happen during tests
        app.config['TESTING'] = True

        # Connect to test database
        connect_to_db(app, "postgresql:///testdb")

        # Create tables from model
        db.create_all()

        # Import different types of data from seed file
        seed.load_users()
        seed.load_groups()
        seed.load_usergroups()
        seed.load_patterns()
        seed.load_invites()
        
        # Reset auto incrementing primary keys to start after seed data
        seed.set_val_user_id()
        seed.set_val_group_id()
        seed.set_val_usergroup_id()
        seed.set_val_pattern_id()
        seed.set_val_invite_id()
 def setUp(self):
     app.config['TESTING'] = True
     app.config['CSRF_ENABLED'] = False
     app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(app.root_path, 'test.db')
     self.app = app.test_client()
     server.clean_db()
     db.create_all()
Example #11
0
    def setUp(self):
        self.client = app.test_client()
        app.config['TESTING'] = True
        app.config['SECRET_KEY'] = 'key'

        # Connect to test database
        connect_to_db(app, "postgresql:///testdb")
Example #12
0
 def setUp(self):
 	"""Set up a blank temp database before each test"""
     app.config['TESTING'] = True
     app.config['CSRF_ENABLED'] = False
     app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, TEST_DB)
     self.app = app.test_client()
     db.create_all()
Example #13
0
    def setUp(self):
        """Setup to do before every test."""

        # Get the Flask test client
        self.client = app.test_client()

        # secret key to allow sessions to be used
        app.config['SECRET_KEY'] = 'sekrit!'

        # Show Flask errors that happen during tests
        app.config['TESTING'] = True

        # Connect to test database
        connect_to_db(app, db_uri="postgresql:///testdb")

        # Create tables and add sample data
        db.create_all()
        # create db records for yarns, users, baskets, basket_yarns,
        #                       projects, and patterns
        create_example_data()
        # create db records for preferences and user_preferences
        load_preferences("test_data/preference_data.txt")
        load_user_preferences("test_data/user_preference_data.txt")

        with self.client as c:
                with c.session_transaction() as session:
                    session['username'] = '******'
Example #14
0
    def test_login(self):
        """Checks that a user is in session after login with correct credentials."""

        sys.stdout.write('Testing login handler...')
        with app.test_client() as c:
            self.login(c)
            assert flask.session['email'] == "*****@*****.**"
Example #15
0
    def setUp(self):
        print "\n\n\n\n (2) DOING A SEARCH TEST \n\n\n\n"
        self.client = app.test_client()
        app.config['TESTING'] = True
        postgrespassword = os.environ['POSTGRES_PASSWORD']
        db_uri = 'postgresql://' + postgrespassword + '/test'
        connect_to_db(app, db_uri)

        db.create_all()

        load_regions()
        load_users()
        load_bestuses()
        load_categories()
        load_brands()
        load_products()
        load_tents()
        load_filltypes()
        load_gendertypes()
        load_sleepingbags()
        load_padtypes()
        load_sleepingpads()
        load_ratings()
        load_histories()
        load_test_postalcodes()
Example #16
0
 def test_Classifier_data(self):
     print 'Test for proper csv saving'
     tester = app.test_client(self)
     fingers_data = [
         [0,1,2,3,4],
         [1,2,3,4,5],
         [2,3,4,5,6],
         [3,4,5,6,7]
     ]
     response = tester.post('/data', data=dict(
         exercise = 0,
         fingers = fingers_data, 
         time = 666,
         success = 0,
         pain = 1
         ), follow_redirects=True);
     f = open('classificationData.csv' ,'r')
     reader = csv.reader(f,delimiter=',', quotechar='|')
     header = reader.next()
     self.assertEqual(header[0], 'finger1')
     firstRow = reader.next()
     self.assertEqual(int(firstRow[0]), 0)
 
     self.assertEqual(int(firstRow[5]), 1)
     os.remove('classificationData.csv')
     assert json.loads(response.data)
Example #17
0
    def setUp(self):
        self.client = app.test_client()
        app.config["TESTING"] = True
        app.config["SECRET_KEY"] = "key"

        connect_to_db(app, db_uri="postgresql:///testdb")

        db.create_all()
Example #18
0
    def setUp(self):
        self.client = app.test_client()
        app.config["TESTING"] = True
        app.config["SECRET_KEY"] = "key"

        with self.client.session_transaction() as sess:
            sess["user_id"] = 1
            sess["username"] = "******"
Example #19
0
 def test_get_anno(self):
     # sends HTTP GET request to the application
     # on the specified path
     tester = app.test_client(self)
      
     result = tester.get('/annotations/api/v1.0/annos', content_type='application/ld+json') 
     # assert the status code of the response
     self.assertEqual(result.status_code, 200)
Example #20
0
    def setUp(self):
        self.client = app.test_client()
        app.config['TESTING'] = True

        connect_to_db(app, "postgresql:///testdb")

        db.create_all()
        example_data_high_scores()
	def setUp(self):
		"""Stuff to do before every test."""
		self.client = app.test_client()
		app.config['TESTING'] = True


		self.test_YP = YumPossibilities(37.773972, -122.431297, 'brunch')
		server.call_yelp = self._mock_call_yelp
Example #22
0
    def setUp(self):
        """Set up app, session key, and fake client."""

        app.config['TESTING'] = True
        self.client = app.test_client()

        connect_to_db(app, 'postgresql:///testdb')
        db.create_all()
Example #23
0
    def setUp(self):
        self.client = app.test_client()
        app.config['TESTING'] = True

        def _mock_get_img_url(soup):
            return "http://cdn3.minimalistbaker.com/wp-content/uploads/2016/06/Cauliflower-Rice-Stuffed-Pepper-SQUARE.jpg"

        webscrape_details.get_img_url = _mock_get_img_url
def test_get_existing_user():
    client = app.test_client()
    response = client.get("/api/v1/users/3")
    response_contents = json.loads(next(response.response).decode("utf-8"))
    assert response.status_code == 200
    assert response.headers["Content-Type"] == "application/json"
    assert response_contents["_id"] == "3"
    assert response_contents["name"] == "John Doe"
Example #25
0
	def setUp(self):
		app.config.from_object('config.TestingConfig')
		self.client = app.test_client()

		with app.app_context():
			init_app()
			user_datastore.create_user(email='test', password=encrypt_password('test'))
			db.session.commit()
 def setUp(self):
     """before every test"""
     
     self.client = app.test_client()
     app.config['TESTING'] = True
     connect_to_db(app, 'postgresql:///testsubreddits')
     db.create_all()
     make_test_data()
Example #27
0
    def setUp(self):
        """Stuff to do before every test."""

        # Get the Flask test client
        self.client = app.test_client()

        # Show Flask errors that happen during tests
        app.config['TESTING'] = True
Example #28
0
 def setUp(self):
     self.client = app.test_client()
     app.config['TESTING'] = True
     app.config['SECRET_KEY'] = 'BalloonicornSmash'
     # Connect to the database
     connect_to_db(app, db_uri=travis_db_uri)
     # Reset the world so we start with clean data
     seed_force(app)
 def setUp(self):
     self.app = app.test_client()
     app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///'
     app.config['TESTING'] = True
     app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
     db.app = app
     db.init_app(app)
     db.create_all()
Example #30
0
    def setUp(self):
        """Stuff to do before every test."""

        self.client = app.test_client()
        app.config['TESTING'] = True
        app.config['SECRET_KEY'] = "JMD"
        connect_to_db(app, "postgresql:///testdb")
        db.create_all()
        example_data()
Example #31
0
    def setUp(self):
        """Stuff to do before every test."""

        # Get the Flask test client
        self.client = app.test_client()

        # Show Flask errors that happen during tests
        app.config['TESTING'] = True

        # Connect to test database
        connect_to_db(app, "postgresql:///testdb")

        # Create tables and add sample data
        db.create_all()
        load_users()

        with self.client as c:
            with c.session_transaction() as sess:
                sess['user_id'] = 1
Example #32
0
 def setUp(self):
     with app.test_client() as c:
         self.uuids1 = []
         self.uuids2 = []
         c.set_cookie("localhost", "access_token_cookie", TOKEN_USER)
         for i in range(0, 2):
             response = c.post(
                 "/organizations",
                 headers={"x-csrf-token": TOKEN_USER_CSRF},
                 json={"name": get_random_name()},
             )
             self.uuids1.append(response.json["uuid"])
         c.set_cookie("localhost", "access_token_cookie", TOKEN_USER2)
         response = c.post(
             "/organizations",
             headers={"x-csrf-token": TOKEN_USER2_CSRF},
             json={"name": get_random_name()},
         )
         self.uuids2.append(response.json["uuid"])
Example #33
0
    def setUp(self):
        """Before every test"""

        app.config['TESTING'] = True
        self.client = app.test_client()

        # Connect to test database
        connect_to_db(app, "postgresql:///testdb")

        # Create tables and add sample data
        db.create_all()
        example_data()

        with self.client as c:
            with c.session_transaction() as sess:
                sess['user_id'] = 1

        # Make mock
        def _mock_recipe_search(search_name, recipe_id):
            """ Mocks info returned from Spoonacular API. """

            example_search = fake_api_json.recipe_search('pasta', 1)

            return example_search

        def _mock_summary_info(recipe_id):
            """ Mocks info returned from Spoonacular API. """

            example_summary = fake_api_json.summary_info('548180')

            return example_summary

        def _mock_recipe_info(recipe_id):
            """ Mocks info returned from Spoonacular API. """

            example_info = fake_api_json.recipe_info('548180')

            return example_info

        # Attaches mocks calls to app's real calls
        api_calls.recipe_search = _mock_recipe_search
        api_calls.summary_info = _mock_summary_info
        api_calls.recipe_info = _mock_recipe_info
Example #34
0
 def test_list_fields(self, mock_get_uri):
     with app.test_client() as c:
         c.set_cookie("localhost", "access_token_cookie", TOKEN_USER)
         response = c.get(
             "/printers?fields=webcam,status,job",
             headers={"x-csrf-token": TOKEN_USER_CSRF},
         )
         self.assertEqual(response.status_code, 200)
         # coming from db fixtures
         self.assertTrue("items" in response.json)
         self.assertTrue(len(response.json["items"]) >= 2)
         self.assertTrue("client" in response.json["items"][0])
         self.assertTrue("webcam" in response.json["items"][0])
         self.assertTrue("status" in response.json["items"][0])
         self.assertTrue("job" in response.json["items"][0])
         self.assertTrue("client" in response.json["items"][1])
         self.assertTrue("webcam" in response.json["items"][1])
         self.assertTrue("status" in response.json["items"][1])
         self.assertTrue("job" in response.json["items"][1])
Example #35
0
 def test_delete(self, mock_get_uri, mock_avahi):
     with app.test_client() as c:
         c.set_cookie("localhost", "access_token_cookie", TOKEN_ADMIN)
         ip = "192.168.%s" % ".".join(
             [str(random.randint(0, 255)) for _ in range(2)])
         response = c.post(
             "/printers",
             headers={"x-csrf-token": TOKEN_ADMIN_CSRF},
             json={
                 "ip": ip,
                 "name": "random-test-printer-name"
             },
         )
         self.assertEqual(response.status_code, 201)
         response = c.delete(
             "/printers/%s" % response.json["uuid"],
             headers={"x-csrf-token": TOKEN_ADMIN_CSRF},
         )
         self.assertEqual(response.status_code, 204)
Example #36
0
 def test_good_booking(self):
     # Create a test client using the Flask application configured for testing
     with app.test_client() as test_client:
         club_name = 'Simply Lift TEST'
         club_balance_before = [
             int(club['points']) for club in clubs
             if club['name'] == club_name
         ][0]
         response = test_client.post('/purchasePlaces',
                                     data=dict(
                                         competition='TEST Competitiion',
                                         club=club_name,
                                         places=2),
                                     follow_redirects=True)
         assert response.status_code == 200
         # check if the club current balance have changed
         assert str(club_balance_before -
                    int(request.form['places']) * 3) in str(response.data)
         assert b"Great-booking complete!" in response.data
Example #37
0
    def setUp(self):
        """Setting up tests for pages where user is logged in"""

        self.client = app.test_client()
        app.config['TESTING'] = True  # shows debugging output
        connect_to_db(app, "postgresql:///testdb"
                      )  # work on this postg understanding and db test
        app.config['SECRET_KEY'] = 'key'

        with self.client as c:
            with c.session_transaction() as sess:
                sess['user_name'] = 'Brian'
                sess['user_id'] = 1
                sess['hometown'] = 2
                sess['hometown_name'] = 'Selby'

        #create tables and ad sample data
        db.create_all()
        example_data()
Example #38
0
    def setUp(self):
        """Stuff to do before every test."""

        app.config['TESTING'] = True
        app.config['SECRET_KEY'] = 'ABC'
        self.client = app.test_client()

        with self.client as c:
            with c.session_transaction() as sess:
                sess['current_user'] = "******"

        # Connect to test database
        connect_to_db(app, "postgresql:///testdb")

        # Create tables and add sample data

        db.drop_all()
        db.create_all()
        example_data()
Example #39
0
    def setUp(self):
        """Stuff to do before every test."""

        app.config['TESTING'] = True
        app.config['SECRET_KEY'] = 'key'
        self.client = app.test_client()

        with self.client as c:
            with c.session_transaction() as sess:
                sess['user_id'] = 1

        connect_to_db(app, "postgresql:///testdb")

        # Create tables and add sample data
        db.create_all()
        # import pdb
        # pdb.set_trace()

        example_data()
Example #40
0
 def test_list(self):
     with app.test_client() as c:
         c.set_cookie("localhost", "access_token_cookie", TOKEN_USER)
         response = c.get("/gcodes", headers={"x-csrf-token": TOKEN_USER_CSRF})
         self.assertEqual(response.status_code, 200)
         self.assertTrue("items" in response.json)
         if len(response.json["items"]) < 200:
             self.assertTrue("next" not in response.json)
         self.assertTrue(len(response.json["items"]) >= 2)
         self.assertTrue("id" in response.json["items"][0])
         self.assertTrue("user_uuid" in response.json["items"][0])
         self.assertTrue("username" in response.json["items"][0])
         self.assertTrue("path" in response.json["items"][0])
         self.assertTrue("display" in response.json["items"][0])
         self.assertTrue("absolute_path" in response.json["items"][0])
         self.assertTrue("uploaded" in response.json["items"][0])
         self.assertTrue("size" in response.json["items"][0])
         self.assertTrue("data" in response.json["items"][0])
         self.assertTrue(response.json["items"][0]["username"] is not None)
    def setUp(self):
        """Necessary before every test. Configures the app,
        creates client, connects to test database, creates
        the tables, and seeds the test database."""

        # Get the Flask test client
        app.config['TESTING'] = True
        app.config['SECRET_KEY'] = 'ABC'
        self.client = app.test_client()

        # Connect to test database
        connect_to_db(app, uri='postgres:///testdb')

        # Create tables and add sample data
        example_data()

        with self.client as c:
            with c.session_transaction() as sess:
                sess['user'] = '******'
Example #42
0
    def setUp(self):
        self.client = app.test_client()
        app.config['TESTING'] = True

        connect_to_db(app, "postgresql:///testdb")

        db.create_all()
        example_data()

        with self.client as c:
            with c.session_transaction() as sess:
                sess['username'] = '******'

        self.client.post('/login',
                         data={
                             'username': '******',
                             'password': '******'
                         },
                         follow_redirects=True)
Example #43
0
    def setUp(self):
        """Stuff to do before every test."""

        # Get the Flask test client
        self.client = app.test_client()

        # Show Flask errors that happen during tests
        app.config['TESTING'] = True

        with self.client as c:
            with c.session_transaction() as sess:
                sess['user_id'] = 1
       
        # Connect to test database
        connect_to_db(app, "testdb") #create testdb based on model.py

        # # Create tables and add sample data
        db.create_all()
        example_data()
Example #44
0
    def setUp(self):
        """Stuff to do before every test."""

        # Get the Flask test client
        self.client = app.test_client()

        #Shows Flask errors that happen during tests
        app.config['TESTING'] = True

        #To test sessions we need to set Secret key
        app.config['SECRET_KEY'] = 'key'

        # Connect to test database
        connect_to_db(app, "postgresql:///testdb")

        # Create tables and add sample data
        db.create_all()
        users()
        reviews()
Example #45
0
    def setUp(self):
        """Stuff to do before every test."""

        # Get the Flask test client
        self.client = app.test_client()
        app.config['TESTING'] = True
        app.config['SECRET_KEY'] = 'key'

        # Connect to test database
        connect_to_db(app, "postgresql:///testdb")

        # Create tables and add sample data
        db.create_all()
        populate_example_data()

        with self.client as c:
            with c.session_transaction() as sess:
                sess['user_id'] = 1
                sess['name'] = "First1"
Example #46
0
    def setUp(self):
        """Setup for database function testing."""

        # Get the Flask test client.
        self.client = app.test_client()
        app.config["TESTING"] = True
        app.config["SECRET_KEY"] = "key"
        app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False

        with self.client as c:
            with c.session_transaction() as sess:
                sess["dietitian_id"] = 1

        # Connect to the test database.
        connect_to_db(app, db_uri="postgresql:///testnourish")

        # Create the tables and add the sample data.
        db.create_all()
        load_test_data()
Example #47
0
 def test_send_email_with_reset_link(self, mock_send_mail):
     with app.test_client() as c:
         email = get_random_email()
         c.post("/users/me", json={"email": email})
         user = users.get_by_email(email)
         users.update_user(uuid=user["uuid"], activated=datetime.now())
         local_users.add_local_user(user_uuid=user["uuid"],
                                    pwd_hash="aaa",
                                    force_pwd_change=False)
         response = c.post("/users/me/request-password-reset",
                           json={"email": email})
         self.assertEqual(response.status_code, 202)
         self.assertEqual(mock_send_mail.call_count, 2)
         args = mock_send_mail.call_args_list
         self.assertEqual(args[1][0][0][0], email)
         self.assertEqual(args[1][0][1], "PASSWORD_RESET_LINK")
         self.assertTrue(args[1][0][2]["pwd_reset_key"] is not None)
         self.assertTrue(args[1][0][2]["pwd_reset_key_expires"] is not None)
         self.assertEqual(args[1][0][2]["email"], email)
Example #48
0
    def setUp(self):
        """Prepare for each test before execution."""

        self.app = app.test_client()
        app.config['TESTING'] = True
        app.config['SECRET_KEY'] = 'key'

        connect_to_db(app, 'postgresql:///testdb')

        db.create_all()
        load_users()
        load_activities()
        load_sessions()
        load_records()

        with self.app as c:
            with c.session_transaction() as sess:
                sess['user_id'] = 2
                sess['sess_id'] = 40
Example #49
0
 def test_delete(self):
     gcode_uuid = gcodes.add_gcode(
         uuid=guid.uuid4(),
         path="delete-ab/c",
         filename="delete-gcode-specific-file1",
         display="file-display",
         absolute_path="/ab/a/b/c",
         size=123,
         user_uuid=UUID_USER,
         organization_uuid=UUID_ORG,
     )
     printjobs.add_printjob(
         uuid=guid.uuid4(),
         gcode_uuid=gcode_uuid,
         gcode_data={"uuid": gcode_uuid},
         printer_uuid="20e91c14-c3e4-4fe9-a066-e69d53324a20",
         printer_data={"host": "172.16.236.11:8080"},
         organization_uuid=UUID_ORG,
     )
     printjobs.add_printjob(
         uuid=guid.uuid4(),
         gcode_uuid=gcode_uuid,
         gcode_data={"uuid": gcode_uuid},
         printer_uuid="20e91c14-c3e4-4fe9-a066-e69d53324a20",
         printer_data={"host": "172.16.236.11:8080"},
         organization_uuid=UUID_ORG,
     )
     with app.test_client() as c:
         c.set_cookie("localhost", "access_token_cookie", TOKEN_USER)
         response = c.delete(
             "/organizations/%s/gcodes/%s" % (UUID_ORG, gcode_uuid),
             headers={"x-csrf-token": TOKEN_USER_CSRF},
         )
         self.assertEqual(response.status_code, 204)
     self.assertEqual(gcodes.get_gcode(gcode_uuid), None)
     pjs = [
         pj for pj in printjobs.get_printjobs(UUID_ORG)
         if pj["gcode_data"]["uuid"] == gcode_uuid
     ]
     self.assertEqual(len(pjs), 2)
     for pj in pjs:
         self.assertFalse(pj["gcode_data"]["available"])
Example #50
0
    def setUp(self):
        """Stuff to do before every test."""

        # Get the Flask test client
        self.client = app.test_client()

        # Show Flask errors that happen during tests
        app.config['TESTING'] = True

        app.config['SECRET_KEY'] = 'key'

        # Connect to test database
        connect_to_db(app, "postgresql:///testdb")

        # Create tables and seed with data
        db.create_all()
        load_location('locations_fortest.txt')
        load_person('user_examples.txt')
        load_saved_record('records_fortest.txt')

        def _mock_get_locations_dict(loc_lst):
            mock_dict = {}
            mock_forecast = open('mock_forecast_response.txt', 'r').read()
            mock_forecast = json.loads(mock_forecast)

            for loc in loc_lst:
                mock_dict[loc] = mock_forecast

            return mock_dict

        def _mock_get_location_geojson(loc_lst):

            geojson_str = """{ "features": [ { "geometry":
                { "coordinates": [ -100.00, 100.00 ], "type": "Point" },
                "properties": { "id": 1, "name": "StarsEverywhere", "light": 1 },
                "type": "Feature" }], "type" : "FeatureCollection"}"""

            return geojson_str

        import server
        server.get_locations_dict = _mock_get_locations_dict
        server.get_location_geojson = _mock_get_location_geojson
Example #51
0
 def test_delete(self, mock_send_mail):
     with app.test_client() as c:
         c.set_cookie("localhost", "access_token_cookie", TOKEN_ADMIN)
         email = get_random_email()
         response = c.post(
             "/organizations/%s/users" % UUID_ORG,
             headers={"x-csrf-token": TOKEN_ADMIN_CSRF},
             json={
                 "role": "user",
                 "email": email,
             },
         )
         self.assertEqual(response.status_code, 201)
         uuid = response.json["uuid"]
         user = users.get_by_email(email)
         api_tokens.add_token(
             user_uuid=uuid,
             jti=guid.uuid4(),
             organization_uuid=UUID_ORG,
             name="jti",
         )
         self.assertTrue(user["uuid"], uuid)
         response = c.delete(
             "/organizations/%s/users/%s" % (UUID_ORG, uuid),
             headers={"x-csrf-token": TOKEN_ADMIN_CSRF},
         )
         self.assertEqual(response.status_code, 204)
         orgrole = organization_roles.get_organization_role(
             UUID_ORG, user["uuid"])
         tokens = api_tokens.get_tokens_for_user_uuid(user["uuid"],
                                                      org_uuid=UUID_ORG)
         self.assertTrue(user is not None)
         self.assertTrue(orgrole is None)
         for t in tokens:
             self.assertTrue(t["revoked"])
             self.assertTrue(t["organization_uuid"] == UUID_ORG)
         args = mock_send_mail.call_args_list
         self.assertEqual(args[1][0][0][0], email)
         self.assertEqual(args[1][0][1], "ORGANIZATION_REMOVAL")
         self.assertTrue(args[1][0][2]["organization_name"] is not None)
         self.assertTrue(args[1][0][2]["organization_uuid"] is not None)
         self.assertEqual(args[1][0][2]["email"], email)
Example #52
0
 def test_reset_password(self, mock_send_mail):
     with app.test_client() as c:
         response = c.post(
             "/users/me/reset-password",
             json={
                 "email": self.email,
                 "pwd_reset_key": self.pwd_reset_key,
                 "password": "******",
                 "password_confirmation": "aaa",
             },
         )
         self.assertEqual(response.status_code, 204)
         local_user = local_users.get_local_user(self.user_uuid)
         self.assertTrue(local_user["pwd_reset_key_hash"] is None)
         self.assertTrue(local_user["pwd_reset_key_expires"] is None)
         self.assertEqual(mock_send_mail.call_count, 1)
         args = mock_send_mail.call_args_list
         self.assertEqual(args[0][0][0][0], self.email)
         self.assertEqual(args[0][0][1], "PASSWORD_RESET_CONFIRMATION")
         self.assertEqual(args[0][0][2]["email"], self.email)
Example #53
0
 def test_filter_next(self):
     with app.test_client() as c:
         c.set_cookie("localhost", "access_token_cookie", TOKEN_USER)
         response = c.get(
             "/organizations/%s/printjobs?filter=printer_uuid:e24a9711-aabc-48f0-b790-eac056c43f07&limit=10&order_by=-uuid"
             % UUID_ORG,
             headers={"x-csrf-token": TOKEN_USER_CSRF},
         )
         self.assertEqual(response.status_code, 200)
         self.assertTrue("items" in response.json)
         self.assertTrue("next" in response.json)
         self.assertTrue(len(response.json["items"]) == 10)
         response2 = c.get(
             response.json["next"],
             headers={"x-csrf-token": TOKEN_USER_CSRF},
         )
         self.assertEqual(response2.status_code, 200)
         self.assertTrue("items" in response2.json)
         self.assertTrue(response.json["items"][0]["uuid"] >
                         response2.json["items"][0]["uuid"])
Example #54
0
    def setUp(self):
        """ Things to do before every test."""

        # Get the Flask test client
        self.client = app.test_client()
        app.config['TESTING'] = True

        # Connect to test database
        connect_to_db(app, "postgresql:///testfood")

        # Create tables and add sample data
        db.create_all()
        example_data()

        # Create a session
        app.config['SECRET_KEY'] = os.environ["testing_secret_key"]

        with self.client as c:
            with c.session_transaction() as sess:
                sess['user_id'] = 1
Example #55
0
    def setUp(self):
        """Done before every test."""

        # Get the Flask test client
        self.client = app.test_client()
        app.config['TESTING'] = True

        app.config['SECRET_KEY'] = 'testingSecrets'
        with self.client as c:
            with c.session_transaction() as sess:
                # Log in as 'Potato' user
                sess['user'] = 2

        # Connect to test database
        connect_to_db(app, "postgresql:///testdb")
        UPLOAD_FOLDER = 'static/Testing/testfiles'
        app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
        db.create_all()
        set_acceptable_media_types()
        create_data()
Example #56
0
 def test_update_user(self):
     with app.test_client() as c:
         c.set_cookie("localhost", "access_token_cookie", TOKEN_ADMIN)
         response = c.patch(
             "/users/%s" % self.uuid,
             headers={"x-csrf-token": TOKEN_ADMIN_CSRF},
             json={
                 "role": "admin",
                 "suspended": True
             },
         )
         self.assertEqual(response.status_code, 200)
         self.assertTrue("role" in response.json)
         self.assertTrue("suspended" in response.json)
         self.assertEqual(response.json["role"], "admin")
         self.assertEqual(response.json["suspended"], True)
         user = users.get_by_uuid(self.uuid)
         self.assertTrue(user is not None)
         self.assertEqual(user["role"], "admin")
         self.assertEqual(user["suspended"], True)
Example #57
0
	def setUp(self):
		''' runs before each test '''

		# test_client simulates that the server is running
		# app defined inside server
		app.config['TESTING'] = True
		self.client = app.test_client()
		connect_to_db(app, "postgresql:///testdb")
		db.create_all()
		example_data()

		# adds a user to the session to carry out routes while logged in
		# user = User.query.filter_by(username='******').first()

		with self.client as c:
			with c.session_transaction() as sess:
				sess['user_id'] = 2
				sess['game_id'] = 4
				sess['difficulty_level'] = "3"
				sess['name'] = 'teddy'
Example #58
0
    def setUp(self):
        """Set up test database and mock api result."""

        self.client = app.test_client()
        app.config['TESTING'] = True
        connect_to_db(app, "postgresql:///testdb")

        db.create_all()
        example_data()

        # Make mock
        def _mock_find_route_coordinates(origin, destination):

            return [(37.8067567, -122.2961741), (37.8070326, -122.2974171),
                    (37.8167166, -122.2896513), (37.8276755, -122.2890558),
                    (37.8279634, -122.2893052), (37.8280475, -122.288937),
                    (37.8287455, -122.2891528), (37.8290338, -122.2886093),
                    (37.8291819, -122.2886597)]

        find_route_coordinates = _mock_find_route_coordinates
    def setUp(self):
        """Method called before each test."""

        # Flask's test client is instantiated.
        self.client = app.test_client()

        # Flask's TESTING configuration variable is set so that any Flask error
        # will be printed in the same console as the tests. This makes it
        # easy to debug any errors that occur during tests.
        app.config['TESTING'] = True
        app.config['DEBUG'] = False

        # Required configuration for apps that use sessions.
        app.config['SECRET_KEY'] = 'key'

        # Assigns the test client a user_if of 1.
        # Useful for testing the parts of my app that require login.
        with self.client as c:
            with c.session_transaction() as sess:
                sess['user_id'] = 1
Example #60
0
    def setUp(self):
        """Stuff to do before every test."""

        # Get the Flask test client
        self.client = app.test_client()

        # Show Flask errors that happen during tests
        app.config['TESTING'] = True

        # Connect to test database
        connect_to_db(app, "postgresql:///testdb")

        # Create tables and add sample data
        db.create_all()
        example_data_users()

        # initiate a session
        with self.client.session_transaction() as session:
            session['user'] = '******'
            self.client.set_cookie('localhost', 'MYCOOKIE', 'cookie_value')