<commit_before>import os, logging, time
import pdb
import unittest
from xml.dom import minidom
from xml.etree import cElementTree as xtree

from myql import MYQL
from myql.contrib.auth import YOAuth

from myql.contrib.table import Table
from myql.contrib.table import Base, BaseInput
from myql.contrib.table import Binder, BinderFunction, InputKey, InputValue, PagingPage, PagingUrl, PagingOffset

import readline, rlcompleter
readline.parse_and_bind('tab: complete')

logging.basicConfig(level=logging.DEBUG,format="[%(asctime)s %(levelname)s] [%(name)s.%(module)s.%(funcName)s] %(message)s \n")
logging.getLogger(__name__)

class TestOAuth(unittest.TestCase):

    def setUp(self,):
        pass

    def tearUp(self,):
        pass

    def test_get_guid(self,):
        oauth = YOAuth(None, None, from_file='credentials.json')
        yql = MYQL(format='json', oauth=oauth)
        response = yql.getGUID('josue_brunel')
        logging.debug(response.content)
        self.assertEquals(response.status_code,200)

    def test_yahoo_fantasy_sport(self,):
        oauth = YOAuth(None, None, from_file='credentials.json')
        yql = MYQL(format='json', oauth=oauth)
        teams = ('mlb.l.1328.t.1','mlb.l.1328.t.2')
        year = '2015-05-05'
        for team in teams:
            response = yql.rawQuery("SELECT * FROM fantasysports.teams.roster WHERE team_key = '{0}'  AND date = '{1}' ".format(team, year))
            if not response.status_code == 200:
                return False

            data = response.json()
            current_team = data['query']['results']['team']
            print current_team['team_id'],current_team['name'],current_team['number_of_trades'],current_team['number_of_moves']

class TestTable(unittest.TestCase):

    def setUp(self,):
        self.table_desc = {
            'name': 'mytest',
            'author': 'josuebrunel',
            'apiKeyURL': 'http://josuebrunel.org/api',
            'documentationURL': 'http://josuebrunel.org/doc.html',
            'sampleQuery': ['SELECT * FROM mytable', 'SELECT name FROM mytable WHERE id="345"','DELETE FROM mytable WHERE id="345"'],
        }

        self.table = Table(**self.table_desc)

        self.binder_desc = {
            'name': 'select',
            'itemPath': 'products.product',
            'produces': 'xml'
        }

        self.binder = Binder(**self.binder_desc)
        self.binder_insert = Binder('insert','products.product','json')

        self.key_desc = {
            'id': 'artist',
            'type': 'xs:string',
            'paramType': 'path'
        }

        self.key = InputKey(**self.key_desc)
        self.key2 = InputKey(id='song', type='xs:string', paramType='path', required='true')

        start= {'id': 'ItemPage', 'default': '1'}
        pageSize= {'id':'Count' ,'max':'25'}
        total= {'default': '10'}
        self.paging = PagingPage(start, pageSize, total)

    def xml_pretty_print(self, data):
        """Pretty logging.debug xml data
        """
        raw_string = xtree.tostring(data, 'utf-8')
        parsed_string = minidom.parseString(raw_string)
        return parsed_string.toprettyxml(indent='\t')

    def test_add_binder(self,):
        self.assertEqual(self.table.addBinder(self.binder),True)
        logging.debug(self.xml_pretty_print(self.table.etree))

    def test_remove_binder(self,):
        self.binder.addInput(self.key)
        self.binder_insert.addInput(self.key)
        self.binder.addFunction('', from_file='tests_data/jscode.js')
        self.binder_insert.addFunction("console.log('hello this is an insert function'); ")
        self.table.addBinder(self.binder)
        self.table.addBinder(self.binder_insert)
        self.table.save(name='before', path='tests_data')
        self.assertEqual(os.path.isfile('tests_data/before.xml'),True)
        self.table.removeBinder('select')
        self.table.save(name='after', path='tests_data')
        self.assertEqual(os.path.isfile('tests_data/after.xml'),True)

    def test_add_input_to_binder(self,):
        logging.debug(self.xml_pretty_print(self.binder.etree))
        self.assertEqual(self.binder.addInput(self.key),True)
        logging.debug(self.xml_pretty_print(self.binder.etree))

    def test_remove_input(self,):
        logging.debug(self.xml_pretty_print(self.binder.etree))
        self.assertEqual(self.binder.addInput(self.key),True)
        logging.debug(self.xml_pretty_print(self.binder.etree))
        self.assertEqual(self.binder.addInput(self.key2),True)
        logging.debug(self.xml_pretty_print(self.binder.etree))
        self.assertEquals(self.binder.removeInput(key_id='artist'),True)
        logging.debug(self.xml_pretty_print(self.binder.etree))

    def test_add_function_from_file(self,):
        logging.debug(self.xml_pretty_print(self.binder.etree))
        self.assertEqual(self.binder.addFunction('', from_file='tests_data/jscode.js'),True)
        logging.debug(self.xml_pretty_print(self.binder.etree))

    def test_remove_function(self,):
        logging.debug(self.xml_pretty_print(self.binder.etree))
        self.assertEqual(self.binder.addFunction('', from_file='tests_data/jscode.js'),True)
        logging.debug(self.xml_pretty_print(self.binder.etree))
        self.assertEqual(self.binder.removeFunction(), True)
        logging.debug(self.xml_pretty_print(self.binder.etree))

    def test_add_paging(self,):
        logging.debug(self.xml_pretty_print(self.binder.etree))
        self.assertEquals(self.binder.addPaging(self.paging), True)
        logging.debug(self.xml_pretty_print(self.binder.etree))

    def test_create_binder_with_paging(self,):
        start= {'id': 'ItemPage', 'default': '1'}
        pageSize= {'id':'Count' ,'max':'25'}
        total= {'default': '10'}
        paging = PagingPage(start, pageSize, total)
        logging.debug(self.xml_pretty_print(paging.etree))
        self.binder_desc['paging']=paging
        logging.debug(self.binder_desc)
        binder = Binder(**self.binder_desc)
        self.assertNotEqual(binder.paging,None)
        logging.debug(self.xml_pretty_print(binder.etree))

    def test_create_binder_with_offset_paging(self,):
        start= {'id': 'ItemPage', 'default': '1'}
        pageSize= {'id':'Count' ,'max':'25'}
        total= {'default': '10'}
        paging = PagingOffset(True,  start, pageSize, total)
        logging.debug(self.xml_pretty_print(paging.etree))
        self.binder_desc['paging']=paging
        logging.debug(self.binder_desc)
        binder = Binder(**self.binder_desc)
        self.assertNotEqual(binder.paging,None)
        logging.debug(self.xml_pretty_print(binder.etree))

    def test_create_binder_with_url_paging(self,):
        nextpage = {'path': 'ysearchresponse.nextpage'}
        paging = PagingUrl(nextpage)
        logging.debug(self.xml_pretty_print(paging.etree))
        self.binder_desc['paging']=paging
        logging.debug(self.binder_desc)
        binder = Binder(**self.binder_desc)
        self.assertNotEqual(binder.paging,None)
        logging.debug(self.xml_pretty_print(binder.etree))

    def test_remove_paging(self,):
        logging.debug(self.xml_pretty_print(self.binder.etree))
        self.assertEquals(self.binder.addPaging(self.paging), True)
        logging.debug(self.xml_pretty_print(self.binder.etree))
        self.assertEqual(self.binder.removePaging(), True)
        logging.debug(self.xml_pretty_print(self.binder.etree))

    def test_create_binder_with_urls(self,):
        url = 'http://josuebrunel.org/service/v1'
        url2 = 'http://josuebrunel.org/service/v1/?name=lol'
        self.binder_desc['urls'] = [url, url2]
        binder = Binder(**self.binder_desc)
        logging.debug(self.xml_pretty_print(binder.etree))
        self.assertEquals(self.binder.addUrl(url), True)
        logging.debug(self.xml_pretty_print(self.binder.etree))

    def test_add_url(self,):
        url = 'http://josuebrunel.org/service.js'
        logging.debug(self.xml_pretty_print(self.binder.etree))
        self.assertEquals(self.binder.addUrl(url), True)
        logging.debug(self.xml_pretty_print(self.binder.etree))

    def test_remove_url(self,):
        url = 'http://josuebrunel.org/service.js'
        url2 = 'http://google.com'
        logging.debug(self.xml_pretty_print(self.binder.etree))
        self.assertEquals(self.binder.addUrl(url), True)
        logging.debug(self.xml_pretty_print(self.binder.etree))
        self.assertEquals(self.binder.addUrl(url2), True)
        logging.debug(self.xml_pretty_print(self.binder.etree))
        self.assertEquals(self.binder.removeUrl(url), True)
        logging.debug(self.xml_pretty_print(self.binder.etree))

    def test_save_file(self,):
        self.table.save()
        self.assertEquals(os.path.isfile('mytest.xml'),True)

    def test_save_with_another_name(self):
        name = "tests_data/toto"
        self.table.save(name)
        self.assertEquals(os.path.isfile(name+'.xml'),True)

    def test_save_to_different_location(self,):
        fname = "titi"
        path = 'tests_data'
        name = os.path.join(path,fname)
        self.table.save(name=fname, path=path)
        self.assertEquals(os.path.isfile(name+'.xml'),True)

    def test_create_table(self,):
        self.binder.addInput(self.key)
        self.binder.addFunction('', from_file='tests_data/jscode.js')
        logging.debug(self.xml_pretty_print(self.table.etree))
        self.table.addBinder(self.binder)
        self.table.save(name='mytable', path='tests_data')
        self.assertEqual(os.path.isfile('tests_data/mytable.xml'),True)
        logging.debug(self.xml_pretty_print(self.table.etree))

    def test_create_table_and_add_two_binders(self,):
        self.binder.addInput(self.key)
        self.binder_insert.addInput(self.key)
        self.binder.addFunction('', from_file='tests_data/jscode.js')
        self.binder_insert.addFunction("console.log('hello this is an insert function'); ")
        logging.debug(self.xml_pretty_print(self.table.etree))
        self.table.addBinder(self.binder)
        logging.debug(self.xml_pretty_print(self.table.etree))
        self.table.addBinder(self.binder_insert)
        self.table.save(name='mytable', path='tests_data')
        self.assertEqual(os.path.isfile('tests_data/mytable.xml'),True)
        logging.debug(self.xml_pretty_print(self.table.etree))

    def test_create_table_with_binder(self,):
        self.binder.addInput(self.key)
        self.binder.addFunction('', from_file='tests_data/jscode.js')
        self.table_desc['bindings'] = [self.binder]
        table = Table(**self.table_desc)
        logging.debug(self.xml_pretty_print(table.etree))
        table.save(name='mytable', path='tests_data')
        self.assertEqual(os.path.isfile('tests_data/mytable.xml'),True)
        logging.debug(self.xml_pretty_print(table.etree))

    def test_create_table_with_two_binders(self,):
        self.binder.addInput(self.key)
        self.binder.addFunction('', from_file='tests_data/jscode.js')
        self.table_desc['bindings'] = [self.binder, self.binder_insert]
        table = Table(**self.table_desc)
        logging.debug(self.xml_pretty_print(table.etree))
        table.save(name='mytable', path='tests_data')
        self.assertEqual(os.path.isfile('tests_data/mytable.xml'),True)
        logging.debug(self.xml_pretty_print(table.etree))

    def test_add_function_table(self):
        logging.debug(self.xml_pretty_print(self.table.etree))
        bf = BinderFunction('concat', inputs=[self.key, self.key2])
        bf.addFunction('', from_file='tests_data/jscode.js')
        self.table.addBinder(bf)
        #self.assertEquals(self.table.addFunction('', from_file='tests_data/jscode.js'),True)
        logging.debug(self.xml_pretty_print(self.table.etree))

    def test_create_function_with_func_code(self):
        logging.debug(self.xml_pretty_print(self.table.etree))
        bf = BinderFunction('concat', func_code='console.log("hello moron !!!")')
        logging.debug(self.xml_pretty_print(bf.etree))

    def test_create_function_with_func_file(self):
        logging.debug(self.xml_pretty_print(self.table.etree))
        bf = BinderFunction('concat', func_file='tests_data/jscode.js')
        logging.debug(self.xml_pretty_print(bf.etree))

    def test_remove_function_table(self,):
        logging.debug(self.xml_pretty_print(self.table.etree))
        self.assertEquals(self.table.addFunction('', from_file='tests_data/jscode.js'),True)
        logging.debug(self.xml_pretty_print(self.table.etree))
        self.assertEquals(self.table.removeFunction(),True)
        logging.debug(self.xml_pretty_print(self.table.etree))

    def test_baseinput_to_xml(self,):
        i = BaseInput('key','name','xs:string', 'path', required=True, default='josh', private=True, maxBatchItems=10)
        logging.debug(self.xml_pretty_print(i.etree))

    def test_inputvalue(self,):
        v = InputValue('content', 'xs:string', 'variable', required=True)
        logging.debug(self.xml_pretty_print(v.etree))

    def tearUp(self):
        os.path.unlink('tests_data/mytest.xml')
        os.path.unlink('tests_data/toto.xml')

if '__main__' == __name__:
    unittest.main()

<commit_msg>doing it like @unpairestgoog :smiley:<commit_after>import os, logging, time
import pdb
import unittest
from xml.dom import minidom
from xml.etree import cElementTree as xtree

from myql import MYQL
from myql.contrib.auth import YOAuth

from myql.contrib.table import Table
from myql.contrib.table import Base, BaseInput
from myql.contrib.table import Binder, BinderFunction, InputKey, InputValue, PagingPage, PagingUrl, PagingOffset

import readline, rlcompleter
readline.parse_and_bind('tab: complete')

logging.basicConfig(level=logging.DEBUG,format="[%(asctime)s %(levelname)s] [%(name)s.%(module)s.%(funcName)s] %(message)s \n")
logging.getLogger(__name__)

class TestOAuth(unittest.TestCase):

    def setUp(self,):
        pass

    def tearUp(self,):
        pass

    def test_get_guid(self,):
        oauth = YOAuth(None, None, from_file='credentials.json')
        yql = MYQL(format='json', oauth=oauth)
        response = yql.getGUID('josue_brunel')
        logging.debug(response.content)
        self.assertEquals(response.status_code,200)

    def test_yahoo_fantasy_sport(self,):
        oauth = YOAuth(None, None, from_file='credentials.json')
        yql = MYQL(format='json', oauth=oauth)
        teams = ('mlb.l.1328.t.1','mlb.l.1328.t.2')
        year = '2015-05-05'
        for team in teams:
            #response = yql.rawQuery("SELECT * FROM fantasysports.teams.roster WHERE team_key = '{0}'  AND date = '{1}' ".format(team, year))
            response = yql.select('fantasysports.teams.roster').where(['team_key','=',team],['date','=',year])
            if not response.status_code == 200:
                return False

            data = response.json()
            current_team = data['query']['results']['team']
            print current_team['team_id'],current_team['name'],current_team['number_of_trades'],current_team['number_of_moves']

class TestTable(unittest.TestCase):

    def setUp(self,):
        self.table_desc = {
            'name': 'mytest',
            'author': 'josuebrunel',
            'apiKeyURL': 'http://josuebrunel.org/api',
            'documentationURL': 'http://josuebrunel.org/doc.html',
            'sampleQuery': ['SELECT * FROM mytable', 'SELECT name FROM mytable WHERE id="345"','DELETE FROM mytable WHERE id="345"'],
        }

        self.table = Table(**self.table_desc)

        self.binder_desc = {
            'name': 'select',
            'itemPath': 'products.product',
            'produces': 'xml'
        }

        self.binder = Binder(**self.binder_desc)
        self.binder_insert = Binder('insert','products.product','json')

        self.key_desc = {
            'id': 'artist',
            'type': 'xs:string',
            'paramType': 'path'
        }

        self.key = InputKey(**self.key_desc)
        self.key2 = InputKey(id='song', type='xs:string', paramType='path', required='true')

        start= {'id': 'ItemPage', 'default': '1'}
        pageSize= {'id':'Count' ,'max':'25'}
        total= {'default': '10'}
        self.paging = PagingPage(start, pageSize, total)

    def xml_pretty_print(self, data):
        """Pretty logging.debug xml data
        """
        raw_string = xtree.tostring(data, 'utf-8')
        parsed_string = minidom.parseString(raw_string)
        return parsed_string.toprettyxml(indent='\t')

    def test_add_binder(self,):
        self.assertEqual(self.table.addBinder(self.binder),True)
        logging.debug(self.xml_pretty_print(self.table.etree))

    def test_remove_binder(self,):
        self.binder.addInput(self.key)
        self.binder_insert.addInput(self.key)
        self.binder.addFunction('', from_file='tests_data/jscode.js')
        self.binder_insert.addFunction("console.log('hello this is an insert function'); ")
        self.table.addBinder(self.binder)
        self.table.addBinder(self.binder_insert)
        self.table.save(name='before', path='tests_data')
        self.assertEqual(os.path.isfile('tests_data/before.xml'),True)
        self.table.removeBinder('select')
        self.table.save(name='after', path='tests_data')
        self.assertEqual(os.path.isfile('tests_data/after.xml'),True)

    def test_add_input_to_binder(self,):
        logging.debug(self.xml_pretty_print(self.binder.etree))
        self.assertEqual(self.binder.addInput(self.key),True)
        logging.debug(self.xml_pretty_print(self.binder.etree))

    def test_remove_input(self,):
        logging.debug(self.xml_pretty_print(self.binder.etree))
        self.assertEqual(self.binder.addInput(self.key),True)
        logging.debug(self.xml_pretty_print(self.binder.etree))
        self.assertEqual(self.binder.addInput(self.key2),True)
        logging.debug(self.xml_pretty_print(self.binder.etree))
        self.assertEquals(self.binder.removeInput(key_id='artist'),True)
        logging.debug(self.xml_pretty_print(self.binder.etree))

    def test_add_function_from_file(self,):
        logging.debug(self.xml_pretty_print(self.binder.etree))
        self.assertEqual(self.binder.addFunction('', from_file='tests_data/jscode.js'),True)
        logging.debug(self.xml_pretty_print(self.binder.etree))

    def test_remove_function(self,):
        logging.debug(self.xml_pretty_print(self.binder.etree))
        self.assertEqual(self.binder.addFunction('', from_file='tests_data/jscode.js'),True)
        logging.debug(self.xml_pretty_print(self.binder.etree))
        self.assertEqual(self.binder.removeFunction(), True)
        logging.debug(self.xml_pretty_print(self.binder.etree))

    def test_add_paging(self,):
        logging.debug(self.xml_pretty_print(self.binder.etree))
        self.assertEquals(self.binder.addPaging(self.paging), True)
        logging.debug(self.xml_pretty_print(self.binder.etree))

    def test_create_binder_with_paging(self,):
        start= {'id': 'ItemPage', 'default': '1'}
        pageSize= {'id':'Count' ,'max':'25'}
        total= {'default': '10'}
        paging = PagingPage(start, pageSize, total)
        logging.debug(self.xml_pretty_print(paging.etree))
        self.binder_desc['paging']=paging
        logging.debug(self.binder_desc)
        binder = Binder(**self.binder_desc)
        self.assertNotEqual(binder.paging,None)
        logging.debug(self.xml_pretty_print(binder.etree))

    def test_create_binder_with_offset_paging(self,):
        start= {'id': 'ItemPage', 'default': '1'}
        pageSize= {'id':'Count' ,'max':'25'}
        total= {'default': '10'}
        paging = PagingOffset(True,  start, pageSize, total)
        logging.debug(self.xml_pretty_print(paging.etree))
        self.binder_desc['paging']=paging
        logging.debug(self.binder_desc)
        binder = Binder(**self.binder_desc)
        self.assertNotEqual(binder.paging,None)
        logging.debug(self.xml_pretty_print(binder.etree))

    def test_create_binder_with_url_paging(self,):
        nextpage = {'path': 'ysearchresponse.nextpage'}
        paging = PagingUrl(nextpage)
        logging.debug(self.xml_pretty_print(paging.etree))
        self.binder_desc['paging']=paging
        logging.debug(self.binder_desc)
        binder = Binder(**self.binder_desc)
        self.assertNotEqual(binder.paging,None)
        logging.debug(self.xml_pretty_print(binder.etree))

    def test_remove_paging(self,):
        logging.debug(self.xml_pretty_print(self.binder.etree))
        self.assertEquals(self.binder.addPaging(self.paging), True)
        logging.debug(self.xml_pretty_print(self.binder.etree))
        self.assertEqual(self.binder.removePaging(), True)
        logging.debug(self.xml_pretty_print(self.binder.etree))

    def test_create_binder_with_urls(self,):
        url = 'http://josuebrunel.org/service/v1'
        url2 = 'http://josuebrunel.org/service/v1/?name=lol'
        self.binder_desc['urls'] = [url, url2]
        binder = Binder(**self.binder_desc)
        logging.debug(self.xml_pretty_print(binder.etree))
        self.assertEquals(self.binder.addUrl(url), True)
        logging.debug(self.xml_pretty_print(self.binder.etree))

    def test_add_url(self,):
        url = 'http://josuebrunel.org/service.js'
        logging.debug(self.xml_pretty_print(self.binder.etree))
        self.assertEquals(self.binder.addUrl(url), True)
        logging.debug(self.xml_pretty_print(self.binder.etree))

    def test_remove_url(self,):
        url = 'http://josuebrunel.org/service.js'
        url2 = 'http://google.com'
        logging.debug(self.xml_pretty_print(self.binder.etree))
        self.assertEquals(self.binder.addUrl(url), True)
        logging.debug(self.xml_pretty_print(self.binder.etree))
        self.assertEquals(self.binder.addUrl(url2), True)
        logging.debug(self.xml_pretty_print(self.binder.etree))
        self.assertEquals(self.binder.removeUrl(url), True)
        logging.debug(self.xml_pretty_print(self.binder.etree))

    def test_save_file(self,):
        self.table.save()
        self.assertEquals(os.path.isfile('mytest.xml'),True)

    def test_save_with_another_name(self):
        name = "tests_data/toto"
        self.table.save(name)
        self.assertEquals(os.path.isfile(name+'.xml'),True)

    def test_save_to_different_location(self,):
        fname = "titi"
        path = 'tests_data'
        name = os.path.join(path,fname)
        self.table.save(name=fname, path=path)
        self.assertEquals(os.path.isfile(name+'.xml'),True)

    def test_create_table(self,):
        self.binder.addInput(self.key)
        self.binder.addFunction('', from_file='tests_data/jscode.js')
        logging.debug(self.xml_pretty_print(self.table.etree))
        self.table.addBinder(self.binder)
        self.table.save(name='mytable', path='tests_data')
        self.assertEqual(os.path.isfile('tests_data/mytable.xml'),True)
        logging.debug(self.xml_pretty_print(self.table.etree))

    def test_create_table_and_add_two_binders(self,):
        self.binder.addInput(self.key)
        self.binder_insert.addInput(self.key)
        self.binder.addFunction('', from_file='tests_data/jscode.js')
        self.binder_insert.addFunction("console.log('hello this is an insert function'); ")
        logging.debug(self.xml_pretty_print(self.table.etree))
        self.table.addBinder(self.binder)
        logging.debug(self.xml_pretty_print(self.table.etree))
        self.table.addBinder(self.binder_insert)
        self.table.save(name='mytable', path='tests_data')
        self.assertEqual(os.path.isfile('tests_data/mytable.xml'),True)
        logging.debug(self.xml_pretty_print(self.table.etree))

    def test_create_table_with_binder(self,):
        self.binder.addInput(self.key)
        self.binder.addFunction('', from_file='tests_data/jscode.js')
        self.table_desc['bindings'] = [self.binder]
        table = Table(**self.table_desc)
        logging.debug(self.xml_pretty_print(table.etree))
        table.save(name='mytable', path='tests_data')
        self.assertEqual(os.path.isfile('tests_data/mytable.xml'),True)
        logging.debug(self.xml_pretty_print(table.etree))

    def test_create_table_with_two_binders(self,):
        self.binder.addInput(self.key)
        self.binder.addFunction('', from_file='tests_data/jscode.js')
        self.table_desc['bindings'] = [self.binder, self.binder_insert]
        table = Table(**self.table_desc)
        logging.debug(self.xml_pretty_print(table.etree))
        table.save(name='mytable', path='tests_data')
        self.assertEqual(os.path.isfile('tests_data/mytable.xml'),True)
        logging.debug(self.xml_pretty_print(table.etree))

    def test_add_function_table(self):
        logging.debug(self.xml_pretty_print(self.table.etree))
        bf = BinderFunction('concat', inputs=[self.key, self.key2])
        bf.addFunction('', from_file='tests_data/jscode.js')
        self.table.addBinder(bf)
        #self.assertEquals(self.table.addFunction('', from_file='tests_data/jscode.js'),True)
        logging.debug(self.xml_pretty_print(self.table.etree))

    def test_create_function_with_func_code(self):
        logging.debug(self.xml_pretty_print(self.table.etree))
        bf = BinderFunction('concat', func_code='console.log("hello moron !!!")')
        logging.debug(self.xml_pretty_print(bf.etree))

    def test_create_function_with_func_file(self):
        logging.debug(self.xml_pretty_print(self.table.etree))
        bf = BinderFunction('concat', func_file='tests_data/jscode.js')
        logging.debug(self.xml_pretty_print(bf.etree))

    def test_remove_function_table(self,):
        logging.debug(self.xml_pretty_print(self.table.etree))
        self.assertEquals(self.table.addFunction('', from_file='tests_data/jscode.js'),True)
        logging.debug(self.xml_pretty_print(self.table.etree))
        self.assertEquals(self.table.removeFunction(),True)
        logging.debug(self.xml_pretty_print(self.table.etree))

    def test_baseinput_to_xml(self,):
        i = BaseInput('key','name','xs:string', 'path', required=True, default='josh', private=True, maxBatchItems=10)
        logging.debug(self.xml_pretty_print(i.etree))

    def test_inputvalue(self,):
        v = InputValue('content', 'xs:string', 'variable', required=True)
        logging.debug(self.xml_pretty_print(v.etree))

    def tearUp(self):
        os.path.unlink('tests_data/mytest.xml')
        os.path.unlink('tests_data/toto.xml')

if '__main__' == __name__:
    unittest.main()

<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import

from django.test import TestCase

from tags.models import Tag

from .models import Food

class TestFoodModel(TestCase):

    def test_create_food(self):
        food = Food.objects.create(
            name="nacho",
            tags="tortilla chips")

        self.assertTrue(food)
        self.assertEqual(Tag.objects.all()[0].name, "tortilla chips")
        self.assertEqual(Tag.objects.all()[0].slug, "tortilla-chips")

    def test_create_two_tags(self):
        food = Food.objects.create(
            name="nacho",
            tags="tortilla chips, salsa")
        tags = Tag.objects.all()

        self.assertTrue(food)
        self.assertEqual(len(tags), 2)
        self.assertEqual(tags[1].slug, "tortilla-chips")
        self.assertEqual(tags[0].slug, "salsa")
<commit_msg>remove assert valide order return query set on python 3.3<commit_after># -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import

from django.test import TestCase

from tags.models import Tag

from .models import Food

class TestFoodModel(TestCase):

    def test_create_food(self):
        food = Food.objects.create(
            name="nacho",
            tags="tortilla chips")

        self.assertTrue(food)
        self.assertEqual(Tag.objects.all()[0].name, "tortilla chips")
        self.assertEqual(Tag.objects.all()[0].slug, "tortilla-chips")

    def test_create_two_tags(self):
        food = Food.objects.create(
            name="nacho",
            tags="tortilla chips, salsa")
        tags = Tag.objects.all()

        self.assertTrue(food)
        self.assertEqual(len(tags), 2)
<|endoftext|>


<commit_before>#!/usr/bin/env python3
import os
import sys

import unittest2

sys.path.append(os.path.abspath('..'))
os.chdir('..')

class TestURLMethods(unittest2.TestCase):
    def test_is_subdomain(self):
        from pajbot.modules.linkchecker import is_subdomain

        self.assertTrue(is_subdomain('pajlada.se', 'pajlada.se'))
        self.assertTrue(is_subdomain('test.pajlada.se', 'pajlada.se'))

        self.assertFalse(is_subdomain('test.pajlada.se', 'pajlada.com'))
        self.assertFalse(is_subdomain('kastaren.com', 'roleplayer.se'))
        self.assertFalse(is_subdomain('foo.bar.com', 'foobar.com'))

    def test_is_subpath(self):
        from pajbot.modules.linkchecker import is_subpath

        self.assertTrue(is_subpath('/foo/', '/foo/'))
        self.assertTrue(is_subpath('/foo/bar', '/foo/'))

        self.assertFalse(is_subpath('/foo/', '/bar/'))
        self.assertFalse(is_subpath('/foo/', '/foo/bar'))

    def test_is_same_url(self):
        from pajbot.modules.linkchecker import is_same_url, Url

        self.assertTrue(is_same_url(Url('pajlada.se'), Url('pajlada.se/')))

        self.assertFalse(is_same_url(Url('pajlada.com'), Url('pajlada.se')))
        self.assertFalse(is_same_url(Url('pajlada.com'), Url('pajlada.com/abc')))

    def test_find_unique_urls(self):
        from pajbot.modules.linkchecker import find_unique_urls
        from pajbot.bot import Bot
        import re

        regex = re.compile(Bot.url_regex_str, re.IGNORECASE)

        self.assertEqual(find_unique_urls(regex, 'pajlada.se test http://pajlada.se'), {'http://pajlada.se'})
        self.assertEqual(find_unique_urls(regex, 'pajlada.se pajlada.com foobar.se'), {'http://pajlada.se', 'http://pajlada.com', 'http://foobar.se'})
        self.assertEqual(find_unique_urls(regex, 'foobar.com foobar.com'), {'http://foobar.com'})
        self.assertEqual(find_unique_urls(regex, 'foobar.com foobar.se'), {'http://foobar.com', 'http://foobar.se'})
        self.assertEqual(find_unique_urls(regex, 'www.foobar.com foobar.se'), {'http://www.foobar.com', 'http://foobar.se'})

        # TODO: Edge case, this behaviour should probably be changed. These URLs should be considered the same.
        # Use is_same_url method?
        self.assertEqual(find_unique_urls(regex, 'pajlada.se/ pajlada.se'), {'http://pajlada.se/', 'http://pajlada.se'})

        # TODO: The protocol of a URL is entirely thrown away, this behaviour should probably be changed.
        self.assertEqual(find_unique_urls(regex, 'https://pajlada.se/ https://pajlada.se'), {'https://pajlada.se/', 'https://pajlada.se'})

class ActionsTester(unittest2.TestCase):
    def setUp(self):
        from pajbot.bot import Bot
        from pajbot.utils import load_config
        import datetime

        config = load_config('config.ini')
        args = Bot.parse_args()
        self.pajbot = Bot(config, args)
        self.source = self.pajbot.users['omgthisuserdoesnotexist123']
        self.source.username_raw = 'OmgthisuserdoesnotexiSt123'
        self.source.points = 142
        self.source.last_seen = datetime.datetime.strptime('17:01:42', '%H:%M:%S')

    def test_message_action_parse(self):
        from pajbot.models.action import SayAction  # noqa
        import pytz
        import datetime

        values = [  # noqa
                {
                    'message': 'hi',
                    'num_argument_subs': 0,
                    'num_subs': 0,
                    'arguments': '',
                    'result': 'hi',
                }, {
                    'message': 'Hello $(source:username)!',
                    'num_argument_subs': 0,
                    'num_subs': 1,
                    'arguments': '',
                    'result': 'Hello omgthisuserdoesnotexist123!',
                }, {
                    'message': 'Testing $(1)',
                    'num_argument_subs': 1,
                    'num_subs': 0,
                    'arguments': 'a b c',
                    'result': 'Testing a',
                }, {
                    'message': 'Testing $(1) $(2)',
                    'num_argument_subs': 2,
                    'num_subs': 0,
                    'arguments': '',
                    'result': 'Testing  ',
                }, {
                    'message': 'Testing $(1) $(2) $(1)',
                    'num_argument_subs': 2,
                    'num_subs': 0,
                    'arguments': '',
                    'result': 'Testing   ',
                }, {
                    'message': '$(user;1:username_raw) has $(user;1:points) points. 1',
                    'num_argument_subs': 0,
                    'num_subs': 2,
                    'arguments': 'omgthisuserdoesnotexist123',
                    'result': 'OmgthisuserdoesnotexiSt123 has 142 points. 1',
                }, {
                    'message': '$(user;1:username_raw|lower) has $(user;1:points) points. 2',
                    'num_argument_subs': 0,
                    'num_subs': 2,
                    'arguments': 'omgthisuserdoesnotexist123',
                    'result': 'omgthisuserdoesnotexist123 has 142 points. 2',
                }, {
                    'message': '$(user;1:username_raw) has $(user;1:points) points. 3',
                    'num_argument_subs': 0,
                    'num_subs': 2,
                    'arguments': 'OmgthisuserdoesnotExiSt123',
                    'result': 'OmgthisuserdoesnotexiSt123 has 142 points. 3',
                }, {
                    'message': '$(user;1:username_raw|lower) was last seen $(source:last_seen|strftime(%H:%M:%S)).',
                    'num_argument_subs': 0,
                    'num_subs': 2,
                    'arguments': 'omgthisuserdoesnotexist123',
                    'result': 'omgthisuserdoesnotexist123 was last seen 18:01:42.',
                }, {
                    'message': 'Time in Sweden: $(time:Europe/Stockholm)',
                    'num_argument_subs': 0,
                    'num_subs': 1,
                    'arguments': 'omgthisuserdoesnotexist123',
                    'result': 'Time in Sweden: {}'.format(datetime.datetime.now(pytz.timezone('Europe/Stockholm')).strftime(self.pajbot.date_fmt)),
                }, {
                    'message': 'BEFORE $(if:$(1),"YES","NO") AFTER',
                    'num_argument_subs': 1,
                    'num_subs': 1,
                    'arguments': 'omgthisuserdoesnotexist123',
                    'result': 'BEFORE YES AFTER',
                }, {
                    'message': 'BEFORE $(if:$(1),"YES","NO") AFTER',
                    'num_argument_subs': 1,
                    'num_subs': 1,
                    'arguments': '',
                    'result': 'BEFORE NO AFTER',
                }, {
                    'message': 'BEFORE $(source:username|lower|upper) AFTER',
                    'num_argument_subs': 0,
                    'num_subs': 1,
                    'arguments': '',
                    'result': 'BEFORE OMGTHISUSERDOESNOTEXIST123 AFTER',
                },
                ]

        """
        for data in values:
            action = SayAction(data['message'], self.pajbot)
            response = action.get_response(self.pajbot, {'source': self.source, 'message': data['arguments']})
            self.assertEqual(len(action.argument_subs), data['num_argument_subs'], 'Wrong amount of argument substitutions for "{0}"'.format(data['message']))
            self.assertEqual(len(action.subs), data['num_subs'], 'Wrong amount of substitutions for "{0}"'.format(data['message']))
            self.assertEqual(response, data['result'], 'Got output "{}", expected "{}"'.format(response, data['result']))
            """

class TestCleanUpMessage(unittest2.TestCase):
    def test_clean_up(self):
        import pajbot.bot

        self.assertEqual('', pajbot.bot.clean_up_message(''))
        self.assertEqual('', pajbot.bot.clean_up_message('  '))
        self.assertEqual('', pajbot.bot.clean_up_message(' '))

        self.assertEqual('. .timeout pajlada 5', pajbot.bot.clean_up_message('.timeout pajlada 5'))
        self.assertEqual('. /timeout pajlada 5', pajbot.bot.clean_up_message('/timeout pajlada 5'))
        self.assertEqual('. .timeout pajlada 5', pajbot.bot.clean_up_message('   .timeout pajlada 5'))
        self.assertEqual('. /timeout pajlada 5', pajbot.bot.clean_up_message(' /timeout pajlada 5'))
        self.assertEqual('.me xD', pajbot.bot.clean_up_message('.me xD'))
        self.assertEqual('/me xD', pajbot.bot.clean_up_message('/me xD'))
        self.assertEqual('/me xD', pajbot.bot.clean_up_message('   /me xD'))
        self.assertEqual('.me xD', pajbot.bot.clean_up_message('   .me xD'))
        self.assertEqual('asd', pajbot.bot.clean_up_message('asd'))
        self.assertEqual('asd', pajbot.bot.clean_up_message('    asd'))
        for prefix in ['!', '$', '-', '<']:
            self.assertEqual('\uE000{}ping'.format(prefix), pajbot.bot.clean_up_message('{}ping'.format(prefix)))
            self.assertEqual('/me \uE000{}ping'.format(prefix), pajbot.bot.clean_up_message('/me {}ping'.format(prefix)))
            self.assertEqual('.me \uE000{}ping'.format(prefix), pajbot.bot.clean_up_message('.me {}ping'.format(prefix)))
            self.assertEqual('\uE000{}ping'.format(prefix), pajbot.bot.clean_up_message('    {}ping'.format(prefix)))
            self.assertEqual('.me \uE000{}ping'.format(prefix), pajbot.bot.clean_up_message('.me    {}ping'.format(prefix)))
            self.assertEqual('.me \uE000{}ping'.format(prefix), pajbot.bot.clean_up_message(' .me    {}ping'.format(prefix)))
            self.assertEqual('/me \uE000{}ping'.format(prefix), pajbot.bot.clean_up_message('/me    {}ping'.format(prefix)))
            self.assertEqual('/me \uE000{}ping'.format(prefix), pajbot.bot.clean_up_message(' /me    {}ping'.format(prefix)))

            self.assertEqual('\uE000{}'.format(prefix), pajbot.bot.clean_up_message('{}'.format(prefix)))
            self.assertEqual('/me \uE000{}'.format(prefix), pajbot.bot.clean_up_message('/me {}'.format(prefix)))
            self.assertEqual('.me \uE000{}'.format(prefix), pajbot.bot.clean_up_message('.me {}'.format(prefix)))
            self.assertEqual('\uE000{}'.format(prefix), pajbot.bot.clean_up_message('    {}'.format(prefix)))
            self.assertEqual('.me \uE000{}'.format(prefix), pajbot.bot.clean_up_message('.me    {}'.format(prefix)))
            self.assertEqual('.me \uE000{}'.format(prefix), pajbot.bot.clean_up_message(' .me    {}'.format(prefix)))
            self.assertEqual('/me \uE000{}'.format(prefix), pajbot.bot.clean_up_message('/me    {}'.format(prefix)))
            self.assertEqual('/me \uE000{}'.format(prefix), pajbot.bot.clean_up_message(' /me    {}'.format(prefix)))

if __name__ == '__main__':
    unittest2.main()
<commit_msg>oops fix in tests<commit_after>#!/usr/bin/env python3
import os
import sys

import unittest2

sys.path.append(os.path.abspath('..'))
os.chdir('..')

class TestURLMethods(unittest2.TestCase):
    def test_is_subdomain(self):
        from pajbot.modules.linkchecker import is_subdomain

        self.assertTrue(is_subdomain('pajlada.se', 'pajlada.se'))
        self.assertTrue(is_subdomain('test.pajlada.se', 'pajlada.se'))

        self.assertFalse(is_subdomain('test.pajlada.se', 'pajlada.com'))
        self.assertFalse(is_subdomain('kastaren.com', 'roleplayer.se'))
        self.assertFalse(is_subdomain('foo.bar.com', 'foobar.com'))

    def test_is_subpath(self):
        from pajbot.modules.linkchecker import is_subpath

        self.assertTrue(is_subpath('/foo/', '/foo/'))
        self.assertTrue(is_subpath('/foo/bar', '/foo/'))

        self.assertFalse(is_subpath('/foo/', '/bar/'))
        self.assertFalse(is_subpath('/foo/', '/foo/bar'))

    def test_is_same_url(self):
        from pajbot.modules.linkchecker import is_same_url, Url

        self.assertTrue(is_same_url(Url('pajlada.se'), Url('pajlada.se/')))

        self.assertFalse(is_same_url(Url('pajlada.com'), Url('pajlada.se')))
        self.assertFalse(is_same_url(Url('pajlada.com'), Url('pajlada.com/abc')))

    def test_find_unique_urls(self):
        from pajbot.modules.linkchecker import find_unique_urls
        from pajbot.bot import Bot
        import re

        regex = re.compile(Bot.url_regex_str, re.IGNORECASE)

        self.assertEqual(find_unique_urls(regex, 'pajlada.se test http://pajlada.se'), {'http://pajlada.se'})
        self.assertEqual(find_unique_urls(regex, 'pajlada.se pajlada.com foobar.se'), {'http://pajlada.se', 'http://pajlada.com', 'http://foobar.se'})
        self.assertEqual(find_unique_urls(regex, 'foobar.com foobar.com'), {'http://foobar.com'})
        self.assertEqual(find_unique_urls(regex, 'foobar.com foobar.se'), {'http://foobar.com', 'http://foobar.se'})
        self.assertEqual(find_unique_urls(regex, 'www.foobar.com foobar.se'), {'http://www.foobar.com', 'http://foobar.se'})

        # TODO: Edge case, this behaviour should probably be changed. These URLs should be considered the same.
        # Use is_same_url method?
        self.assertEqual(find_unique_urls(regex, 'pajlada.se/ pajlada.se'), {'http://pajlada.se/', 'http://pajlada.se'})

        # TODO: The protocol of a URL is entirely thrown away, this behaviour should probably be changed.
        self.assertEqual(find_unique_urls(regex, 'https://pajlada.se/ https://pajlada.se'), {'https://pajlada.se/', 'https://pajlada.se'})

class ActionsTester(unittest2.TestCase):
    def setUp(self):
        from pajbot.bot import Bot
        from pajbot.utils import load_config
        import datetime

        config = load_config('config.ini')
        args = Bot.parse_args()
        self.pajbot = Bot(config, args)
        self.source = self.pajbot.users['omgthisuserdoesnotexist123']
        self.source.username_raw = 'OmgthisuserdoesnotexiSt123'
        self.source.points = 142
        self.source.last_seen = datetime.datetime.strptime('17:01:42', '%H:%M:%S')

    def test_message_action_parse(self):
        from pajbot.models.action import SayAction  # noqa
        import pytz
        import datetime

        values = [  # noqa
                {
                    'message': 'hi',
                    'num_argument_subs': 0,
                    'num_subs': 0,
                    'arguments': '',
                    'result': 'hi',
                }, {
                    'message': 'Hello $(source:username)!',
                    'num_argument_subs': 0,
                    'num_subs': 1,
                    'arguments': '',
                    'result': 'Hello omgthisuserdoesnotexist123!',
                }, {
                    'message': 'Testing $(1)',
                    'num_argument_subs': 1,
                    'num_subs': 0,
                    'arguments': 'a b c',
                    'result': 'Testing a',
                }, {
                    'message': 'Testing $(1) $(2)',
                    'num_argument_subs': 2,
                    'num_subs': 0,
                    'arguments': '',
                    'result': 'Testing  ',
                }, {
                    'message': 'Testing $(1) $(2) $(1)',
                    'num_argument_subs': 2,
                    'num_subs': 0,
                    'arguments': '',
                    'result': 'Testing   ',
                }, {
                    'message': '$(user;1:username_raw) has $(user;1:points) points. 1',
                    'num_argument_subs': 0,
                    'num_subs': 2,
                    'arguments': 'omgthisuserdoesnotexist123',
                    'result': 'OmgthisuserdoesnotexiSt123 has 142 points. 1',
                }, {
                    'message': '$(user;1:username_raw|lower) has $(user;1:points) points. 2',
                    'num_argument_subs': 0,
                    'num_subs': 2,
                    'arguments': 'omgthisuserdoesnotexist123',
                    'result': 'omgthisuserdoesnotexist123 has 142 points. 2',
                }, {
                    'message': '$(user;1:username_raw) has $(user;1:points) points. 3',
                    'num_argument_subs': 0,
                    'num_subs': 2,
                    'arguments': 'OmgthisuserdoesnotExiSt123',
                    'result': 'OmgthisuserdoesnotexiSt123 has 142 points. 3',
                }, {
                    'message': '$(user;1:username_raw|lower) was last seen $(source:last_seen|strftime(%H:%M:%S)).',
                    'num_argument_subs': 0,
                    'num_subs': 2,
                    'arguments': 'omgthisuserdoesnotexist123',
                    'result': 'omgthisuserdoesnotexist123 was last seen 18:01:42.',
                }, {
                    'message': 'Time in Sweden: $(time:Europe/Stockholm)',
                    'num_argument_subs': 0,
                    'num_subs': 1,
                    'arguments': 'omgthisuserdoesnotexist123',
                    'result': 'Time in Sweden: {}'.format(datetime.datetime.now(pytz.timezone('Europe/Stockholm')).strftime(self.pajbot.date_fmt)),
                }, {
                    'message': 'BEFORE $(if:$(1),"YES","NO") AFTER',
                    'num_argument_subs': 1,
                    'num_subs': 1,
                    'arguments': 'omgthisuserdoesnotexist123',
                    'result': 'BEFORE YES AFTER',
                }, {
                    'message': 'BEFORE $(if:$(1),"YES","NO") AFTER',
                    'num_argument_subs': 1,
                    'num_subs': 1,
                    'arguments': '',
                    'result': 'BEFORE NO AFTER',
                }, {
                    'message': 'BEFORE $(source:username|lower|upper) AFTER',
                    'num_argument_subs': 0,
                    'num_subs': 1,
                    'arguments': '',
                    'result': 'BEFORE OMGTHISUSERDOESNOTEXIST123 AFTER',
                },
                ]

        """
        for data in values:
            action = SayAction(data['message'], self.pajbot)
            response = action.get_response(self.pajbot, {'source': self.source, 'message': data['arguments']})
            self.assertEqual(len(action.argument_subs), data['num_argument_subs'], 'Wrong amount of argument substitutions for "{0}"'.format(data['message']))
            self.assertEqual(len(action.subs), data['num_subs'], 'Wrong amount of substitutions for "{0}"'.format(data['message']))
            self.assertEqual(response, data['result'], 'Got output "{}", expected "{}"'.format(response, data['result']))
            """

class TestCleanUpMessage(unittest2.TestCase):
    def test_clean_up(self):
        import pajbot.bot

		self.assertEqual('', '\U000e0000')

        self.assertEqual('', pajbot.bot.clean_up_message(''))
        self.assertEqual('', pajbot.bot.clean_up_message('  '))
        self.assertEqual('', pajbot.bot.clean_up_message(' '))

        self.assertEqual('. .timeout pajlada 5', pajbot.bot.clean_up_message('.timeout pajlada 5'))
        self.assertEqual('. /timeout pajlada 5', pajbot.bot.clean_up_message('/timeout pajlada 5'))
        self.assertEqual('. .timeout pajlada 5', pajbot.bot.clean_up_message('   .timeout pajlada 5'))
        self.assertEqual('. /timeout pajlada 5', pajbot.bot.clean_up_message(' /timeout pajlada 5'))
        self.assertEqual('.me xD', pajbot.bot.clean_up_message('.me xD'))
        self.assertEqual('/me xD', pajbot.bot.clean_up_message('/me xD'))
        self.assertEqual('/me xD', pajbot.bot.clean_up_message('   /me xD'))
        self.assertEqual('.me xD', pajbot.bot.clean_up_message('   .me xD'))
        self.assertEqual('asd', pajbot.bot.clean_up_message('asd'))
        self.assertEqual('asd', pajbot.bot.clean_up_message('    asd'))
        for prefix in ['!', '$', '-', '<']:
            self.assertEqual('\U000e0000{}ping'.format(prefix), pajbot.bot.clean_up_message('{}ping'.format(prefix)))
            self.assertEqual('/me \U000e0000{}ping'.format(prefix), pajbot.bot.clean_up_message('/me {}ping'.format(prefix)))
            self.assertEqual('.me \U000e0000{}ping'.format(prefix), pajbot.bot.clean_up_message('.me {}ping'.format(prefix)))
            self.assertEqual('\U000e0000{}ping'.format(prefix), pajbot.bot.clean_up_message('    {}ping'.format(prefix)))
            self.assertEqual('.me \U000e0000{}ping'.format(prefix), pajbot.bot.clean_up_message('.me    {}ping'.format(prefix)))
            self.assertEqual('.me \U000e0000{}ping'.format(prefix), pajbot.bot.clean_up_message(' .me    {}ping'.format(prefix)))
            self.assertEqual('/me \U000e0000{}ping'.format(prefix), pajbot.bot.clean_up_message('/me    {}ping'.format(prefix)))
            self.assertEqual('/me \U000e0000{}ping'.format(prefix), pajbot.bot.clean_up_message(' /me    {}ping'.format(prefix)))

            self.assertEqual('\U000e0000{}'.format(prefix), pajbot.bot.clean_up_message('{}'.format(prefix)))
            self.assertEqual('/me \U000e0000{}'.format(prefix), pajbot.bot.clean_up_message('/me {}'.format(prefix)))
            self.assertEqual('.me \U000e0000{}'.format(prefix), pajbot.bot.clean_up_message('.me {}'.format(prefix)))
            self.assertEqual('\U000e0000{}'.format(prefix), pajbot.bot.clean_up_message('    {}'.format(prefix)))
            self.assertEqual('.me \U000e0000{}'.format(prefix), pajbot.bot.clean_up_message('.me    {}'.format(prefix)))
            self.assertEqual('.me \U000e0000{}'.format(prefix), pajbot.bot.clean_up_message(' .me    {}'.format(prefix)))
            self.assertEqual('/me \U000e0000{}'.format(prefix), pajbot.bot.clean_up_message('/me    {}'.format(prefix)))
            self.assertEqual('/me \U000e0000{}'.format(prefix), pajbot.bot.clean_up_message(' /me    {}'.format(prefix)))

if __name__ == '__main__':
    unittest2.main()
<|endoftext|>


<commit_before>#!/usr/bin/python
# -*- coding: utf-8 -*-

from io import open
import json
import unittest
from collections import namedtuple
# Path hack.
import sys, os
sys.path.insert(0, os.path.abspath('..'))

from src import model

class ModuleParsingTestCase(unittest.TestCase):
    """ Here we only test if the parsing works right and ends up with a correct module object.
        Does not treat the generation of IMS or EDX archive """

    def setUp(self):
        with open('tests.config.json', encoding='utf-8') as jsf:
            self.control_module = json.load(jsf, object_hook=lambda d: namedtuple('X', d.keys())(*d.values()))

        with open("module_test.md", encoding='utf-8') as sample_file:
            self.sample_object = model.Module(sample_file, "tests", "http://culturenumerique.univ-lille3.fr")
            self.sample_object.toHTML(False)
            outfile = open('sample.config.json', 'wb')
            outfile.write(self.sample_object.toJson())
            self.sample_module = json.loads(self.sample_object.toJson(), object_hook=lambda d: namedtuple('X', d.keys())(*d.values()))

    def check_number_of_sections(self):
        """for  sample module 'sample_m', match the number of sections with control module 'control_m'"""
        return len(self.control_module.sections) == len(self.sample_module.sections)

    def check_number_of_subsections(control_s, sample_s):
        """for  sample section 'sample_s', match the number of subsections with control section 'control_s'"""
        pass

    def check_subsections_split_and_types(self):
        """for  sample section 'sample_s', match the number of subsections with control section 'control_s'"""
        for i,sec in enumerate(self.sample_module.sections):
            for j,sub in enumerate(sec.subsections):
                control_sub = self.control_module.sections[i].subsections[j]
                if sub.folder != control_sub.folder:
                    return False
                if sub.src != control_sub.src:
                    return False
        return True

    def runTest(self):
        #check number of sections
        self.assertTrue(self.check_number_of_sections(), "Not the same number of sections")
        #check subsections are splited right and with right types
        self.assertTrue(self.check_subsections_split_and_types(), "One subsection split or type is not right")
        #Module object exact match
        self.assertEqual(self.control_module, self.sample_module,msg="Module objects do not match")

if __name__ == '__main__':
    unittest.main()

    # def test_config_json(self):
    #     test_json =
    #
    #     self.assertEqual(fun(3), 4)
<commit_msg>keep exceptions in memory to separate different level of checks<commit_after>#!/usr/bin/python
# -*- coding: utf-8 -*-

from io import open
import json
import unittest
from collections import namedtuple
# Path hack.
import sys, os
sys.path.insert(0, os.path.abspath('..'))

from src import model

class ModuleParsingTestCase(unittest.TestCase):
    """ Here we only test if the parsing works right and ends up with a correct module object.
        Does not treat the generation of IMS or EDX archive """

    def setUp(self):
        self.longMessage=True
        with open('tests.config.json', encoding='utf-8') as jsf:
            self.control_module = json.load(jsf, object_hook=lambda d: namedtuple('X', d.keys())(*d.values()))

        with open("module_test.md", encoding='utf-8') as sample_file:
            self.sample_object = model.Module(sample_file, "tests", "http://culturenumerique.univ-lille3.fr")
            self.sample_object.toHTML(False)
            outfile = open('sample.config.json', 'wb')
            outfile.write(self.sample_object.toJson())
            self.sample_module = json.loads(self.sample_object.toJson(), object_hook=lambda d: namedtuple('X', d.keys())(*d.values()))

    def check_number_of_sections(self):
        """for  sample module 'sample_m', match the number of sections with control module 'control_m'"""
        self.assertEqual(len(self.control_module.sections),len(self.sample_module.sections), "Not the same number of sections")
        print("-- Number of sections OK --")

    def check_headers_parsing(self):
        pass

    def check_subsections_split_and_types(self):
        """Loop through all subsections and check types and source split
            we catch and keep each type of exception to separate checks
        """
        typeMatchingError = None
        srcSplitError = None
        for i,sec in enumerate(self.sample_module.sections):
            for j,sub in enumerate(sec.subsections):
                self.assertIsNotNone(self.control_module.sections[i].subsections[j], "actual subsection out of bound for sec[%d].sub[%d]" % (i,j))
                control_sub = self.control_module.sections[i].subsections[j]
                try:
                    self.assertEqual(sub.folder,control_sub.folder, "no matching type for sec[%d].sub[%d]" % (i,j))
                except AssertionError as typeMatchingError:
                    pass
                try:
                    self.assertMultiLineEqual(sub.src,control_sub.src,"src string do not match for sec[%d].sub[%d]" % (i,j))
                except Exception as srcSplitError:
                    pass
        if not typeMatchingError:
            print("-- Subsections types OK --")
        else:
            raise typeMatchingError
        if not srcSplitError:
            print("-- Subsections split OK --")
        else:
            raise srcSplitError

    def runTest(self):
        #check number of sections
        self.check_number_of_sections()
        #check subsections are splited right and with right types
        self.check_subsections_split_and_types()
        #Module object exact match
        self.assertEqual(self.control_module, self.sample_module,msg="Module objects do not match exactly")
        print("-- Exact match OK --")

# Main
if __name__ == '__main__':
    unittest.main(verbosity=1)
<|endoftext|>


<commit_before>import os
import pytest
import tinymongo as tm

# setup the db
db_name = os.path.abspath('./test_db')
try:
    for f in os.listdir(os.path.join('.', db_name)):
        print('removing file ', f)
        os.remove(os.path.join(db_name, f))
except FileNotFoundError:
    pass

try:
    if len(os.listdir(db_name)) == 0:
        os.rmdir(db_name)
except FileNotFoundError:
    pass

tiny_client = tm.TinyMongoClient(db_name)
tiny_database = tiny_client.tinyDatabase
tiny_collection = tiny_database.tinyCollection

@pytest.fixture()
def collection(request):
    # setup the db, clear if necessary
    # todo: the 'drop()' function from pymongo should work in future revisions
    tiny_collection.delete_many({})    # should delete all records in the collection

    # insert 100 integers, strings, floats, booleans, arrays, and objects
    for num in range(100):
        new_obj = {}
        new_obj['count'] = num
        new_obj['countStr'] = str(num)
        new_obj['countFloat'] = float(num) + 0.1
        new_obj['countBool'] = True if num & 1 else False
        new_obj['countArray'] = [num + i for i in range(5)]
        # todo: add object to the db

        tiny_collection.insert_one(new_obj)

    def fin():
        tiny_client.close()

    request.addfinalizer(finalizer=fin)

    return tiny_collection

def test_initialize_db(collection):
    """
    Ensure that the initial db is of the correct size

    :param collection: pytest fixture that returns the collection
    :return:
    """
    c = collection.find({})

    count = 0
    for doc in c:
        count += 1

    assert count == 100
    assert c.count() == 100

def test_greater_than(collection):
    """
    Testing the greater than operator

    :param collection: pytest fixture that returns the collection
    :return:
    """
    c = collection.find({'count': {'$gte': 50}})

    assert c.count() == 50

def test_sort_wrong_input_type(collection):
    """
    Testing the sort method in the positive direction

    :param collection: pytest fixture that returns the collection
    :return:
    """
    c = collection.find()  # find all
    with pytest.raises(ValueError):
        c.sort('count')

def test_sort_positive(collection):
    """
    Testing the sort method in the positive direction

    :param collection: pytest fixture that returns the collection
    :return:
    """
    c = collection.find()  # find all
    c.sort({'count': 1})
    assert c[0]['count'] == 0
    assert c[1]['count'] == 1

def test_sort_negative(collection):
    """
    Testing the sort method in the positive direction

    :param collection: pytest fixture that returns the collection
    :return:
    """
    c = collection.find()  # find all
    c.sort({'count': -1})
    assert c[0]['count'] == 99
    assert c[1]['count'] == 98

def test_has_next(collection):
    """
    Testing hasNext

    :param collection: pytest fixture that returns the collection
    :return:
    """
    c = collection.find().sort({'count': 1})

    assert c.hasNext() is True
    assert c.next()['count'] == 0

def test_not_has_next(collection):
    """
    Testing hasNext when it should be false

    :param collection: pytest fixture that returns the collection
    :return:
    """
    c = collection.find({'count': {'$gte': 98}}).sort({'count': 1})

    assert c.hasNext() is True
    assert c.next()['count'] == 98
    assert c.hasNext() is True
    assert c.next()['count'] == 99
    assert c.hasNext() is False

def test_empty_find(collection):
    """
    Tests 'find' method when empty
    :param collection:
    :return:
    """
    c = collection.find()
    assert c.count() == 100

def test_find_one(collection):
    """
    Testing the retrieval of an item using the 'find_one' method

    :param collection: pytest fixture that returns the collection
    :return:
    """
    c = collection.find_one({'count': 3})

    assert c['countStr'] == '3'

def test_gte_lt(collection):
    """
    Testing the >= and < queries
    :param collection: pytest fixture that returns the collection
    :return:
    """
    c = collection.find({'count': {'$gte': 50, '$lt': 51}})
    assert c.count() == 1
    assert c[0]['countStr'] == '50'

def test_gt_lte(collection):
    """
    Testing the < and >= queries
    :param collection: pytest fixture that returns the collection
    :return:
    """
    c = collection.find({'count': {'$gt': 50, '$lte': 51}})
    assert c.count() == 1
    assert c[0]['countStr'] == '51'

def test_ne(collection):
    """
    Testing the < and >= queries
    :param collection: pytest fixture that returns the collection
    :return:
    """
    c = collection.find({'count': {'$ne': 50}})
    assert c.count() == 99

    for item in c:
        assert item['countStr'] != '50'

def test_update_one_set(collection):
    """
    Testing the update_one method of the collection

    :param collection: pytest fixture that returns the collection
    :return:
    """
    cu = collection.update_one({'count': 3}, {'$set': {'countStr': 'three'}})
    assert cu is True

    c = collection.find_one({'count': 3})
    assert c['countStr'] == 'three'

def test_delete_one(collection):
    """
    Testing the 'delete_one' method

    :param collection: pytest fixture that returns the collection
    :return:
    """
    collection.delete_one({'count': 3})

    c = collection.find({})

    assert c.count() == 99

def test_delete_all(collection):
    """
    Testing the 'delete_many' method to remove all

    :param collection: pytest fixture that returns the collection
    :return:
    """
    collection.delete_many({})

    c = collection.find({})

    assert c.count() == 0

def test_delete_many(collection):
    """
    Testing the 'delete_many' method to remove some items

    :param collection: pytest fixture that returns the collection
    :return:
    """
    collection.delete_many({'count': {'$gte': 50}})

    c = collection.find({})

    assert c.count() == 50

def test_insert_one(collection):
    """
    Testing the 'insert_one' method
    :param collection: pytest fixture that returns the collection
    :return:
    """
    collection.insert_one({'my_object_name': 'my object value', 'count': 1000})

    c = collection.find({})

    assert c.count() == 101
    assert collection.find({'my_object_name': 'my object value'})['count'] == 1000

def test_insert_many(collection):
    """
    Testing the 'insert_many' method
    :param collection: pytest fixture that returns the collection
    :return:
    """
    items = []
    for i in range(10):
        value = 1000 + i
        items.append({'count': value, 'countStr': str(value)})

    collection.insert_many(items)

    c = collection.find({})

    assert c.count() == 110

def test_insert_many_wrong_input(collection):
    """
    Testing the 'insert_many' method with a non-list input
    :param collection: pytest fixture that returns the collection
    :return:
    """
    item = {'my_key': 'my value'}
    with pytest.raises(ValueError):
        collection.insert_many(item)

def test_insert_one_with_list_input(collection):
    """
    Testing the 'insert_one' method with a list input
    :param collection: pytest fixture that returns the collection
    :return:
    """
    with pytest.raises(ValueError):
        collection.insert_one([{'my_object_name': 'my object value', 'count': 1000}])

<commit_msg>Increased test coverage<commit_after>import os
import pytest
import tinymongo as tm

# setup the db
db_name = os.path.abspath('./test_db')
try:
    for f in os.listdir(os.path.join('.', db_name)):
        print('removing file ', f)
        os.remove(os.path.join(db_name, f))
except FileNotFoundError:
    pass

try:
    if len(os.listdir(db_name)) == 0:
        os.rmdir(db_name)
except FileNotFoundError:
    pass

tiny_client = tm.TinyMongoClient(db_name)
tiny_database = tiny_client.tinyDatabase
tiny_collection = tiny_database.tinyCollection

@pytest.fixture()
def collection(request):
    # setup the db, clear if necessary
    # todo: the 'drop()' function from pymongo should work in future revisions
    tiny_collection.delete_many({})    # should delete all records in the collection

    # insert 100 integers, strings, floats, booleans, arrays, and objects
    for num in range(100):
        new_obj = {}
        new_obj['count'] = num
        new_obj['countStr'] = str(num)
        new_obj['countFloat'] = float(num) + 0.1
        new_obj['countBool'] = True if num & 1 else False
        new_obj['countArray'] = [num + i for i in range(5)]
        # todo: add object to the db

        tiny_collection.insert_one(new_obj)

    def fin():
        tiny_client.close()

    request.addfinalizer(finalizer=fin)

    return tiny_collection

def test_initialize_db():
    """
    Ensure that the db can be created, use two clients in order to increase coverage

    :return:
    """
    tiny_client = tm.TinyMongoClient(db_name)
    another_client = tm.TinyMongoClient(db_name)
    assert True

def test_initialize_collection(collection):
    """
    Ensure that the initial db is of the correct size

    :param collection: pytest fixture that returns the collection
    :return:
    """
    c = collection.find({})

    count = 0
    for doc in c:
        count += 1

    assert count == 100
    assert c.count() == 100

def test_greater_than(collection):
    """
    Testing the greater than operator

    :param collection: pytest fixture that returns the collection
    :return:
    """
    c = collection.find({'count': {'$gte': 50}})

    assert c.count() == 50

def test_sort_wrong_input_type(collection):
    """
    Testing the sort method in the positive direction

    :param collection: pytest fixture that returns the collection
    :return:
    """
    c = collection.find()  # find all
    with pytest.raises(ValueError):
        c.sort('count')

def test_sort_positive(collection):
    """
    Testing the sort method in the positive direction

    :param collection: pytest fixture that returns the collection
    :return:
    """
    c = collection.find()  # find all
    c.sort({'count': 1})
    assert c[0]['count'] == 0
    assert c[1]['count'] == 1

def test_sort_negative(collection):
    """
    Testing the sort method in the positive direction

    :param collection: pytest fixture that returns the collection
    :return:
    """
    c = collection.find()  # find all
    c.sort({'count': -1})
    assert c[0]['count'] == 99
    assert c[1]['count'] == 98

def test_has_next(collection):
    """
    Testing hasNext

    :param collection: pytest fixture that returns the collection
    :return:
    """
    c = collection.find().sort({'count': 1})

    assert c.hasNext() is True
    assert c.next()['count'] == 0

def test_not_has_next(collection):
    """
    Testing hasNext when it should be false

    :param collection: pytest fixture that returns the collection
    :return:
    """
    c = collection.find({'count': {'$gte': 98}}).sort({'count': 1})

    assert c.hasNext() is True
    assert c.next()['count'] == 98
    assert c.hasNext() is True
    assert c.next()['count'] == 99
    assert c.hasNext() is False

def test_empty_find(collection):
    """
    Tests 'find' method when empty
    :param collection:
    :return:
    """
    c = collection.find()
    assert c.count() == 100

def test_find_one(collection):
    """
    Testing the retrieval of an item using the 'find_one' method

    :param collection: pytest fixture that returns the collection
    :return:
    """
    c = collection.find_one({'count': 3})

    assert c['countStr'] == '3'

def test_gte_lt(collection):
    """
    Testing the >= and < queries
    :param collection: pytest fixture that returns the collection
    :return:
    """
    c = collection.find({'count': {'$gte': 50, '$lt': 51}})
    assert c.count() == 1
    assert c[0]['countStr'] == '50'

def test_gt_lte(collection):
    """
    Testing the < and >= queries
    :param collection: pytest fixture that returns the collection
    :return:
    """
    c = collection.find({'count': {'$gt': 50, '$lte': 51}})
    assert c.count() == 1
    assert c[0]['countStr'] == '51'

def test_ne(collection):
    """
    Testing the < and >= queries
    :param collection: pytest fixture that returns the collection
    :return:
    """
    c = collection.find({'count': {'$ne': 50}})
    assert c.count() == 99

    for item in c:
        assert item['countStr'] != '50'

def test_update_one_set(collection):
    """
    Testing the update_one method of the collection

    :param collection: pytest fixture that returns the collection
    :return:
    """
    cu = collection.update_one({'count': 3}, {'$set': {'countStr': 'three'}})
    assert cu is True

    c = collection.find_one({'count': 3})
    assert c['countStr'] == 'three'

def test_delete_one(collection):
    """
    Testing the 'delete_one' method

    :param collection: pytest fixture that returns the collection
    :return:
    """
    collection.delete_one({'count': 3})

    c = collection.find({})

    assert c.count() == 99

def test_delete_all(collection):
    """
    Testing the 'delete_many' method to remove all

    :param collection: pytest fixture that returns the collection
    :return:
    """
    collection.delete_many({})

    c = collection.find({})

    assert c.count() == 0

def test_delete_many(collection):
    """
    Testing the 'delete_many' method to remove some items

    :param collection: pytest fixture that returns the collection
    :return:
    """
    collection.delete_many({'count': {'$gte': 50}})

    c = collection.find({})

    assert c.count() == 50

def test_insert_one(collection):
    """
    Testing the 'insert_one' method
    :param collection: pytest fixture that returns the collection
    :return:
    """
    collection.insert_one({'my_object_name': 'my object value', 'count': 1000})

    c = collection.find({})

    assert c.count() == 101
    assert collection.find({'my_object_name': 'my object value'})['count'] == 1000

def test_insert_many(collection):
    """
    Testing the 'insert_many' method
    :param collection: pytest fixture that returns the collection
    :return:
    """
    items = []
    for i in range(10):
        value = 1000 + i
        items.append({'count': value, 'countStr': str(value)})

    collection.insert_many(items)

    c = collection.find({})

    assert c.count() == 110

def test_insert_many_wrong_input(collection):
    """
    Testing the 'insert_many' method with a non-list input
    :param collection: pytest fixture that returns the collection
    :return:
    """
    item = {'my_key': 'my value'}
    with pytest.raises(ValueError):
        collection.insert_many(item)

def test_insert_one_with_list_input(collection):
    """
    Testing the 'insert_one' method with a list input
    :param collection: pytest fixture that returns the collection
    :return:
    """
    with pytest.raises(ValueError):
        collection.insert_one([{'my_object_name': 'my object value', 'count': 1000}])

<|endoftext|>


<commit_before># -*- coding: utf-8 -*-

from __future__ import unicode_literals
import datetime

from django.test import TestCase, override_settings
from django import forms
from django.conf import settings

import djconfig
from djconfig import forms as djconfig_forms
from djconfig.utils import override_djconfig
from djconfig.conf import Config, config
from djconfig.forms import ConfigForm
from djconfig.models import Config as ConfigModel
from djconfig.middleware import DjConfigMiddleware, DjConfigLocMemMiddleware

class FooForm(ConfigForm):

    boolean = forms.BooleanField(initial=True, required=False)
    boolean_false = forms.BooleanField(initial=False, required=False)
    char = forms.CharField(initial="foo")
    email = forms.EmailField(initial="foo@bar.com")
    float_number = forms.FloatField(initial=1.23)
    integer = forms.IntegerField(initial=123)
    url = forms.URLField(initial="foo.com/")

class DjConfigTest(TestCase):

    def setUp(self):
        config._reset()

    def test_register(self):
        """
        register forms
        """
        djconfig.register(FooForm)
        self.assertSetEqual(config._registry, {FooForm, })

    def test_register_invalid_form(self):
        """
        register invalid forms
        """
        class BadForm(forms.Form):
            """"""

        self.assertRaises(AssertionError, djconfig.register, BadForm)

    @override_settings(MIDDLEWARE_CLASSES=settings.MIDDLEWARE_CLASSES[:-1])
    def test_register_check_backend(self):
        """
        Raises valueError if middleware is missing
        """
        self.assertRaises(ValueError, djconfig.register, FooForm)

class BarForm(ConfigForm):

    char = forms.CharField(initial="foo")

class DjConfigFormsTest(TestCase):

    def setUp(self):
        config._reset()

    def test_config_form_initial(self):
        """
        config form, populate initial data
        """
        djconfig.register(BarForm)
        djconfig.reload_maybe()
        form = BarForm()
        self.assertEqual(form.initial['char'], 'foo')

    def test_config_form_auto_populate(self):
        """
        config form, populate initial data,
        load the config if it's not loaded
        """
        ConfigModel.objects.create(key="char", value="foo2")
        djconfig.register(BarForm)
        djconfig.reload_maybe()

        form = BarForm()
        self.assertEqual(form.initial['char'], 'foo2')

    def test_config_form_allow_initial_overwrite(self):
        """
        config form, allow user to pass initial data
        """
        djconfig.register(BarForm)
        djconfig.reload_maybe()
        config._set("char", "foo2")

        form = BarForm(initial={'char': 'bar', 'email': 'new_initial@mail.com'})
        self.assertEqual(form.initial['char'], 'foo2')
        self.assertEqual(form.initial['email'], 'new_initial@mail.com')

    def test_config_form(self):
        """
        config form
        """
        form = BarForm(data={"char": "foo2", })
        self.assertTrue(form.is_valid())
        form.save()

        qs = ConfigModel.objects.get(key="char")
        self.assertEqual(qs.value, "foo2")

    def test_config_form_update(self):
        """
        Should update the form with the supplied data when saving
        """
        ConfigModel.objects.create(key="char", value="bar")

        form = BarForm(data={"char": "foo2", })
        self.assertTrue(form.is_valid())
        form.save()

        qs = ConfigModel.objects.get(key="char")
        self.assertEqual(qs.value, "foo2")

    def test_config_form_cache_update(self):
        """
        config form, update cache on form save
        """
        djconfig.register(BarForm)

        form = BarForm(data={"char": "foo2", })
        self.assertTrue(form.is_valid())
        form.save()

        self.assertEqual(config.char, "foo2")

    def test_config_form_updated_at(self):
        """
        updated_at should get update on every save() call
        """
        now = djconfig_forms.timezone.now()

        class TZMock:
            @classmethod
            def now(cls):
                return now

        orig_djconfig_forms_timezone, djconfig_forms.timezone = djconfig_forms.timezone, TZMock
        try:
            form = BarForm(data={"char": "foo2", })
            self.assertTrue(form.is_valid())
            form.save()
            updated_at_a = ConfigModel.objects.get(key="_updated_at").value

            now += datetime.timedelta(seconds=1)

            form = BarForm(data={"char": "foo2", })
            self.assertTrue(form.is_valid())
            form.save()
            updated_at_b = ConfigModel.objects.get(key="_updated_at").value

            self.assertNotEqual(updated_at_a, updated_at_b)
        finally:
            djconfig_forms.timezone = orig_djconfig_forms_timezone

class DjConfigConfTest(TestCase):

    def setUp(self):
        config._reset()

    def test_config_attr_error(self):
        """
        config attribute error when it's not in keys
        """
        config_ = Config()
        self.assertRaises(AttributeError, lambda: config_.foo)
        config_._set('foo', 'bar')
        self.assertEqual(config_.foo, 'bar')

    def test_config_set(self):
        """
        config set adds the item
        """
        config._set('foo', 'bar')
        self.assertTrue('foo' in config._cache)
        self.assertEqual(config.foo, 'bar')

    def test_config_set_many(self):
        """
        config set adds the key
        """
        config._set_many({'foo': 'bar', })
        self.assertTrue('foo' in config._cache)
        self.assertEqual(config.foo, 'bar')

    def test_config_load(self):
        """
        Load initial configuration into the cache
        """
        djconfig.register(FooForm)
        djconfig.reload_maybe()
        keys = ['boolean', 'boolean_false', 'char', 'email', 'float_number', 'integer', 'url']
        values = {k: getattr(config, k) for k in keys}
        self.assertDictEqual(
            values,
            {
                'boolean': True,
                'boolean_false': False,
                'char': "foo",
                'email': "foo@bar.com",
                'float_number': 1.23,
                'integer': 123,
                'url': "foo.com/"
            }
        )

    def test_config_load_from_database(self):
        """
        Load configuration into the cache
        """
        data = [
            ConfigModel(key='boolean', value=False),
            ConfigModel(key='boolean_false', value=True),
            ConfigModel(key='float_number', value=2.1),
            ConfigModel(key='char', value="foo2"),
            ConfigModel(key='email', value="foo2@bar.com"),
            ConfigModel(key='integer', value=321),
            ConfigModel(key='url', value="foo2.com/")
        ]
        ConfigModel.objects.bulk_create(data)

        djconfig.register(FooForm)
        djconfig.reload_maybe()
        keys = ['boolean', 'boolean_false', 'char', 'email', 'float_number', 'integer', 'url']
        values = {k: getattr(config, k) for k in keys}
        self.assertDictEqual(
            values,
            {
                'boolean': False,
                'boolean_false': True,
                'float_number': 2.1,
                'char': "foo2",
                'email': "foo2@bar.com",
                'integer': 321,
                'url': "http://foo2.com/"
            }
        )

        # use initial if the field is not found in the db
        ConfigModel.objects.get(key='char').delete()
        config._reset()
        djconfig.register(FooForm)
        djconfig.reload_maybe()
        self.assertEqual(config.char, "foo")

    def test_config_load_unicode(self):
        """
        Load configuration into the cache
        """
        ConfigModel.objects.create(key='char', value=u"áéíóú")
        djconfig.register(FooForm)
        djconfig.reload_maybe()
        self.assertEqual(config.char, u"áéíóú")

    def test_config_load_from_database_invalid(self):
        """
        Load initial if the db value is invalid
        """
        ConfigModel.objects.create(key='integer', value="string")
        djconfig.register(FooForm)
        djconfig.reload_maybe()
        self.assertEqual(config.integer, 123)

    def test_config_load_updated_at(self):
        """
        Load updated_at
        """
        djconfig.register(FooForm)
        djconfig.reload_maybe()
        self.assertIsNone(config._updated_at)

        ConfigModel.objects.create(key="_updated_at", value="string")
        config._reset()

        djconfig.register(FooForm)
        djconfig.reload_maybe()
        self.assertEqual(config._updated_at, "string")

    def test_config_reload_maybe(self):
        """
        Reload if not loaded
        """
        self.assertRaises(AttributeError, lambda: config.char)
        djconfig.register(FooForm)
        self.assertRaises(AttributeError, lambda: config.char)
        djconfig.reload_maybe()
        self.assertEqual(config.char, "foo")

TEST_CACHES = {
    'good': {
        'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
    },
    'bad': {
        'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
    }
}

class DjConfigMiddlewareTest(TestCase):

    def setUp(self):
        config._reset()

    def test_config_middleware_process_request(self):
        """
        config middleware, reload cache
        """
        ConfigModel.objects.create(key="char", value="foo")
        djconfig.register(BarForm)
        djconfig.reload_maybe()
        config._set('char', None)

        # Should not reload since _updated_at does not exists (form was not saved)
        middleware = DjConfigMiddleware()
        middleware.process_request(request=None)
        self.assertIsNone(config._cache.get('char'))

        # Changing _updated_at should make it reload
        ConfigModel.objects.create(key="_updated_at", value="111")
        middleware.process_request(request=None)
        self.assertEqual(config._cache.get('char'), "foo")
        self.assertEqual(config._cache.get("_updated_at"), "111")

        # It does not update again, since _updated_at has not changed
        ConfigModel.objects.filter(key="char").update(value="bar")
        middleware.process_request(request=None)
        self.assertNotEqual(config._cache.get('char'), "bar")
        self.assertEqual(config._cache.get("_updated_at"), "111")

        # Changing _updated_at should make it reload
        ConfigModel.objects.filter(key="_updated_at").update(value="222")
        middleware.process_request(request=None)
        self.assertEqual(config._cache.get('char'), "bar")
        self.assertEqual(config._cache.get("_updated_at"), "222")

    def test_config_middleware_old(self):
        """
        Regression test for the old LocMem Middleware
        """
        self.assertEqual(DjConfigLocMemMiddleware, DjConfigMiddleware)

class DjConfigUtilsTest(TestCase):

    def setUp(self):
        config._reset()

    def test_override_djconfig(self):
        """
        Sets config variables temporarily
        """
        @override_djconfig(foo='bar', foo2='bar2')
        def my_test(my_var):
            return my_var, config.foo, config.foo2

        config._set('foo', 'org')
        config._set('foo2', 'org2')

        res = my_test("stuff")
        self.assertEqual(res, ("stuff", 'bar', 'bar2'))
        self.assertEqual((config.foo, config.foo2), ("org", 'org2'))

    def test_override_djconfig_except(self):
        """
        Sets config variables temporarily, even on exceptions
        """
        @override_djconfig(foo='bar')
        def my_test():
            raise AssertionError

        config._set('foo', 'org')

        try:
            my_test()
        except AssertionError:
            pass

        self.assertEqual(config.foo, "org")
<commit_msg>ChoiceField support #16<commit_after># -*- coding: utf-8 -*-

from __future__ import unicode_literals
import datetime

from django.test import TestCase, override_settings
from django import forms
from django.conf import settings

import djconfig
from djconfig import forms as djconfig_forms
from djconfig.utils import override_djconfig
from djconfig.conf import Config, config
from djconfig.forms import ConfigForm
from djconfig.models import Config as ConfigModel
from djconfig.middleware import DjConfigMiddleware, DjConfigLocMemMiddleware

class FooForm(ConfigForm):

    boolean = forms.BooleanField(initial=True, required=False)
    boolean_false = forms.BooleanField(initial=False, required=False)
    char = forms.CharField(initial="foo")
    email = forms.EmailField(initial="foo@bar.com")
    float_number = forms.FloatField(initial=1.23)
    integer = forms.IntegerField(initial=123)
    url = forms.URLField(initial="foo.com/")
    choices = forms.ChoiceField(initial=None, choices=[(1, 'label_a'), (2, 'label_b')])

class DjConfigTest(TestCase):

    def setUp(self):
        config._reset()

    def test_register(self):
        """
        register forms
        """
        djconfig.register(FooForm)
        self.assertSetEqual(config._registry, {FooForm, })

    def test_register_invalid_form(self):
        """
        register invalid forms
        """
        class BadForm(forms.Form):
            """"""

        self.assertRaises(AssertionError, djconfig.register, BadForm)

    @override_settings(MIDDLEWARE_CLASSES=settings.MIDDLEWARE_CLASSES[:-1])
    def test_register_check_backend(self):
        """
        Raises valueError if middleware is missing
        """
        self.assertRaises(ValueError, djconfig.register, FooForm)

class BarForm(ConfigForm):

    char = forms.CharField(initial="foo")

class DjConfigFormsTest(TestCase):

    def setUp(self):
        config._reset()

    def test_config_form_initial(self):
        """
        config form, populate initial data
        """
        djconfig.register(BarForm)
        djconfig.reload_maybe()
        form = BarForm()
        self.assertEqual(form.initial['char'], 'foo')

    def test_config_form_auto_populate(self):
        """
        config form, populate initial data,
        load the config if it's not loaded
        """
        ConfigModel.objects.create(key="char", value="foo2")
        djconfig.register(BarForm)
        djconfig.reload_maybe()

        form = BarForm()
        self.assertEqual(form.initial['char'], 'foo2')

    def test_config_form_allow_initial_overwrite(self):
        """
        config form, allow user to pass initial data
        """
        djconfig.register(BarForm)
        djconfig.reload_maybe()
        config._set("char", "foo2")

        form = BarForm(initial={'char': 'bar', 'email': 'new_initial@mail.com'})
        self.assertEqual(form.initial['char'], 'foo2')
        self.assertEqual(form.initial['email'], 'new_initial@mail.com')

    def test_config_form(self):
        """
        config form
        """
        form = BarForm(data={"char": "foo2", })
        self.assertTrue(form.is_valid())
        form.save()

        qs = ConfigModel.objects.get(key="char")
        self.assertEqual(qs.value, "foo2")

    def test_config_form_update(self):
        """
        Should update the form with the supplied data when saving
        """
        ConfigModel.objects.create(key="char", value="bar")

        form = BarForm(data={"char": "foo2", })
        self.assertTrue(form.is_valid())
        form.save()

        qs = ConfigModel.objects.get(key="char")
        self.assertEqual(qs.value, "foo2")

    def test_config_form_cache_update(self):
        """
        config form, update cache on form save
        """
        djconfig.register(BarForm)

        form = BarForm(data={"char": "foo2", })
        self.assertTrue(form.is_valid())
        form.save()

        self.assertEqual(config.char, "foo2")

    def test_config_form_updated_at(self):
        """
        updated_at should get update on every save() call
        """
        now = djconfig_forms.timezone.now()

        class TZMock:
            @classmethod
            def now(cls):
                return now

        orig_djconfig_forms_timezone, djconfig_forms.timezone = djconfig_forms.timezone, TZMock
        try:
            form = BarForm(data={"char": "foo2", })
            self.assertTrue(form.is_valid())
            form.save()
            updated_at_a = ConfigModel.objects.get(key="_updated_at").value

            now += datetime.timedelta(seconds=1)

            form = BarForm(data={"char": "foo2", })
            self.assertTrue(form.is_valid())
            form.save()
            updated_at_b = ConfigModel.objects.get(key="_updated_at").value

            self.assertNotEqual(updated_at_a, updated_at_b)
        finally:
            djconfig_forms.timezone = orig_djconfig_forms_timezone

class DjConfigConfTest(TestCase):

    def setUp(self):
        config._reset()

    def test_config_attr_error(self):
        """
        config attribute error when it's not in keys
        """
        config_ = Config()
        self.assertRaises(AttributeError, lambda: config_.foo)
        config_._set('foo', 'bar')
        self.assertEqual(config_.foo, 'bar')

    def test_config_set(self):
        """
        config set adds the item
        """
        config._set('foo', 'bar')
        self.assertTrue('foo' in config._cache)
        self.assertEqual(config.foo, 'bar')

    def test_config_set_many(self):
        """
        config set adds the key
        """
        config._set_many({'foo': 'bar', })
        self.assertTrue('foo' in config._cache)
        self.assertEqual(config.foo, 'bar')

    def test_config_load(self):
        """
        Load initial configuration into the cache
        """
        djconfig.register(FooForm)
        djconfig.reload_maybe()
        keys = ['boolean', 'boolean_false', 'char', 'email', 'float_number', 'integer', 'url', 'choices']
        values = {k: getattr(config, k) for k in keys}
        self.assertDictEqual(
            values,
            {
                'boolean': True,
                'boolean_false': False,
                'char': "foo",
                'email': "foo@bar.com",
                'float_number': 1.23,
                'integer': 123,
                'url': "foo.com/",
                'choices': None
            }
        )

    def test_config_load_from_database(self):
        """
        Load configuration into the cache
        """
        data = [
            ConfigModel(key='boolean', value=False),
            ConfigModel(key='boolean_false', value=True),
            ConfigModel(key='float_number', value=2.1),
            ConfigModel(key='char', value="foo2"),
            ConfigModel(key='email', value="foo2@bar.com"),
            ConfigModel(key='integer', value=321),
            ConfigModel(key='url', value="foo2.com/"),
            ConfigModel(key='choices', value=None)
        ]
        ConfigModel.objects.bulk_create(data)

        djconfig.register(FooForm)
        djconfig.reload_maybe()
        keys = ['boolean', 'boolean_false', 'char', 'email', 'float_number', 'integer', 'url', 'choices']
        values = {k: getattr(config, k) for k in keys}
        self.assertDictEqual(
            values,
            {
                'boolean': False,
                'boolean_false': True,
                'float_number': 2.1,
                'char': "foo2",
                'email': "foo2@bar.com",
                'integer': 321,
                'url': "http://foo2.com/",
                'choices': None
            }
        )

        # use initial if the field is not found in the db
        ConfigModel.objects.get(key='char').delete()
        config._reset()
        djconfig.register(FooForm)
        djconfig.reload_maybe()
        self.assertEqual(config.char, "foo")

    def test_config_load_unicode(self):
        """
        Load configuration into the cache
        """
        ConfigModel.objects.create(key='char', value=u"áéíóú")
        djconfig.register(FooForm)
        djconfig.reload_maybe()
        self.assertEqual(config.char, u"áéíóú")

    def test_config_load_from_database_invalid(self):
        """
        Load initial if the db value is invalid
        """
        ConfigModel.objects.create(key='integer', value="string")
        djconfig.register(FooForm)
        djconfig.reload_maybe()
        self.assertEqual(config.integer, 123)

    def test_config_load_updated_at(self):
        """
        Load updated_at
        """
        djconfig.register(FooForm)
        djconfig.reload_maybe()
        self.assertIsNone(config._updated_at)

        ConfigModel.objects.create(key="_updated_at", value="string")
        config._reset()

        djconfig.register(FooForm)
        djconfig.reload_maybe()
        self.assertEqual(config._updated_at, "string")

    def test_config_reload_maybe(self):
        """
        Reload if not loaded
        """
        self.assertRaises(AttributeError, lambda: config.char)
        djconfig.register(FooForm)
        self.assertRaises(AttributeError, lambda: config.char)
        djconfig.reload_maybe()
        self.assertEqual(config.char, "foo")

TEST_CACHES = {
    'good': {
        'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
    },
    'bad': {
        'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
    }
}

class DjConfigMiddlewareTest(TestCase):

    def setUp(self):
        config._reset()

    def test_config_middleware_process_request(self):
        """
        config middleware, reload cache
        """
        ConfigModel.objects.create(key="char", value="foo")
        djconfig.register(BarForm)
        djconfig.reload_maybe()
        config._set('char', None)

        # Should not reload since _updated_at does not exists (form was not saved)
        middleware = DjConfigMiddleware()
        middleware.process_request(request=None)
        self.assertIsNone(config._cache.get('char'))

        # Changing _updated_at should make it reload
        ConfigModel.objects.create(key="_updated_at", value="111")
        middleware.process_request(request=None)
        self.assertEqual(config._cache.get('char'), "foo")
        self.assertEqual(config._cache.get("_updated_at"), "111")

        # It does not update again, since _updated_at has not changed
        ConfigModel.objects.filter(key="char").update(value="bar")
        middleware.process_request(request=None)
        self.assertNotEqual(config._cache.get('char'), "bar")
        self.assertEqual(config._cache.get("_updated_at"), "111")

        # Changing _updated_at should make it reload
        ConfigModel.objects.filter(key="_updated_at").update(value="222")
        middleware.process_request(request=None)
        self.assertEqual(config._cache.get('char'), "bar")
        self.assertEqual(config._cache.get("_updated_at"), "222")

    def test_config_middleware_old(self):
        """
        Regression test for the old LocMem Middleware
        """
        self.assertEqual(DjConfigLocMemMiddleware, DjConfigMiddleware)

class DjConfigUtilsTest(TestCase):

    def setUp(self):
        config._reset()

    def test_override_djconfig(self):
        """
        Sets config variables temporarily
        """
        @override_djconfig(foo='bar', foo2='bar2')
        def my_test(my_var):
            return my_var, config.foo, config.foo2

        config._set('foo', 'org')
        config._set('foo2', 'org2')

        res = my_test("stuff")
        self.assertEqual(res, ("stuff", 'bar', 'bar2'))
        self.assertEqual((config.foo, config.foo2), ("org", 'org2'))

    def test_override_djconfig_except(self):
        """
        Sets config variables temporarily, even on exceptions
        """
        @override_djconfig(foo='bar')
        def my_test():
            raise AssertionError

        config._set('foo', 'org')

        try:
            my_test()
        except AssertionError:
            pass

        self.assertEqual(config.foo, "org")
<|endoftext|>


<commit_before># -*- coding: utf8 -*-
import time

from django.conf import settings
from django.contrib.auth import authenticate
from django.test.utils import override_settings
from django.utils import unittest

from django_nopassword.models import LoginCode
from django_nopassword.utils import User

class TestLoginCodes(unittest.TestCase):
    def setUp(self):
        self.user = User.objects.create(username='test_user')

    def test_login_backend(self):
        self.code = LoginCode.create_code_for_user(self.user)
        self.assertEqual(len(self.code.code), 20)
        self.assertIsNotNone(authenticate(username=self.user.username, code=self.code.code))
        self.assertEqual(LoginCode.objects.filter(user=self.user, code=self.code.code).count(), 0)

    @override_settings(LOGIN_CODE_TIMEOUT=1)
    def test_code_timeout(self):
        self.timeout_code = LoginCode.create_code_for_user(self.user)
        time.sleep(3)
        self.assertIsNone(authenticate(username=self.user.username, code=self.timeout_code.code))

    def tearDown(self):
        self.user.delete()
<commit_msg>update tests to check inactive users<commit_after># -*- coding: utf8 -*-
import time

from django.contrib.auth import authenticate
from django.test.utils import override_settings
from django.utils import unittest

from django_nopassword.models import LoginCode
from django_nopassword.utils import User

class TestLoginCodes(unittest.TestCase):
    def setUp(self):
        self.user = User.objects.create(username='test_user')
        self.inactive_user = User.objects.create(username='inactive', is_active=False)

    def test_login_backend(self):
        self.code = LoginCode.create_code_for_user(self.user)
        self.assertEqual(len(self.code.code), 20)
        self.assertIsNotNone(authenticate(username=self.user.username, code=self.code.code))
        self.assertEqual(LoginCode.objects.filter(user=self.user, code=self.code.code).count(), 0)

        self.assertIsNone(LoginCode.create_code_for_user(self.inactive_user))

    @override_settings(LOGIN_CODE_TIMEOUT=1)
    def test_code_timeout(self):
        self.timeout_code = LoginCode.create_code_for_user(self.user)
        time.sleep(3)
        self.assertIsNone(authenticate(username=self.user.username, code=self.timeout_code.code))

    def tearDown(self):
        self.user.delete()
        self.inactive_user.delete()
<|endoftext|>


<commit_before>import os
import sys

def add_bin_to_path():
    BINPATH = os.path.abspath(
        os.path.join(os.path.dirname(__file__), '../HOME/bin'))
    sys.path.append(BINPATH)
<commit_msg>Fix code style<commit_after>import os
import sys

def add_bin_to_path():
    binpath = os.path.abspath(
        os.path.join(os.path.dirname(__file__), '../HOME/bin'))
    sys.path.append(binpath)
<|endoftext|>