These are chat archives for pythonvietnam/Flask

5th
Jul 2017
dan
@Piusdan
Jul 05 2017 23:52

Having problems using url_for inside unnitests
This is my code

class APITestCase(unittest.TestCase):
    def setUp(self):
        self.app = create_app('testing')
        self.app_context = self.app.app_context()
        self.app_context.push()
        db.create_all()
        Role.insert_roles()
        self.client = self.app.test_client()

    def tearDown(self):
        db.session.remove()
        db.drop_all()
        self.app_context.pop()

    def get_api_headers(self, phone_number, password):
        return {
            'Authorization':
                'Basic' + b64encode(
                    (phone_number + ':' + password).encode('utf-8')).decode('utf-8'),
            'Accept': 'application/json',
            'Content-Type': 'Application/json'
        }

    def test_no_auth(self):
        response = self.client.get(url_for('api.get_events', _external=False),
                                   content_type='application/json')
        self.assertTrue(response.status_code == 401)

    def test_event(self):
        # create a new user
        r = Role.query.filter_by(name='User').first()
        self.assertIsNotNone(r)
        u = User(email='joe@example.com', password='cat', phone_number='254703554404', role=r)
        db.session.add(u)
        db.session.commit()

        resp = self.client.post(
            url_for('api.create_event', _external=False),
            headers=self.get_api_headers('254703554404', 'cat'),
            data=json.dumps({'desc': 'working party', 'date': datetime.datetime.now()})
        )
        self.assertTrue(resp.status_code == 201)
        url = resp.headers.get('Location')
        self.assertIsNotNone(url)

When run, it returns an error that flask cannot find the endpoints,
Someone help