Python unittest.main() Examples

The following are code examples for showing how to use unittest.main(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: fs_image   Author: facebookincubator   File: test_extent.py    MIT License 6 votes vote down vote up
def test_truncate(self):
        e = Extent.empty().write(offset=3, length=7)
        for i in range(1, 10):
            self.assertEqual(Extent((e,), 0, i), e.truncate(length=i))
        self.assertEqual(
            Extent((e, Extent(Extent.Kind.HOLE, 0, 1)), 0, 11),
            e.truncate(length=11),
        )

    # A cute demonstration that while different orders of operations produce
    # different nestings, `gen_trimmed_leaves` restores commutativity.
    #
    # While it does not replace `test_write_and_clone`, the main benefit of
    # this test is scalability: it gives us a cheap-to-implement, but
    # meaningful assertion, which we can validate on a huge number of
    # sequences of operations with no manual effort.
    #
    # Additionally, it contributes "complex" case coverage for `truncate`. 
Example 2
Project: pyblish-win   Author: pyblish   File: test_program.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def testCatchBreakInstallsHandler(self):
        module = sys.modules['unittest.main']
        original = module.installHandler
        def restore():
            module.installHandler = original
        self.addCleanup(restore)

        self.installed = False
        def fakeInstallHandler():
            self.installed = True
        module.installHandler = fakeInstallHandler

        program = self.program
        program.catchbreak = True

        program.testRunner = FakeRunner

        program.runTests()
        self.assertTrue(self.installed) 
Example 3
Project: pyblish-win   Author: pyblish   File: configDialog.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def LoadGeneralCfg(self):
        #startup state
        self.startupEdit.set(idleConf.GetOption(
                'main', 'General', 'editor-on-startup', default=1, type='bool'))
        #autosave state
        self.autoSave.set(idleConf.GetOption(
                'main', 'General', 'autosave', default=0, type='bool'))
        #initial window size
        self.winWidth.set(idleConf.GetOption(
                'main', 'EditorWindow', 'width', type='int'))
        self.winHeight.set(idleConf.GetOption(
                'main', 'EditorWindow', 'height', type='int'))
        #initial paragraph reformat size
        self.paraWidth.set(idleConf.GetOption(
                'main', 'FormatParagraph', 'paragraph', type='int'))
        # default source encoding
        self.encoding.set(idleConf.GetOption(
                'main', 'EditorWindow', 'encoding', default='none'))
        # additional help sources
        self.userHelpList = idleConf.GetAllExtraHelpSourcesList()
        for helpItem in self.userHelpList:
            self.listHelp.insert(END, helpItem[0])
        self.SetHelpListButtonStates() 
Example 4
Project: pyblish-win   Author: pyblish   File: configDialog.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def SaveAllChangedConfigs(self):
        "Save configuration changes to the user config file."
        idleConf.userCfg['main'].Save()
        for configType in self.changedItems:
            cfgTypeHasChanges = False
            for section in self.changedItems[configType]:
                if section == 'HelpFiles':
                    #this section gets completely replaced
                    idleConf.userCfg['main'].remove_section('HelpFiles')
                    cfgTypeHasChanges = True
                for item in self.changedItems[configType][section]:
                    value = self.changedItems[configType][section][item]
                    if self.SetUserValue(configType, section, item, value):
                        cfgTypeHasChanges = True
            if cfgTypeHasChanges:
                idleConf.userCfg[configType].Save()
        for configType in ['keys', 'highlight']:
            # save these even if unchanged!
            idleConf.userCfg[configType].Save()
        self.ResetChangedItems() #clear the changed items dict 
Example 5
Project: pyblish-win   Author: pyblish   File: IdleHistory.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, text):
        '''Initialize data attributes and bind event methods.

        .text - Idle wrapper of tk Text widget, with .bell().
        .history - source statements, possibly with multiple lines.
        .prefix - source already entered at prompt; filters history list.
        .pointer - index into history.
        .cyclic - wrap around history list (or not).
        '''
        self.text = text
        self.history = []
        self.prefix = None
        self.pointer = None
        self.cyclic = idleConf.GetOption("main", "History", "cyclic", 1, "bool")
        text.bind("<<history-previous>>", self.history_prev)
        text.bind("<<history-next>>", self.history_next) 
Example 6
Project: flasky   Author: RoseOu   File: test.py    MIT License 6 votes vote down vote up
def run_tests(self):
        import unittest

        # Purge modules under test from sys.modules. The test loader will
        # re-import them from the build location. Required when 2to3 is used
        # with namespace packages.
        if sys.version_info >= (3,) and getattr(self.distribution, 'use_2to3', False):
            module = self.test_args[-1].split('.')[0]
            if module in _namespace_packages:
                del_modules = []
                if module in sys.modules:
                    del_modules.append(module)
                module += '.'
                for name in sys.modules:
                    if name.startswith(module):
                        del_modules.append(name)
                list(map(sys.modules.__delitem__, del_modules))

        loader_ep = EntryPoint.parse("x="+self.test_loader)
        loader_class = loader_ep.load(require=False)
        cks = loader_class()
        unittest.main(
            None, None, [unittest.__file__]+self.test_args,
            testLoader = cks
        ) 
Example 7
Project: mimic   Author: googlearchive   File: target_env_test.py    Apache License 2.0 6 votes vote down vote up
def testAppEngineConfig(self):
    self._env._TearDown()  # RunScript will set up the env
    self._tree.SetFile('appengine_config.py', _SIMPLE_APPENGINE_CONFIG)
    self._tree.SetFile('d/foo.py', _SIMPLE_D_FOO)
    level = logging.getLogger().level
    self.assertTrue(level > logging.DEBUG)  # should be true in a test
    handler = CollectingHandler()
    self._env.RunScript('d/foo.py', handler)

    module_main = _test_portal.main
    self.assertEquals('__main__', module_main.__name__)
    self.assertEquals('/target/d/foo.py', module_main.__file__)

    module_appengine_config = _test_portal.appengine_config
    self.assertEquals('appengine_config', module_appengine_config.__name__)
    self.assertEquals('/target/appengine_config.py',
                      module_appengine_config.__file__) 
Example 8
Project: mimic   Author: googlearchive   File: target_env_test.py    Apache License 2.0 6 votes vote down vote up
def testSysModulesHasTwoEntriesForCurrentTopLevelScript(self):
    self._env._TearDown()  # RunScript will set up the env
    self._tree.SetFile('foo.py', """
import logging
import sys
_test_portal.main = sys.modules['__main__']
_test_portal.foo = sys.modules['foo']
logging.debug('running foo.py')
""")
    handler = CollectingHandler()
    self._env.RunScript('foo.py', handler)
    # check that logging handler was invoked
    self.assertEquals(1, len(handler.records))
    self.assertEquals('running foo.py',
                      handler.records[0].getMessage())
    module_main = _test_portal.main
    self.assertEquals('__main__', module_main.__name__)
    module_foo = _test_portal.foo
    self.assertEquals(module_foo, module_main) 
Example 9
Project: mimic   Author: googlearchive   File: target_env_test.py    Apache License 2.0 6 votes vote down vote up
def testSysModulesHasTwoEntriesForCurrentPackageScript(self):
    self._env._TearDown()  # RunScript will set up the env
    self._tree.SetFile('d/foo.py', """
import logging
import sys
_test_portal.main = sys.modules['__main__']
_test_portal.foo = sys.modules['d.foo']
logging.debug('running foo.py')
""")
    handler = CollectingHandler()
    self._env.RunScript('d/foo.py', handler)
    # check that logging handler was invoked
    self.assertEquals(1, len(handler.records))
    self.assertEquals('running foo.py',
                      handler.records[0].getMessage())
    module_main = _test_portal.main
    self.assertEquals('__main__', module_main.__name__)
    module_foo = _test_portal.foo
    self.assertEquals(module_foo, module_main) 
Example 10
Project: mimic   Author: googlearchive   File: target_env_test.py    Apache License 2.0 6 votes vote down vote up
def testStatOnFile(self):
    """Tests patched stat on a file in the target file system."""
    self._env._TearDown()  # RunScript will set up the env
    self._tree.SetFile('template.html', 'template text')
    self._tree.SetFile('main.py', """
import os
import logging
import stat

stats = os.stat('template.html')
logging.info(stats[stat.ST_MODE])
# also test accessing the stat values as attributes
logging.info(stats.st_size)
logging.info(stats.st_mtime)
""")
    handler = CollectingHandler()
    self._env.RunScript('main.py', handler)
    self.assertEqual(str(target_env._FILE_STAT_MODE),
                     handler.records[0].getMessage())
    self.assertEqual('13', handler.records[1].getMessage())
    self.assertIsNotNone(handler.records[2].getMessage()) 
Example 11
Project: mimic   Author: googlearchive   File: target_env_test.py    Apache License 2.0 6 votes vote down vote up
def testStatOnDirectory(self):
    """Tests patched stat on a directory in the target file system."""
    self._env._TearDown()  # RunScript will set up the env
    self._tree.SetFile('templates/template.html', 'template text')
    self._tree.SetFile('main.py', """
import os
import logging
import stat

stats = os.stat('templates')
logging.info(stats[stat.ST_MODE])
# also test accessing the stat values as attributes
logging.info(stats.st_size)
""")
    handler = CollectingHandler()
    self._env.RunScript('main.py', handler)
    self.assertEqual(str(target_env._DIR_STAT_MODE),
                     handler.records[0].getMessage())
    self.assertEqual('0', handler.records[1].getMessage()) 
Example 12
Project: mimic   Author: googlearchive   File: target_env_test.py    Apache License 2.0 6 votes vote down vote up
def testStatFileDoesNotExist(self):
    """Tests that patched stat raises OSError on a file that doesn't exist."""
    self._env._TearDown()  # RunScript will set up the env
    self._tree.SetFile('main.py', """
import os
import logging

try:
  # this is in the target file system
  os.stat('template.html')
except OSError, e:
  logging.info('got OSError: ' + str(e.errno))

try:
  # this should go through the original stat
  os.stat('/folder-foo/file-baz')
except OSError, e:
  logging.info('got OSError: ' + str(e.errno))
""")
    handler = CollectingHandler()
    self._env.RunScript('main.py', handler)
    no_ent_error_msg = 'got OSError: ' + str(errno.ENOENT)
    self.assertEqual(no_ent_error_msg, handler.records[0].getMessage())
    self.assertEqual(no_ent_error_msg, handler.records[1].getMessage()) 
Example 13
Project: mimic   Author: googlearchive   File: target_env_test.py    Apache License 2.0 6 votes vote down vote up
def testOpenSkippedFile(self):
    self._env._TearDown()  # RunScript will set up the env
    self._tree.SetFile('README.txt', 'readme')
    self._tree.SetFile('folder/README.txt', 'readme too')
    self._tree.SetFile('skip_folder/skipped.txt', 'skip me')
    self._tree.SetFile('main.py', """
import logging
for file in ('README.txt', 'folder/README.txt', 'skip_folder/skipped.txt'):
  for file2 in (file, '/target/' + file):
    try:
      open(file2)
    except IOError, e:
      logging.error('got IOError: ' + str(e.errno))
""")
    handler = CollectingHandler()
    self._env.RunScript('main.py', handler)
    no_ent_error_msg = 'got IOError: ' + str(errno.ENOENT)
    self.assertEqual(6, len(handler.records))
    for record in handler.records:
      self.assertEqual(no_ent_error_msg, record.getMessage()) 
Example 14
Project: mimic   Author: googlearchive   File: target_env_test.py    Apache License 2.0 6 votes vote down vote up
def testStatOnSkippedFile(self):
    """Tests patched stat on a skipped file."""
    self._env._TearDown()  # RunScript will set up the env
    self._tree.SetFile('README.txt', 'readme')
    self._tree.SetFile('folder/README.txt', 'readme too')
    self._tree.SetFile('skip_folder/file', 'skipme')
    self._tree.SetFile('main.py', """
import logging
import os
for file in ('README.txt', 'folder/README.txt', 'skip_folder/skipped.txt'):
  for file2 in (file, '/target/' + file):
    try:
      os.stat(file2)
    except OSError, e:
      logging.error('got OSError: ' + str(e.errno))
""")
    handler = CollectingHandler()
    self._env.RunScript('main.py', handler)
    no_ent_error_msg = 'got OSError: ' + str(errno.ENOENT)
    self.assertEqual(6, len(handler.records))
    for record in handler.records:
      self.assertEqual(no_ent_error_msg, record.getMessage()) 
Example 15
Project: mimic   Author: googlearchive   File: target_env_test.py    Apache License 2.0 6 votes vote down vote up
def testSkipFilesBadRegex(self):
    self._env._TearDown()
    config = yaml.load(r"""
handlers:
- url: /.*
  script: main.py

skip_files:
# invalid
- '*'
""")
    try:
      target_env.TargetEnvironment(self._tree, config, 'ProjectName',
                                   test_portal=_test_portal)
      # the constructor should raise an exception
      self.fail()
    except target_info.ValidationError, e:
      # make sure it's the right valididation error
      self.assertTrue('skip_files' in str(e)) 
Example 16
Project: pyblish-win   Author: pyblish   File: test_program.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_NonExit(self):
        program = unittest.main(exit=False,
                                argv=["foobar"],
                                testRunner=unittest.TextTestRunner(stream=StringIO()),
                                testLoader=self.FooBarLoader())
        self.assertTrue(hasattr(program, 'result')) 
Example 17
Project: pyblish-win   Author: pyblish   File: test_program.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_Exit(self):
        self.assertRaises(
            SystemExit,
            unittest.main,
            argv=["foobar"],
            testRunner=unittest.TextTestRunner(stream=StringIO()),
            exit=True,
            testLoader=self.FooBarLoader()) 
Example 18
Project: pyblish-win   Author: pyblish   File: test_program.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_ExitAsDefault(self):
        self.assertRaises(
            SystemExit,
            unittest.main,
            argv=["foobar"],
            testRunner=unittest.TextTestRunner(stream=StringIO()),
            testLoader=self.FooBarLoader()) 
Example 19
Project: pyblish-win   Author: pyblish   File: test_main.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def tearDown(self):
        # Clean up logging configuration down by main.
        del logging.root.handlers[:]
        if self.temp_dir:
            shutil.rmtree(self.temp_dir) 
Example 20
Project: pyblish-win   Author: pyblish   File: test_all.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testPrintVersions(self):
        print_versions()


# This little hack is for when this module is run as main and all the
# other modules import it so they will still be able to get the right
# verbose setting.  It's confusing but it works. 
Example 21
Project: pyblish-win   Author: pyblish   File: configDialog.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def VarChanged_fontSize(self, *params):
        value = self.fontSize.get()
        self.AddChangedItem('main', 'EditorWindow', 'font-size', value) 
Example 22
Project: pyblish-win   Author: pyblish   File: configDialog.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def VarChanged_fontName(self, *params):
        value = self.fontName.get()
        self.AddChangedItem('main', 'EditorWindow', 'font', value) 
Example 23
Project: pyblish-win   Author: pyblish   File: configDialog.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def VarChanged_fontBold(self, *params):
        value = self.fontBold.get()
        self.AddChangedItem('main', 'EditorWindow', 'font-bold', value) 
Example 24
Project: pyblish-win   Author: pyblish   File: configDialog.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def VarChanged_spaceNum(self, *params):
        value = self.spaceNum.get()
        self.AddChangedItem('main', 'Indent', 'num-spaces', value) 
Example 25
Project: pyblish-win   Author: pyblish   File: configDialog.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def VarChanged_customTheme(self, *params):
        value = self.customTheme.get()
        if value != '- no custom themes -':
            self.AddChangedItem('main', 'Theme', 'name', value)
            self.PaintThemeSample() 
Example 26
Project: pyblish-win   Author: pyblish   File: configDialog.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def VarChanged_themeIsBuiltin(self, *params):
        value = self.themeIsBuiltin.get()
        self.AddChangedItem('main', 'Theme', 'default', value)
        if value:
            self.VarChanged_builtinTheme()
        else:
            self.VarChanged_customTheme() 
Example 27
Project: pyblish-win   Author: pyblish   File: configDialog.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def VarChanged_builtinKeys(self, *params):
        value = self.builtinKeys.get()
        self.AddChangedItem('main', 'Keys', 'name', value)
        self.LoadKeysList(value) 
Example 28
Project: pyblish-win   Author: pyblish   File: configDialog.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def VarChanged_customKeys(self, *params):
        value = self.customKeys.get()
        if value != '- no custom keys -':
            self.AddChangedItem('main', 'Keys', 'name', value)
            self.LoadKeysList(value) 
Example 29
Project: pyblish-win   Author: pyblish   File: configDialog.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def VarChanged_keysAreBuiltin(self, *params):
        value = self.keysAreBuiltin.get()
        self.AddChangedItem('main', 'Keys', 'default', value)
        if value:
            self.VarChanged_builtinKeys()
        else:
            self.VarChanged_customKeys() 
Example 30
Project: pyblish-win   Author: pyblish   File: configDialog.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def VarChanged_winHeight(self, *params):
        value = self.winHeight.get()
        self.AddChangedItem('main', 'EditorWindow', 'height', value) 
Example 31
Project: pyblish-win   Author: pyblish   File: configDialog.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def VarChanged_paraWidth(self, *params):
        value = self.paraWidth.get()
        self.AddChangedItem('main', 'FormatParagraph', 'paragraph', value) 
Example 32
Project: pyblish-win   Author: pyblish   File: configDialog.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def VarChanged_startupEdit(self, *params):
        value = self.startupEdit.get()
        self.AddChangedItem('main', 'General', 'editor-on-startup', value) 
Example 33
Project: pyblish-win   Author: pyblish   File: configDialog.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def VarChanged_autoSave(self, *params):
        value = self.autoSave.get()
        self.AddChangedItem('main', 'General', 'autosave', value) 
Example 34
Project: pyblish-win   Author: pyblish   File: configDialog.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def VarChanged_encoding(self, *params):
        value = self.encoding.get()
        self.AddChangedItem('main', 'EditorWindow', 'encoding', value) 
Example 35
Project: pyblish-win   Author: pyblish   File: configDialog.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def GetDefaultItems(self):
        dItems={'main':{}, 'highlight':{}, 'keys':{}, 'extensions':{}}
        for configType in dItems:
            sections = idleConf.GetSectionList('default', configType)
            for section in sections:
                dItems[configType][section] = {}
                options = idleConf.defaultCfg[configType].GetOptionList(section)
                for option in options:
                    dItems[configType][section][option] = (
                            idleConf.defaultCfg[configType].Get(section, option))
        return dItems 
Example 36
Project: pyblish-win   Author: pyblish   File: configDialog.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def DeleteCustomKeys(self):
        keySetName=self.customKeys.get()
        delmsg = 'Are you sure you wish to delete the key set %r ?'
        if not tkMessageBox.askyesno(
                'Delete Key Set',  delmsg % keySetName, parent=self):
            return
        #remove key set from config
        idleConf.userCfg['keys'].remove_section(keySetName)
        if keySetName in self.changedItems['keys']:
            del(self.changedItems['keys'][keySetName])
        #write changes
        idleConf.userCfg['keys'].Save()
        #reload user key set list
        itemList = idleConf.GetSectionList('user', 'keys')
        itemList.sort()
        if not itemList:
            self.radioKeysCustom.config(state=DISABLED)
            self.optMenuKeysCustom.SetMenu(itemList, '- no custom keys -')
        else:
            self.optMenuKeysCustom.SetMenu(itemList, itemList[0])
        #revert to default key set
        self.keysAreBuiltin.set(idleConf.defaultCfg['main'].Get('Keys', 'default'))
        self.builtinKeys.set(idleConf.defaultCfg['main'].Get('Keys', 'name'))
        #user can't back out of these changes, they must be applied now
        self.Apply()
        self.SetKeysType() 
Example 37
Project: pyblish-win   Author: pyblish   File: configDialog.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def DeleteCustomTheme(self):
        themeName = self.customTheme.get()
        delmsg = 'Are you sure you wish to delete the theme %r ?'
        if not tkMessageBox.askyesno(
                'Delete Theme',  delmsg % themeName, parent=self):
            return
        #remove theme from config
        idleConf.userCfg['highlight'].remove_section(themeName)
        if themeName in self.changedItems['highlight']:
            del(self.changedItems['highlight'][themeName])
        #write changes
        idleConf.userCfg['highlight'].Save()
        #reload user theme list
        itemList = idleConf.GetSectionList('user', 'highlight')
        itemList.sort()
        if not itemList:
            self.radioThemeCustom.config(state=DISABLED)
            self.optMenuThemeCustom.SetMenu(itemList, '- no custom themes -')
        else:
            self.optMenuThemeCustom.SetMenu(itemList, itemList[0])
        #revert to default theme
        self.themeIsBuiltin.set(idleConf.defaultCfg['main'].Get('Theme', 'default'))
        self.builtinTheme.set(idleConf.defaultCfg['main'].Get('Theme', 'name'))
        #user can't back out of these changes, they must be applied now
        self.Apply()
        self.SetThemeType() 
Example 38
Project: pyblish-win   Author: pyblish   File: configDialog.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def UpdateUserHelpChangedItems(self):
        "Clear and rebuild the HelpFiles section in self.changedItems"
        self.changedItems['main']['HelpFiles'] = {}
        for num in range(1, len(self.userHelpList) + 1):
            self.AddChangedItem(
                    'main', 'HelpFiles', str(num),
                    ';'.join(self.userHelpList[num-1][:2])) 
Example 39
Project: pyblish-win   Author: pyblish   File: configDialog.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def LoadFontCfg(self):
        ##base editor font selection list
        fonts = list(tkFont.families(self))
        fonts.sort()
        for font in fonts:
            self.listFontName.insert(END, font)
        configuredFont = idleConf.GetOption(
                'main', 'EditorWindow', 'font', default='courier')
        lc_configuredFont = configuredFont.lower()
        self.fontName.set(lc_configuredFont)
        lc_fonts = [s.lower() for s in fonts]
        if lc_configuredFont in lc_fonts:
            currentFontIndex = lc_fonts.index(lc_configuredFont)
            self.listFontName.see(currentFontIndex)
            self.listFontName.select_set(currentFontIndex)
            self.listFontName.select_anchor(currentFontIndex)
        ##font size dropdown
        fontSize = idleConf.GetOption(
                'main', 'EditorWindow', 'font-size', type='int', default='10')
        self.optMenuFontSize.SetMenu(('7', '8', '9', '10', '11', '12', '13',
                                      '14', '16', '18', '20', '22'), fontSize )
        ##fontWeight
        self.fontBold.set(idleConf.GetOption(
                'main', 'EditorWindow', 'font-bold', default=0, type='bool'))
        ##font sample
        self.SetFontSample() 
Example 40
Project: pyblish-win   Author: pyblish   File: configDialog.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def LoadThemeCfg(self):
        ##current theme type radiobutton
        self.themeIsBuiltin.set(idleConf.GetOption(
                'main', 'Theme', 'default', type='bool', default=1))
        ##currently set theme
        currentOption = idleConf.CurrentTheme()
        ##load available theme option menus
        if self.themeIsBuiltin.get(): #default theme selected
            itemList = idleConf.GetSectionList('default', 'highlight')
            itemList.sort()
            self.optMenuThemeBuiltin.SetMenu(itemList, currentOption)
            itemList = idleConf.GetSectionList('user', 'highlight')
            itemList.sort()
            if not itemList:
                self.radioThemeCustom.config(state=DISABLED)
                self.customTheme.set('- no custom themes -')
            else:
                self.optMenuThemeCustom.SetMenu(itemList, itemList[0])
        else: #user theme selected
            itemList = idleConf.GetSectionList('user', 'highlight')
            itemList.sort()
            self.optMenuThemeCustom.SetMenu(itemList, currentOption)
            itemList = idleConf.GetSectionList('default', 'highlight')
            itemList.sort()
            self.optMenuThemeBuiltin.SetMenu(itemList, itemList[0])
        self.SetThemeType()
        ##load theme element option menu
        themeNames = self.themeElements.keys()
        themeNames.sort(key=lambda x: self.themeElements[x][1])
        self.optMenuHighlightTarget.SetMenu(themeNames, themeNames[0])
        self.PaintThemeSample()
        self.SetHighlightTarget() 
Example 41
Project: pyblish-win   Author: pyblish   File: configDialog.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def LoadKeyCfg(self):
        ##current keys type radiobutton
        self.keysAreBuiltin.set(idleConf.GetOption(
                'main', 'Keys', 'default', type='bool', default=1))
        ##currently set keys
        currentOption = idleConf.CurrentKeys()
        ##load available keyset option menus
        if self.keysAreBuiltin.get(): #default theme selected
            itemList = idleConf.GetSectionList('default', 'keys')
            itemList.sort()
            self.optMenuKeysBuiltin.SetMenu(itemList, currentOption)
            itemList = idleConf.GetSectionList('user', 'keys')
            itemList.sort()
            if not itemList:
                self.radioKeysCustom.config(state=DISABLED)
                self.customKeys.set('- no custom keys -')
            else:
                self.optMenuKeysCustom.SetMenu(itemList, itemList[0])
        else: #user key set selected
            itemList = idleConf.GetSectionList('user', 'keys')
            itemList.sort()
            self.optMenuKeysCustom.SetMenu(itemList, currentOption)
            itemList = idleConf.GetSectionList('default', 'keys')
            itemList.sort()
            self.optMenuKeysBuiltin.SetMenu(itemList, itemList[0])
        self.SetKeysType()
        ##load keyset element list
        keySetName = idleConf.CurrentKeys()
        self.LoadKeysList(keySetName) 
Example 42
Project: pyblish-win   Author: pyblish   File: test_idlehistory.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_init(self):
        self.assertIs(self.history.text, self.text)
        self.assertEqual(self.history.history, [])
        self.assertIsNone(self.history.prefix)
        self.assertIsNone(self.history.pointer)
        self.assertEqual(self.history.cyclic,
                idleConf.GetOption("main", "History",  "cyclic", 1, "bool")) 
Example 43
Project: SOFTX_2019_164   Author: ElsevierSoftwareX   File: test_spharabasis.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_basis_unit_result(self):
        """Class SpharaBasis, method basis, mode='unit', triangular test mesh

        Determine the SPHARA basis with unit edge weight for a
        triangular mesh with 118 vertices. The valid basis vectors of
        the SPHARA basis can point in opposite directions
        (multiplication by -1). To compare the calculated basis with
        the reference basis, the transposed matrix of the calculated
        basis is multiplied by the matrix of the reference basis. If
        the calculated basis is correct, then the result matrix of the
        matrix multiplication contains only the elements 1 and -1 at
        the main diagonal, all other elements of the matrix are 0 or
        very small.

        """
        testtrimesh = tm.TriMesh(self.testdatatriangles,
                                 self.testdatavertices)
        sb_unit = sb.SpharaBasis(testtrimesh, mode='unit')
        sb_unit_fun, sb_unit_freq = sb_unit.basis()
        self.assertTrue(
            np.allclose(np.absolute(np.matmul
                                    (np.transpose(sb_unit_fun),
                                     self.testdataspharabasisunitweight)),
                        np.identity(np.size(sb_unit_freq)))
            and
            np.allclose(sb_unit_freq, self.testdataspharanatfrequnitweight)
        ) 
Example 44
Project: SOFTX_2019_164   Author: ElsevierSoftwareX   File: test_spharabasis.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_basis_ie_result(self):
        """Class SpharaBasis, method basis, mode='inv_euclidean', triangular
        test mesh

        Determine the SPHARA basis with inverse euclidean edge weight
        for a triangular mesh with 118 vertices. The valid basis
        vectors of the SPHARA basis can point in opposite directions
        (multiplication by -1). To compare the calculated basis with
        the reference basis, the transposed matrix of the calculated
        basis is multiplied by the matrix of the reference basis. If
        the calculated basis is correct, then the result matrix of the
        matrix multiplication contains only the elements 1 and -1 at
        the main diagonal, all other elements of the matrix are 0 or
        very small.

        """
        testtrimesh = tm.TriMesh(self.testdatatriangles,
                                 self.testdatavertices)
        sb_ie = sb.SpharaBasis(testtrimesh, mode='inv_euclidean')
        sb_ie_fun, sb_ie_freq = sb_ie.basis()
        self.assertTrue(
            np.allclose(np.absolute(np.matmul
                                    (np.transpose(sb_ie_fun),
                                     self.testdataspharabasisieweight)),
                        np.identity(np.size(sb_ie_freq)))
            and
            np.allclose(sb_ie_freq, self.testdataspharanatfreqieweight)
        ) 
Example 45
Project: SOFTX_2019_164   Author: ElsevierSoftwareX   File: test_spharabasis.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_basis_fem_result(self):
        """Class SpharaBasis, method basis, mode='fem', triangular test mesh

        Determine the SPHARA basis with FEM discretization for a
        triangular mesh with 118 vertices. The valid basis vectors of
        the SPHARA basis can point in opposite directions
        (multiplication by -1). To compare the calculated basis with
        the reference basis, the transposed matrix of the calculated
        basis is multiplied by the matrix of the reference basis. If
        the calculated basis is correct, then the result matrix of the
        matrix multiplication contains only the elements 1 and -1 at
        the main diagonal, all other elements of the matrix are 0 or
        very small.

        """
        testtrimesh = tm.TriMesh(self.testdatatriangles,
                                 self.testdatavertices)
        sb_fem = sb.SpharaBasis(testtrimesh, mode='fem')
        sb_fem_fun, sb_fem_freq = sb_fem.basis()
        self.assertTrue(
            np.allclose(np.absolute(np.matmul(np.matmul
                                    (np.transpose(sb_fem_fun),
                                     self.testdatamassmatrix),
                                     self.testdataspharabasisfemweight)),
                        np.identity(np.size(sb_fem_freq)))
            and
            np.allclose(sb_fem_freq, self.testdataspharanatfreqfemweight)
        ) 
Example 46
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def main():
    """Runs the testsuite as command line application."""
    try:
        unittest.main(testLoader=BetterLoader(), defaultTest='suite')
    except Exception as e:
        print('Error: %s' % e) 
Example 47
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def main():
    """Runs the testsuite as command line application."""
    try:
        unittest.main(testLoader=BetterLoader(), defaultTest='suite')
    except Exception as e:
        print('Error: %s' % e) 
Example 48
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def main():
    """Runs the testsuite as command line application."""
    try:
        unittest.main(testLoader=BetterLoader(), defaultTest='suite')
    except Exception as e:
        print('Error: %s' % e) 
Example 49
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def main():
    """Runs the testsuite as command line application."""
    try:
        unittest.main(testLoader=BetterLoader(), defaultTest='suite')
    except Exception as e:
        print('Error: %s' % e) 
Example 50
Project: flasky   Author: RoseOu   File: __init__.py    MIT License 5 votes vote down vote up
def main():
    """Runs the testsuite as command line application."""
    try:
        unittest.main(testLoader=BetterLoader(), defaultTest='suite')
    except Exception as e:
        print('Error: %s' % e) 
Example 51
Project: flasky   Author: RoseOu   File: __init__.py    MIT License 5 votes vote down vote up
def main():
    """Runs the testsuite as command line application."""
    try:
        unittest.main(testLoader=BetterLoader(), defaultTest='suite')
    except Exception as e:
        print('Error: %s' % e) 
Example 52
Project: fishroom   Author: tuna   File: telegram.py    GNU General Public License v3.0 5 votes vote down vote up
def main():
    if "telegram" not in config:
        return

    from .runner import run_threads
    tg, im2fish_bus, fish2im_bus = init()
    run_threads([
        (Telegram2FishroomThread, (tg, im2fish_bus, ), ),
        (Fishroom2TelegramThread, (tg, fish2im_bus, ), ),
    ]) 
Example 53
Project: fishroom   Author: tuna   File: telegram.py    GNU General Public License v3.0 5 votes vote down vote up
def test():
    unittest.main()

    from .photostore import VimCN

    tele = Telegram(config['telegram']['token'],
                    nick_store=MemNickStore(), photo_store=VimCN())
    # tele.send_msg('user#67655173', 'hello')
    tele.send_photo('-34678255', open('test.png', 'rb').read())
    tele.send_msg('-34678255', "Back!")
    for msg in tele.message_stream():
        print(msg.dumps())
        tele.send_msg(msg.receiver, msg.content)
    return 
Example 54
Project: sic   Author: Yanixos   File: py31compat.py    GNU General Public License v3.0 5 votes vote down vote up
def unittest_main(*args, **kwargs):
        if 'testRunner' in kwargs and kwargs['testRunner'] is None:
            kwargs['testRunner'] = unittest.TextTestRunner
        return unittest.main(*args, **kwargs) 
Example 55
Project: bigquerylayers   Author: smandaric   File: test.py    GNU General Public License v3.0 5 votes vote down vote up
def run_tests(self):
        # Purge modules under test from sys.modules. The test loader will
        # re-import them from the build location. Required when 2to3 is used
        # with namespace packages.
        if six.PY3 and getattr(self.distribution, 'use_2to3', False):
            module = self.test_suite.split('.')[0]
            if module in _namespace_packages:
                del_modules = []
                if module in sys.modules:
                    del_modules.append(module)
                module += '.'
                for name in sys.modules:
                    if name.startswith(module):
                        del_modules.append(name)
                list(map(sys.modules.__delitem__, del_modules))

        test = unittest.main(
            None, None, self._argv,
            testLoader=self._resolve_as_ep(self.test_loader),
            testRunner=self._resolve_as_ep(self.test_runner),
            exit=False,
        )
        if not test.result.wasSuccessful():
            msg = 'Test failed: %s' % test.result
            self.announce(msg, log.ERROR)
            raise DistutilsError(msg) 
Example 56
Project: AshsSDK   Author: thehappydinoa   File: py31compat.py    MIT License 5 votes vote down vote up
def unittest_main(*args, **kwargs):
        if 'testRunner' in kwargs and kwargs['testRunner'] is None:
            kwargs['testRunner'] = unittest.TextTestRunner
        return unittest.main(*args, **kwargs) 
Example 57
Project: reportengine   Author: NNPDF   File: test_configparser.py    GNU General Public License v2.0 5 votes vote down vote up
def test_rewrite_actions():
    inp = {'actions_': [{'pdfs':[{'report':{'main':True}}]}, {'fits':{'fitcontext': ['fits_chi2_table']}}]}
    c = BaseConfig(inp)
    r = c.parse_actions_(inp['actions_'])
    suggested_yaml = c._rewrite_old_actions(r)
    newacts = yaml.safe_load(suggested_yaml)
    newr = c.parse_actions_(newacts['actions_'])
    assert newr == r 
Example 58
Project: Cryptchat   Author: djohsson   File: test_diffiehellman.py    MIT License 5 votes vote down vote up
def main():
    unittest.main() 
Example 59
Project: Cryptchat   Author: djohsson   File: test_networkhandler.py    MIT License 5 votes vote down vote up
def main():
    unittest.main() 
Example 60
Project: Cryptchat   Author: djohsson   File: test_aes.py    MIT License 5 votes vote down vote up
def main():
    unittest.main() 
Example 61
Project: mimic   Author: googlearchive   File: target_info_test.py    Apache License 2.0 5 votes vote down vote up
def testCGIScript(self):
    config = yaml.load(APP_YAML)
    handler = {'url': '/', 'script': 'main.py'}
    config['handlers'] = [handler]
    # CGI handlers supported only when threadsafe is false
    config['threadsafe'] = False
    target_info._ValidateConfig(config) 
Example 62
Project: mimic   Author: googlearchive   File: target_info_test.py    Apache License 2.0 5 votes vote down vote up
def testWSGIScript(self):
    config = yaml.load(APP_YAML)
    handler = {'url': '/', 'script': 'main.app'}
    config['handlers'] = [handler]
    target_info._ValidateConfig(config) 
Example 63
Project: mimic   Author: googlearchive   File: target_info_test.py    Apache License 2.0 5 votes vote down vote up
def testCGIScriptRaisesValidationError(self):
    config = yaml.load(APP_YAML)
    handler = {'url': '/', 'script': 'main.py'}
    config['handlers'] = [handler]
    # CGI handlers aren't supported when threadsafe is true
    self.assertRaises(target_info.ValidationError, target_info._ValidateConfig,
                      config) 
Example 64
Project: mimic   Author: googlearchive   File: target_info_test.py    Apache License 2.0 5 votes vote down vote up
def testLogin(self):
    def Check(handler):
      config = yaml.load(APP_YAML)
      config['handlers'] = [handler]
      handler['login'] = 'required'
      target_info._ValidateConfig(config)
      handler['login'] = 'admin'
      target_info._ValidateConfig(config)
      handler['login'] = 'not-valid'
      self.assertRaises(target_info.ValidationError,
                        target_info._ValidateConfig, config)

    Check({'url': '/', 'script': 'main.app'})
    Check({'url': '/', 'static_files': 'index.html', 'upload': 'index.html'})
    Check({'url': '/', 'static_dir': 'static'}) 
Example 65
Project: mimic   Author: googlearchive   File: target_info_test.py    Apache License 2.0 5 votes vote down vote up
def testMimeTypeOnScript(self):
    config = yaml.load(APP_YAML)
    handler = {'url': '/', 'script': 'main.py',
               'mime_type': 'text/plain; charset=utf-8'}
    config['handlers'] = [handler]
    self.assertRaises(target_info.ValidationError,
                      target_info._ValidateConfig, config) 
Example 66
Project: mimic   Author: googlearchive   File: target_env_test.py    Apache License 2.0 5 votes vote down vote up
def testImportPackageInsidePackage(self):
    self._env._TearDown()  # RunScript will set up the env
    self._tree.SetFile('main.py', """
_test_portal.files.append(__file__)
# spam will in turn import eggs which should be 'spam.eggs', not 'eggs'
import spam
# confirm that there is indeed a top level 'eggs'
# without this, the 'import eggs' test in spam would be incomplete
import eggs
""")
    self._tree.SetFile('spam/__init__.py', """
_test_portal.files.append(__file__)
# should import eggs from spam
import eggs
""")
    self._tree.SetFile('spam/eggs/__init__.py', """
_test_portal.files.append(__file__)
""")
    self._tree.SetFile('eggs/__init__.py', """
_test_portal.files.append(__file__)
""")
    _test_portal.files = []
    self._env.RunScript('main.py', CollectingHandler())
    self.assertEquals(['/target/main.py',
                       # 'import spam' in main.py
                       '/target/spam/__init__.py',
                       # 'import eggs' in spam/__init__.py
                       '/target/spam/eggs/__init__.py',
                       # 'import eggs' in main.py
                       '/target/eggs/__init__.py'],
                      _test_portal.files) 
Example 67
Project: mimic   Author: googlearchive   File: target_env_test.py    Apache License 2.0 5 votes vote down vote up
def testImportModuleInsidePackage(self):
    self._env._TearDown()  # RunScript will set up the env
    self._tree.SetFile('main.py', """
_test_portal.files.append(__file__)
# spam will in turn import eggs which should be 'spam.eggs', not 'eggs'
import spam
# confirm that there is indeed a top level 'eggs'
# without this, the 'import eggs' test in spam would be incomplete
import eggs
""")
    self._tree.SetFile('spam/__init__.py', """
_test_portal.files.append(__file__)
# should import eggs from spam
import eggs
""")
    self._tree.SetFile('spam/eggs.py', """
_test_portal.files.append(__file__)
""")
    self._tree.SetFile('eggs.py', """
_test_portal.files.append(__file__)
""")
    _test_portal.files = []
    self._env.RunScript('main.py', CollectingHandler())
    self.assertEquals(['/target/main.py',
                       # 'import spam' in main.py
                       '/target/spam/__init__.py',
                       # 'import eggs' in spam/__init__.py
                       '/target/spam/eggs.py',
                       # 'import eggs' in main.py
                       '/target/eggs.py'],
                      _test_portal.files) 
Example 68
Project: mimic   Author: googlearchive   File: target_env_test.py    Apache License 2.0 5 votes vote down vote up
def testRunScript(self):
    self._env._TearDown()  # RunScript will set up the env
    self._tree.SetFile('d/foo.py', _SIMPLE_D_FOO)
    level = logging.getLogger().level
    self.assertTrue(level > logging.DEBUG)  # should be true in a test
    handler = CollectingHandler()
    self._env.RunScript('d/foo.py', handler)
    module = _test_portal.main
    self.assertEquals('__main__', module.__name__)
    self.assertEquals('/target/d/foo.py', module.__file__)
    # check that logging handler was invoked
    self.assertEquals(1, len(handler.records))
    self.assertEquals('running foo.py', handler.records[0].getMessage())
    # check logging cleanup
    self.assertEquals(level, logging.getLogger().level) 
Example 69
Project: mimic   Author: googlearchive   File: target_env_test.py    Apache License 2.0 5 votes vote down vote up
def testMimicMainNotInSysModules(self):
    self._env._TearDown()  # RunScript will set up the env
    self._tree.SetFile('main.py', """
import logging
logging.debug('running main.py')
_test_portal.main_was_imported = True
""")
    self._tree.SetFile('d/foo.py', """
import logging
_test_portal.main_was_imported = False
# should be our main.py, not mimic's
import main
logging.debug('running foo.py')
""")
    level = logging.getLogger().level
    self.assertTrue(level > logging.DEBUG)  # should be true in a test
    handler = CollectingHandler()
    # pollute sys.modules['main'] in the same way mimic's main.py does
    sys.modules['main'] = target_env
    self._env.RunScript('d/foo.py', handler)
    self.assertTrue(_test_portal.main_was_imported)
    # check that logging handler was invoked
    self.assertEquals(2, len(handler.records))
    self.assertEquals('running main.py', handler.records[0].getMessage())
    self.assertEquals('running foo.py', handler.records[1].getMessage())
    # check logging cleanup
    self.assertEquals(level, logging.getLogger().level) 
Example 70
Project: mimic   Author: googlearchive   File: target_env_test.py    Apache License 2.0 5 votes vote down vote up
def testWsgiAppInPackageModule(self):
    self._env._TearDown()  # RunScript will set up the env
    self._tree.SetFile('foo/bar.py', _WSGI_MAIN)
    level = logging.getLogger().level
    self.assertTrue(level > logging.DEBUG)  # should be true in a test
    handler = CollectingHandler()

    os.environ['REQUEST_METHOD'] = 'GET'
    os.environ['PATH_INFO'] = '/foo.bar.APP'
    self._env.RunScript('foo.bar.APP', handler)

    module_main = _test_portal.main
    self.assertEquals('__main__', module_main.__name__)
    self.assertIsNotNone(module_main.APP)
    self.assertEquals('/target/foo/bar.py', module_main.__file__)

    self.assertEquals(module_main.APP, _test_portal.APP)

    # check that logging handler was invoked
    self.assertEquals(2, len(handler.records))
    self.assertEquals('running /target/foo/bar.py', handler.records[0].getMessage())
    self.assertEquals('handling GET request', handler.records[1].getMessage())
    # check logging cleanup
    self.assertEquals(level, logging.getLogger().level)

    self.assertEquals('Status: 200 OK\n'
                      'Content-Type: text/html; charset=utf-8\n'
                      'Cache-Control: no-cache\n'
                      'Content-Length: 18\n\n'
                      'main-response-body', self._output.getvalue()) 
Example 71
Project: mimic   Author: googlearchive   File: target_env_test.py    Apache License 2.0 5 votes vote down vote up
def testWsgiAppInImpliedPackage(self):
    self._env._TearDown()  # RunScript will set up the env
    self._tree.SetFile('foo/bar/__init__.py', _WSGI_MAIN)
    level = logging.getLogger().level
    self.assertTrue(level > logging.DEBUG)  # should be true in a test
    handler = CollectingHandler()

    os.environ['REQUEST_METHOD'] = 'GET'
    os.environ['PATH_INFO'] = '/foo.bar.APP'
    self._env.RunScript('foo.bar.APP', handler)

    module_main = _test_portal.main
    self.assertEquals('__main__', module_main.__name__)
    self.assertIsNotNone(module_main.APP)
    self.assertEquals('/target/foo/bar/__init__.py', module_main.__file__)

    self.assertEquals(module_main.APP, _test_portal.APP)

    # check that logging handler was invoked
    self.assertEquals(2, len(handler.records))
    self.assertEquals('running /target/foo/bar/__init__.py', handler.records[0].getMessage())
    self.assertEquals('handling GET request', handler.records[1].getMessage())
    # check logging cleanup
    self.assertEquals(level, logging.getLogger().level)

    self.assertEquals('Status: 200 OK\n'
                      'Content-Type: text/html; charset=utf-8\n'
                      'Cache-Control: no-cache\n'
                      'Content-Length: 18\n\n'
                      'main-response-body', self._output.getvalue()) 
Example 72
Project: mimic   Author: googlearchive   File: target_env_test.py    Apache License 2.0 5 votes vote down vote up
def testWsgiMiddleware(self):
    self._env._TearDown()  # RunScript will set up the env
    self._tree.SetFile('appengine_config.py', _WSGI_MIDDLEWARE_APPENGINE_CONFIG)
    self._tree.SetFile('main.py', _WSGI_MAIN)
    level = logging.getLogger().level
    self.assertTrue(level > logging.DEBUG)  # should be true in a test
    handler = CollectingHandler()
    self._env.RunScript('main.APP', handler)

    module_main = _test_portal.main
    self.assertEquals('__main__', module_main.__name__)
    self.assertIsNotNone(module_main.APP)
    self.assertEquals('/target/main.py', module_main.__file__)

    module_appengine_config = _test_portal.appengine_config
    self.assertEquals('appengine_config', module_appengine_config.__name__)
    self.assertIsNotNone(module_appengine_config.webapp_add_wsgi_middleware)
    self.assertEquals(module_main.APP, _test_portal.original_app)
    self.assertEquals('/target/appengine_config.py',
                      module_appengine_config.__file__)

    # check that logging handler was invoked
    self.assertEquals(5, len(handler.records))
    self.assertEquals('running appengine_config.py with simple WSGI middleware',
                      handler.records[0].getMessage())
    self.assertEquals('running /target/main.py', handler.records[1].getMessage())
    self.assertEquals('webapp_add_wsgi_middleware called',
                      handler.records[2].getMessage())
    self.assertEquals('handling GET request', handler.records[3].getMessage())
    self.assertEquals('middleware modified body',
                      handler.records[4].getMessage())
    # check logging cleanup
    self.assertEquals(level, logging.getLogger().level)

    self.assertEquals('Status: 200 OK\n'
                      'Content-Type: text/html; charset=utf-8\n'
                      'Cache-Control: no-cache\n'
                      'Content-Length: 29\n\n'
                      'I WUZ HERE main-response-body', self._output.getvalue()) 
Example 73
Project: mimic   Author: googlearchive   File: target_env_test.py    Apache License 2.0 5 votes vote down vote up
def testStatOnStaticFile(self):
    """Tests that patched stat raises an OSError on a static file."""
    self._env._TearDown()  # RunScript will set up the env
    self._tree.SetFile('static/index.html', 'index text')
    self._tree.SetFile('main.py', """
import os
import logging

for path in ('static/index.html', 'stylesheets/main.css'):
  try:
    # this is in the target file system, but matched by a static handler
    os.stat(path)
  except OSError, e:
    logging.info('got OSError')

  path = os.path.join(os.path.dirname(__file__), path)
  try:
    # this is in the target file system, but matched by a static handler, and
    # should be prefixed by "/target"
    os.stat(path)
  except OSError, e:
    logging.info('got OSError')
""")
    handler = CollectingHandler()
    self._env.RunScript('main.py', handler)
    # two for 'static/index.html', and two for 'stylesheets/main.css'
    self.assertEqual('got OSError', handler.records[0].getMessage())
    self.assertEqual('got OSError', handler.records[1].getMessage())
    self.assertEqual('got OSError', handler.records[2].getMessage())
    self.assertEqual('got OSError', handler.records[3].getMessage()) 
Example 74
Project: mimic   Author: googlearchive   File: mimic_test.py    Apache License 2.0 5 votes vote down vote up
def testMainCgiWsgiScript(self):
    self._AddFile('app.yaml', _GENERIC_APP_YAML)
    self._AddFile('main_cgi_wsgi.py', _MAIN_CGI_WSGI_SCRIPT)
    self._CallMimic('/main_cgi_wsgi.py')
    self._CheckResponse(httplib.OK, 'text/plain; charset=utf-8')
    self.assertEquals('Hello, main cgi wsgi\n', self._body) 
Example 75
Project: mimic   Author: googlearchive   File: mimic_test.py    Apache License 2.0 5 votes vote down vote up
def testNoDefaultContentType(self):
    self._AddFile('app.yaml', _GENERIC_APP_YAML)
    # Script which does not print any HTTP repsonse headers.
    self._AddFile('main.py', r'print "hello"')
    self._CallMimic('/main.py')
    # Mimic should not add a default Content-Type header.
    self._CheckResponse(httplib.OK, None)
    self.assertEquals('hello\n', self._body) 
Example 76
Project: mimic   Author: googlearchive   File: mimic_test.py    Apache License 2.0 5 votes vote down vote up
def testCgiPageNotFound(self):
    self._AddFile('app.yaml', _GENERIC_APP_YAML)
    self._CallMimic('/main.py')
    self._CheckResponse(httplib.NOT_FOUND, 'text/plain; charset=utf-8') 
Example 77
Project: mimic   Author: googlearchive   File: mimic_test.py    Apache License 2.0 5 votes vote down vote up
def testScritPageLoginRequired(self):
    self._users_mod.set_current_user(FakeUser('Bob'))
    self._AddFile('app.yaml', MakeAppYaml(login='required'))
    self._AddFile('main.py', _SIMPLE_CGI_SCRIPT)
    self._CallMimic('/main.py')
    self._CheckResponse(httplib.OK, 'text/plain; charset=utf-8')
    self.assertEquals('hello\n', self._body) 
Example 78
Project: mimic   Author: googlearchive   File: mimic_test.py    Apache License 2.0 5 votes vote down vote up
def testScritPageLoginRequiredForbidden(self):
    self._AddFile('app.yaml', MakeAppYaml(login='required'))
    self._AddFile('main.py', _SIMPLE_CGI_SCRIPT)
    self._CallMimic('/main.py')
    self._CheckResponse(httplib.FORBIDDEN, 'text/html; charset=utf-8') 
Example 79
Project: mimic   Author: googlearchive   File: mimic_test.py    Apache License 2.0 5 votes vote down vote up
def testCgiPageLoginAdmin(self):
    self._users_mod.set_current_user_is_admin(True)
    self._users_mod.set_current_user(FakeUser('Bob'))
    self._AddFile('app.yaml', MakeAppYaml(login='admin'))
    self._AddFile('main.py', _SIMPLE_CGI_SCRIPT)
    self._CallMimic('/main.py')
    self._CheckResponse(httplib.OK, 'text/plain; charset=utf-8')
    self.assertEquals('hello\n', self._body) 
Example 80
Project: mimic   Author: googlearchive   File: target_env_test.py    Apache License 2.0 4 votes vote down vote up
def testOpenStaticFile(self):
    self._env._TearDown()  # RunScript will set up the env
    self._tree.SetFile('template.html', 'template text')
    self._tree.SetFile('static/index.html', 'index text')
    self._tree.SetFile('main.py', """
import logging
import os

# this should be fine
f = open('template.html')
logging.info(f.read())

try:
  open('static/index.html')
except IOError, e:
  logging.error('got IOError: ' + str(e.errno))

# results in "/target/static/index.html"
path = os.path.join(os.path.dirname(__file__), 'static/index.html')
try:
  open(path)
except IOError, e:
  logging.error('got IOError: ' + str(e.errno))

try:
  # should match static_dir
  open('stylesheets/main.css')
except IOError, e:
  logging.error('got IOError: ' + str(e.errno))

try:
  # doesn't exist
  open('/static/index.html')
except IOError, e:
  logging.error('got IOError: ' + str(e.errno))
""")
    handler = CollectingHandler()
    self._env.RunScript('main.py', handler)
    self.assertEqual('template text', handler.records[0].getMessage())
    no_ent_error_msg = 'got IOError: ' + str(errno.ENOENT)
    self.assertEqual(no_ent_error_msg, handler.records[1].getMessage())
    self.assertEqual(no_ent_error_msg, handler.records[2].getMessage())
    self.assertEqual(no_ent_error_msg, handler.records[3].getMessage())
    self.assertEqual(no_ent_error_msg, handler.records[4].getMessage())