Ejemplo n.º 1
0
 def test_request(self):
     with app.test_request_context('/users/stevewoz'):
         self.assertEqual(flask.request.path, '/users/stevewoz')
         self.assertNotIn('limit', flask.request.args)
     with app.test_request_context('/users/stevewoz?limit=20'):
         self.assertEqual(flask.request.path, '/users/stevewoz')
         self.assertEqual(int(flask.request.args['limit']), 20)
Ejemplo n.º 2
0
 def test_request(self):
     with app.test_request_context('/hashtags/Python'):
         self.assertEqual(flask.request.path, '/hashtags/Python')
         self.assertNotIn('limit', flask.request.args)
     with app.test_request_context('/hashtags/Python?limit=20'):
         self.assertEqual(flask.request.path, '/hashtags/Python')
         self.assertEqual(int(flask.request.args['limit']), 20)
Ejemplo n.º 3
0
    def test_wiki_without_top(self):
        app.config['WIKI_HITS'] = defaultdict(int)
        self.assertEqual(
            app.config['WIKI_HITS'][self.TEST_WORD] +
            app.config['WIKI_HITS'][self.TEST_WORD1], 0)
        with app.test_request_context():
            with patch('external.get_wiki', self._mock_wiki):
                for i in range(10):
                    self.app.get(url_for('wiki_content', word=self.TEST_WORD),
                                 headers=self.TEST_AUTH)

                for i in range(5):
                    self.app.get(url_for('wiki_content', word=self.TEST_WORD1),
                                 headers=self.TEST_AUTH)

                resp = self.app.get(url_for('wiki_top'),
                                    headers=self.TEST_AUTH)

        self.assertNotEqual(
            app.config['WIKI_HITS'][self.TEST_WORD] +
            app.config['WIKI_HITS'][self.TEST_WORD1], 0)
        self.assertEqual(app.config['WIKI_HITS'][self.TEST_WORD], 10)
        self.assertEqual(app.config['WIKI_HITS'][self.TEST_WORD1], 5)

        self.assertEqual(resp.status_code, 200)
        self.assertEqual(1, len(resp.json['top']))
        self.assertEqual(self.TEST_WORD, resp.json['top'][0])
Ejemplo n.º 4
0
    def test_wiki_with_invalid_top(self):
        with app.test_request_context():
            resp = self.app.get(url_for('wiki_top', top='test'),
                                headers=self.TEST_AUTH)

        self.assertEqual(resp.status_code, 400)
        self.assertIn(MESSAGES['ERR_INVALID_TOP'].encode(), resp.data)
Ejemplo n.º 5
0
    def test_wiki_post(self):
        with app.test_request_context():
            resp_content = self.app.post(
                url_for('wiki_content', word=self.TEST_WORD))
            resp_top = self.app.post(url_for('wiki_top'))

        self.assertEqual(resp_content.status_code, 405)
        self.assertEqual(resp_top.status_code, 405)
Ejemplo n.º 6
0
    def test_login_wrong_password(self):
        self.TEST_PASSWORD = '******'
        with app.test_request_context():
            resp = self.app.get(url_for('login'),
                                headers=self._get_auth_header())

        self.assertEqual(resp.status_code, 401)
        self.assertIn(MESSAGES['AUTH_FAIL_WRONG_PASS'].encode(), resp.data)
Ejemplo n.º 7
0
    def test_login_success(self):
        with app.test_request_context():
            with patch('api._get_token', return_value=self.TEST_TOKEN):
                resp = self.app.get(url_for('login'),
                                    headers=self._get_auth_header())

        self.assertEqual(resp.status_code, 200)
        self.assertEqual(self.TEST_TOKEN, resp.json['token'])
Ejemplo n.º 8
0
    def test_login_blank_username(self):
        self.TEST_USERNAME = ''
        with app.test_request_context():
            resp = self.app.get(url_for('login'),
                                headers=self._get_auth_header())

        self.assertEqual(resp.status_code, 401)
        self.assertIn(MESSAGES['AUTH_FAIL_CREDENTIALS'].encode(), resp.data)
Ejemplo n.º 9
0
    def test_login_no_user(self):
        app.config['USERS'] = {}
        with app.test_request_context():
            with patch('api._get_token', return_value=self.TEST_TOKEN):
                resp = self.app.get(url_for('login'),
                                    headers=self._get_auth_header())

        self.assertEqual(resp.status_code, 401)
        self.assertIn(MESSAGES['AUTH_FAIL_NO_USER'].format(self.TEST_USERNAME, '').encode(), resp.data)
Ejemplo n.º 10
0
    def test_sign_up_blank_password(self):
        with app.test_request_context():
            resp = self.app.post(url_for('signup'),
                                 data=json.dumps(
                                     {'username': self.TEST_USERNAME}),
                                 content_type=JSON_MIME_TYPE)

        self.assertEqual(resp.status_code, 400)
        self.assertIn(MESSAGES['NO_CREDENTIALS'].encode(), resp.data)
Ejemplo n.º 11
0
    def test_random_word_ok(self):
        with app.test_request_context():
            with patch('external._get_random_word_resp', side_effect=self._mock_get_random_word_resp), \
                 patch('external._get_random_api_key', return_value=self.TEST_VALID_API_KEY):
                resp = self.app.get(url_for('random_word'),
                                    headers=self.TEST_AUTH)

        self.assertEqual(resp.status_code, 200)
        self.assertEqual(resp.json['word'], self.TEST_RANDOM_WORD)
Ejemplo n.º 12
0
    def setUp(self):
        # creates a test client
        self.app = app.test_client()
        # propagate the exceptions to the test client
        self.app.testing = True
        with app.test_request_context():
            self.api_url = url_for('divide')

        self.op = operator.div
 def test_build_json_without_success(self):
     success = False
     messages = ['Falhou']
     with app.test_request_context():
         r = JSONResponseBuilder.build_response(success=success,
                                                messages=messages)
     dictionary = json.loads(r.get_data().decode("utf-8"))
     self.assertEquals(dictionary['data'], [])
     self.assertEquals(dictionary['success'], success)
     self.assertEquals(dictionary['messages'], messages)
 def test_build_json_with_success(self):
     data = ['my cool array']
     success = True
     with app.test_request_context():
         r = JSONResponseBuilder.build_response(data,
                                                success)
     dictionary = json.loads(r.get_data().decode("utf-8"))
     self.assertEquals(dictionary['data'], data)
     self.assertEquals(dictionary['success'], success)
     self.assertEquals(dictionary['messages'], [])
Ejemplo n.º 15
0
    def test_joke(self):
        with app.test_request_context():
            with patch('external.get_joke', side_effect=self._mock_joke):
                resp = self.app.get(url_for('joke'), headers=self.TEST_AUTH)

        self.assertEqual(resp.status_code, 200)

        joke = resp.json['joke']
        self.assertIsNotNone(joke)
        self.assertIn(DEFAULT_JOKE_NAMES['firstName'], joke)
        self.assertIn(DEFAULT_JOKE_NAMES['lastName'], joke)
Ejemplo n.º 16
0
    def test_wiki_bad_word(self):
        with app.test_request_context():
            with patch('external.get_wiki', self._mock_wiki):
                resp = self.app.get(url_for('wiki_content',
                                            word=self.BAD_WORD),
                                    headers=self.TEST_AUTH)

        self.assertEqual(resp.status_code, 404)
        self.assertIn(
            MESSAGES['ERR_NO_ARTICLE'].format(self.BAD_WORD).encode(),
            resp.data)
Ejemplo n.º 17
0
    def test_random_word_alternate_empty_dict(self):
        app.config['WORDS'] = []
        with app.test_request_context():
            with patch('external._get_random_word_resp', side_effect=BadRequest('Test')), \
                 patch('external._get_random_api_key', return_value=self.TEST_VALID_API_KEY), \
                 patch('api._init_words', side_effect=None):
                resp = self.app.get(url_for('random_word'),
                                    headers=self.TEST_AUTH)

        self.assertEqual(resp.status_code, 400)
        self.assertIn(MESSAGES['ERR_DICT'].encode(), resp.data)
Ejemplo n.º 18
0
    def test_random_word_invalid_valid_key(self):
        with app.test_request_context():
            with patch('external._get_random_word_resp',
                       side_effect=self._mock_get_random_word_resp) as random_mock, \
                    patch('external._get_random_api_key',
                          side_effect=[self.TEST_INVALID_API_KEY, self.TEST_VALID_API_KEY]):
                resp = self.app.get(url_for('random_word'),
                                    headers=self.TEST_AUTH)
                random_mock.assert_called_with(self.TEST_VALID_API_KEY)

        self.assertEqual(resp.status_code, 200)
        self.assertEqual(resp.json['word'], self.TEST_RANDOM_WORD)
Ejemplo n.º 19
0
    def test_sign_up_user_exists(self):
        with app.test_request_context():
            resp = self.app.post(url_for('signup'),
                                 data=json.dumps({
                                     'username': self.TEST_USERNAME,
                                     'password': self.TEST_PASSWORD
                                 }),
                                 content_type=JSON_MIME_TYPE)

        self.assertEqual(resp.status_code, 400)
        self.assertIn(
            MESSAGES['USER_EXISTS'].format(self.TEST_USERNAME).encode(),
            resp.data)
Ejemplo n.º 20
0
    def test_sign_up_success(self):
        new_username = '******'
        with app.test_request_context():
            resp = self.app.post(url_for('signup'),
                                 data=json.dumps({
                                     'username': new_username,
                                     'password': self.TEST_PASSWORD
                                 }),
                                 content_type=JSON_MIME_TYPE)

        self.assertEqual(resp.status_code, 201)
        self.assertIn(MESSAGES['SIGNED_UP'].format(new_username).encode(),
                      resp.data)
Ejemplo n.º 21
0
    def test_random_word_alternate_ok(self):
        with app.test_request_context():
            with patch('external._get_random_word_resp', side_effect=BadRequest('Test')), \
                 patch('external._get_random_api_key', return_value=self.TEST_VALID_API_KEY):
                resp = self.app.get(url_for('random_word'),
                                    headers=self.TEST_AUTH)
                resp2 = self.app.get(url_for('random_word'),
                                     headers=self.TEST_AUTH)

        self.assertEqual(resp.status_code, 200)
        self.assertEqual(resp2.status_code, 200)

        self.assertIn(resp.json['word'], app.config['WORDS'])
        self.assertIn(resp2.json['word'], app.config['WORDS'])
Ejemplo n.º 22
0
    def test_wiki_good_word(self):
        app.config['WIKI_HITS'] = defaultdict(int)
        self.assertEqual(app.config['WIKI_HITS'][self.TEST_WORD], 0)
        with app.test_request_context():
            with patch('external.get_wiki', self._mock_wiki):
                self.app.get(url_for('wiki_content', word=self.TEST_WORD),
                             headers=self.TEST_AUTH)
                resp = self.app.get(url_for('wiki_content',
                                            word=self.TEST_WORD),
                                    headers=self.TEST_AUTH)

        self.assertEqual(app.config['WIKI_HITS'][self.TEST_WORD], 2)
        self.assertEqual(resp.status_code, 200)
        self.assertEqual({'article': self.TEST_ARTICLE.format(self.TEST_WORD)},
                         resp.json['content'])
Ejemplo n.º 23
0
def client():
    #setup
    db_fd, db_location = tempfile.mkstemp()
    app.config['SQLALCHEMY_DATABASE_URI']=f'sqlite:///{db_location}'
    app.config['TESTING'] = True

    #убираем вывод миграций
    logging.disable(logging.WARNING)

    app_context = app.test_request_context()
    with app.test_client() as client:
        with app_context:
            upgrade()
        yield client
    #teardown
    os.close(db_fd)
    os.unlink(db_location)
Ejemplo n.º 24
0
 def api_url_for(self, endpoint, **kwargs):
     with app.test_request_context('/'):
         return url_for(endpoint, **kwargs)
Ejemplo n.º 25
0
    def test_random_word_post(self):
        with app.test_request_context():
            resp = self.app.post(url_for('random_word'))

        self.assertEqual(resp.status_code, 405)
Ejemplo n.º 26
0
    def test_auth_decorators(self):
        from api.base.resources.decorators import authenticate, public,\
            public_actions

        def _view(_argument, action=None):
            return app.response_class(_argument,
                                      mimetype='application/json',
                                      status=200)

        # Unauthorized
        with app.test_request_context('/') as ctx:
            req = ctx.request

            view = authenticate(_view)
            self.assertEquals(view.__name__, _view.__name__)

            res = view('sample')
            self.assertEquals(res.status_code, 401)
            self.assertEquals(res.headers['X-Odesk-Error-Message'],
                              'Unauthorized')
            self.assertFalse(hasattr(req, 'user'))

        # Authorized
        if hasattr(_view, 'authenticated'):
            delattr(_view, 'authenticated')
        with app.test_request_context('/', headers=HTTP_HEADERS) as ctx:
            req = ctx.request

            view = authenticate(_view)
            self.assertEquals(view.__name__, _view.__name__)

            res = view('sample')
            self.assertEquals(res.status_code, 200)
            self.assertEquals(res.data, 'sample')
            self.assertEquals(str(req.user.uid), 'somebody')

        # Wrong auth token
        headers = dict(HTTP_HEADERS)
        headers['X-Auth-Token'] = 'wrong'
        if hasattr(_view, 'authenticated'):
            delattr(_view, 'authenticated')
        with app.test_request_context('/', headers=headers.items()) as ctx:
            req = ctx.request

            view = authenticate(_view)
            self.assertEquals(view.__name__, _view.__name__)

            res = view('sample')
            self.assertEquals(res.status_code, 401)
            self.assertEquals(res.headers['X-Odesk-Error-Message'],
                              'Unauthorized')
            self.assertIsNone(req.user)

        # Public view
        if hasattr(_view, 'authenticated'):
            delattr(_view, 'authenticated')
        with app.test_request_context('/') as ctx:
            req = ctx.request

            view = public(_view)
            self.assertTrue(hasattr(view, 'authenticated'))
            self.assertTrue(view.authenticated)

            view = authenticate(view)
            self.assertEquals(view.__name__, _view.__name__)

            res = view('sample')
            self.assertEquals(res.status_code, 200)
            self.assertEquals(res.data, 'sample')
            self.assertFalse(hasattr(req, 'user'))

        # Public actions
        if hasattr(_view, 'authenticated'):
            delattr(_view, 'authenticated')
        with app.test_request_context('/') as ctx:
            req = ctx.request

            view = public_actions(['act1', 'act2'])(_view)
            self.assertTrue(hasattr(view, 'public_actions'))

            view = authenticate(view)
            self.assertEquals(view.__name__, _view.__name__)

            res = view('sample', action='act1')
            self.assertEquals(res.status_code, 200)
            self.assertEquals(res.data, 'sample')
            self.assertFalse(hasattr(req, 'user'))

            res = view('sample', action='act2')
            self.assertEquals(res.status_code, 200)
            self.assertEquals(res.data, 'sample')
            self.assertFalse(hasattr(req, 'user'))

            res = view('sample')
            self.assertEquals(res.status_code, 401)

            res = view('sample', action='some_other')
            self.assertEquals(res.status_code, 401)
Ejemplo n.º 27
0
    def test_sign_up_blank(self):
        with app.test_request_context():
            resp = self.app.post(url_for('signup'), data=json.dumps({}))

        self.assertEqual(resp.status_code, 400)
        self.assertIn(MESSAGES['NO_CREDENTIALS'].encode(), resp.data)
Ejemplo n.º 28
0
    def test_joke_post(self):
        with app.test_request_context():
            resp = self.app.post(url_for('joke'))

        self.assertEqual(resp.status_code, 405)
Ejemplo n.º 29
0
    def test_joke_unauth(self):
        with app.test_request_context():
            resp = self.app.get(url_for('joke'))

        self.assertEqual(resp.status_code, 401)
Ejemplo n.º 30
0
from storymap import storage
from api import app, _write_embed_draft, _write_embed_published
from flask import g

# Find all storymaps with ids that contain bad chars

print "Examining StoryMaps"

regex = re.compile("[^A-Za-z0-9_\-]")

skip = 0
limit = 100
n = _user.count()

while skip < n:
    for user in _user.find({}, skip=skip, limit=limit):
        for id in [id for id in user["storymaps"].keys() if regex.search(id)]:
            key_prefix = storage.key_prefix(user["uid"], id)

            with app.test_request_context():
                print "Writing embed draft for %s" % key_prefix
                _write_embed_draft(key_prefix, user["storymaps"][id])

                if user["storymaps"][id].get("published_on"):
                    print "Writing embed published for %s" % key_prefix
                    _write_embed_published(key_prefix, user["storymaps"][id])

    skip += limit

sys.exit(0)
Ejemplo n.º 31
0
from api import app
from api.models import db
import os
from dotenv import load_dotenv
load_dotenv()

app.testing = True
app_context = app.test_request_context()
app_context.push()
client = app.test_client()

basedir = os.path.abspath(os.path.dirname(__file__))

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(
    basedir, 'test.db')
db.drop_all()
db.create_all()