Skip to content

Instantly share code, notes, and snippets.

@spenoir
Created October 28, 2015 12:22
Show Gist options
  • Save spenoir/97d71e2a492e5b0ecad9 to your computer and use it in GitHub Desktop.
Save spenoir/97d71e2a492e5b0ecad9 to your computer and use it in GitHub Desktop.
Tests for a simple countries json api written using Flask
import urllib2
from bson import ObjectId
from flask.ext.pymongo import MongoClient
from flask.ext.testing import LiveServerTestCase, TestCase
from nose.tools import nottest
import requests
from prototypes import app, update_es, es, User
conn = MongoClient()
db = conn['test-am-es-prototypes']
class AppTest(TestCase):
# requires flask server at localhost:5000
@nottest
def create_app(self):
app.config['TESTING'] = True
return app
def test_admin_is_up_and_running(self):
response = urllib2.urlopen('http://localhost:5000/admin/')
self.assertEqual(response.code, 200)
def test_admin_countries_is_up_and_running(self):
response = urllib2.urlopen('http://localhost:5000/admin/countriesview')
self.assertEqual(response.code, 200)
def test_api_is_up_and_running(self):
response = urllib2.urlopen('http://localhost:5000/countries/')
self.assertEqual(response.code, 200)
class ESTest(TestCase):
# requires es server at localhost:9200
@nottest
def create_app(self):
app.config['TESTING'] = True
return app
def test_reset_es_index(self):
update_es('test-countries')
result = es.search('test-countries', body={'query': {'filtered': { 'query': { 'match': {'code': 'ARG'}}}}})
self.assertEqual(result['hits']['total'], 1)
def test_search_multiple(self):
update_es('test-countries')
result = es.search('test-countries', body={'query': {'filtered': { 'query': { 'match': {'poly_type': 'MultiPolygon'}}}}})
self.assertTrue(result['hits']['total'] > 1)
class UserTest(TestCase):
@nottest
def create_app(self):
app.config['TESTING'] = True
return app
def setUp(self):
db.users.insert({
"_id" : ObjectId("554b435bc724d0971f0d00f6"),
"username" : "test",
"first_name" : "test",
"last_name" : "user",
"api_key" : "123456",
"password" : "user",
"active" : True
})
self.user = User(db.users.find_one({'username': 'test', 'password': 'user'}))
def tearDown(self):
db.drop_collection('users')
def test_user_model_creation(self):
self.assertTrue(isinstance(self.user, User))
self.assertTrue(hasattr(self.user, 'username'))
def test_user_can_login(self):
response = requests.post('http://localhost:5000/login/', data={
'username': self.user.username, 'password': self.user.password
})
self.assertTrue('Logged in successfully' in response.content)
self.assertTrue(self.user.is_authenticated())
def test_user_can_logout(self):
response = requests.get('http://localhost:5000/logout/')
self.assertFalse(self.user.is_authenticated())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment