import unittest from wanikaniburned import app, db, User, datetime_format, parse_range from flask.ext.testing import TestCase from datetime import datetime class BaseTestCase(TestCase): def create_app(self): app.config.update( TESTING=True, SQLALCHEMY_DATABASE_URI='sqlite:///:memory:', SECRET_KEY="testkey", WTF_CSRF_ENABLED=False, PRESERVE_CONTEXT_ON_EXCEPTION=False, HASH_ROUNDS=1 ) return app def setUp(self): db.create_all() def tearDown(self): db.session.remove() db.drop_all() class TestLogin(BaseTestCase): def login(self): user = User('test', False) return self.client.post('/', data={'api_key': user.api_key}) def test_user_login(self): response = self.login() self.assertRedirects(response, '/quiz') def test_user_logout(self): response = self.login() self.assertRedirects(response, '/quiz') response = self.client.get('/logout') self.assertRedirects(response, '/') def test_homepage_without_login(self): response = self.client.get('/') self.assert200(response) self.assertTemplateUsed("welcome.html") def test_quiz_inaccessible_without_login(self): response = self.client.get('/quiz') self.assertRedirects(response, '/') def test_user_items_inaccessible_without_login(self): response = self.client.get('/user_items') self.assertRedirects(response, '/') def test_homepage_with_existing_login(self): response = self.login() # Login self.assertRedirects(response, '/quiz') response = self.client.get('/') # Try to go back to the homepage self.assertRedirects(response, '/quiz') def test_user_items_with_existing_login(self): response = self.login() # Login self.assertRedirects(response, '/quiz') response = self.client.get('/user_items') self.assert200(response) class TestFormats(unittest.TestCase): def test_custom_datetime_format(self): test_time = datetime.min output = datetime_format(test_time) self.assertEqual(output, "01 January 0001 12:00AM") def test_parse_range_empty(self): self.assertIsNone(parse_range("")) def test_parse_range_letters(self): self.assertIsNone(parse_range("ab-st,z")) def test_parse_range_single_number(self): self.assertEqual(parse_range("1"), [1]) def test_parse_range_two_with_dash(self): self.assertEqual(parse_range("1-4"), [1, 2, 3, 4]) def test_parse_range_two_with_comma(self): self.assertEqual(parse_range("1,2"), [1, 2]) def test_parse_range_dash_and_comma(self): self.assertEqual(parse_range("1,4-6"), [1, 4, 5, 6]) if __name__ == '__main__': unittest.main()