Dragoman / dragoman / lib / test / test_api.py

# -*- coding: utf-8 -*-
import os

from pymongo import Connection

from urllib import quote
import httplib2
import simplejson

from dragoman.lib.client import Connection as DMConn
from dragoman.lib.client import Catalog, Language
from dragoman.lib.testing import start_test_server

from pprint import pprint, pformat


def stub_db(c):
    c.test_catalog.piglatin.add('I like it', 'Me gusta')

def setup_module(module):
    module.server = start_test_server()

def teardown_module(module):
    del module.server


class TestBasicCrud(object):

    def setup_class(self):
        # clear the cache
        cache = '.dragoman_client_cache'
        if os.path.isdir(cache):
            for f in os.listdir(cache):
                os.remove(os.path.join(cache, f))
        elif os.path.isfile(cache):
            os.remove(cache)

        # get a client
        self.http = httplib2.Http(cache)

        # clear out the database
        c = Connection()
        c.drop_database('test_translations')

    def test_basic(self):
        '''Test basic crud operations at the HTTP level (caching...) '''
        catalog = 'test_gryphon'
        data = simplejson.dumps({'translation': 'Me gustalo',
                                 'phrase': 'I like it',
                                 'description': 'A sample category'})

        url = '%s/api/test_gryphon/piglatin/%s' % (server.base_url, quote('I like it'))
        resp, content = self.http.request(url)
        assert resp.status == 404
        
        resp, content = self.http.request(
            url, 'POST', headers={'Content-Type': 'application/json'},
            body=data
        )
        assert resp.status == 201

        resp, content = self.http.request(url)

        assert resp.status == 200
        assert content == 'Me gustalo'
        assert resp.get('etag')
        assert resp.get('cache-control')

        resp, content = self.http.request(url)
        assert resp.fromcache

class TestLanguageCrud(object):
    def setup_class(self):
        # clear the cache
        cache = '.dragoman_client_cache'
        for f in os.listdir(cache):
            os.remove(os.path.join(cache, f))

        # get a client
        self.http = httplib2.Http(cache)

    
    def test_create_and_delete(self):
        abbrev, name = 'foo', 'bar'

        # create
        create_url = '%s/api/language' % server.base_url
        resp, content = self.http.request(
            create_url, 'POST', body=simplejson.dumps({'abbrev': abbrev,
                                                       'name': name}),
            headers={'Content-Type': 'application/json'}
        )
            
        assert resp.status == 201
        doc = simplejson.loads(content)
        assert doc
        assert doc['message'] == 'created'

        # delete
        delete_url = '%s/api/language/%s' % (server.base_url, abbrev)
        resp, content = self.http.request(delete_url, 'DELETE')
        assert resp.status == 200
        doc = simplejson.loads(content)
        assert doc['message'] == 'deleted'
        

class TestRawCatalogApi(object):
    def setup_class(self):
        # clear the cache b/c the client will make one
        cache = '.dragoman_client_cache'
        for f in os.listdir(cache):
            os.remove(os.path.join(cache, f))
        os.rmdir(cache)
        
        self.base = '%s/api' % server.base_url
        self.conn = DMConn('%s/api' % server.base_url)
        self.h = httplib2.Http()
        c = Connection()
        c.drop_database('test_translations')
        stub_db(self.conn)

    def test_service_doc(self):
        resp, content = self.h.request(self.base)
        assert resp.status == 200
        result = simplejson.loads(content)
        service_keys = set([
            'base', 'self', 'phrase', 'phrases', 'catalog', 'language', 'languages',
        ])
        assert set(result.keys()) == service_keys
        

    def test_raw_catalog_get_listing(self):
        resp, content = self.h.request('%s/catalog' % self.base)
        assert resp.status == 200

        result = simplejson.loads(content)
        assert result[0] == 'test_catalog'

        resp, content = self.h.request('%s/catalog/%s' % (self.base, result[0]))
        assert resp.status == 200

        result = simplejson.loads(content)
        assert result[0] == 'piglatin'


    def test_raw_catalog_add_json(self):
        # add a catalog
        new_catalog_data = {
            'piglatin': [{
                'phrase': 'I like it',
                'translation': '我喜欢它'
            }]
        }

        resp, content = self.h.request(
            '%s/catalog/test_new_catalog/piglatin' % self.base,
            'POST', body=simplejson.dumps(new_catalog_data),
            headers={'Content-Type': 'application/json'}
        )

        assert resp.status == 201
        result = simplejson.loads(content)
        assert result['message'] == 'created'

        # get the languages next
        resp, content = self.h.request('%s/catalog/test_new_catalog' % self.base)
        assert resp.status == 200
        result = simplejson.loads(content)
        assert result == ['piglatin']

    def test_raw_catalog_add_noop(self):
        resp, content = self.h.request('%s/catalog/test_new_catalog' % self.base, 'POST')
        assert resp.status == 400

        resp, content = self.h.request('%s/catalog/test_new_catalog/piglatin' % self.base, 'POST')
        print resp, content
        assert resp.status == 201

        # the default shouldn't have values, but this makes for a
        # better test that the import worked.
        msg = quote("Please provide a whole number.")
        resp, content = self.h.request('%s/test_new_catalog/piglatin/%s' % (self.base, msg))

        assert resp.status == 200
        assert content == '请提供一个整数。'

        
class TestDragomanClient(object):
    def setup_class(self):
        self.conn = DMConn('%s/api' % server.base_url)
        c = Connection()
        c.drop_database('test_translations')

    def test_crud(self):
        cat1 = self.conn.test_catalog
        cat2 = self.conn['test_catalog']
        assert cat1
        assert cat2

        lang1 = cat1.piglatin
        lang2 = cat1['piglatin']
        assert lang1
        assert lang2

        assert lang1.add('I like it', 'Me gustalo')
        assert lang1.get('I like it') == 'Me gustalo'        
        assert lang2('I like it') == 'Me gustalo'
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.