<commit_before>#!/usr/bin/env python

import ConfigParser, os, requests

def parse_docs():

    config = ConfigParser.RawConfigParser(allow_no_value=True)
    config.read('.sauce.ini')

    if not config.getboolean('Docs', 'enable'):
        return None

    branch = config.get('Docs', 'branch')

    deploy_docs = {
        "provider": "script",
        "script": "./.sauce/travis/deploy_docs.sh",
        "skip_cleanup": "true",
        "on": {}
    }

    if branch:
        deploy_docs["on"]["branch"] = branch
    else:
        deploy_docs["on"]["all_branches"] = "true"

    #return deploy_docs
    return ["sh ./.sauce/travis/deploy_docs.sh"]

def get_github_description(api_token):

    headers = {
        "Accept": "application/vnd.github.v3+json",
        "Authorization": "token %s" % api_token,
        "User-Agent": os.environ["TRAVIS_REPO_SLUG"].split("/")[0]
    }

    url = "https://api.github.com/repos/%s" % os.environ["TRAVIS_REPO_SLUG"]

    response = requests.get(url, headers=headers)

    if response.status_code != requests.codes.ok:
        print '------------------------------------------------------------------------------------------------------------------------'
        print "Response status code: %s" % response.status_code
        print '------------------------------------------------------------------------------------------------------------------------'
        print "Response history: %s" % response.history
        print '------------------------------------------------------------------------------------------------------------------------'
        raise response.raise_for_status()

    print response
    print response[description]
    return response["description"]

def parse_docs_options(api_token):

    config = ConfigParser.RawConfigParser(allow_no_value=True)
    config.read('.sauce.ini')

    options = []

    projectname = config.get('Docs', 'projectname')
    description = config.get('Docs', 'description')
    logo = config.get('Docs', 'logo')

    include_non_documented = config.getboolean('Docs', 'include_non_documented')
    include_privates = config.getboolean('Docs', 'include_privates')
    include_nav_panel = config.getboolean('Docs', 'include_nav_panel')
    include_search = config.getboolean('Docs', 'include_search')
    gen_diagrams = config.getboolean('Docs', 'gen_diagrams')

    if projectname:
        options.append("projectname=%s" % projectname)
    else:
        options.append("projectname=%s" % os.environ["TRAVIS_REPO_SLUG"].split("/")[1]) #repo name!

    if description:
        options.append("description=%s" % description)
    else:
        options.append("description=%s" % get_github_description(api_token))

    if logo:
        options.append("logo=%s" % logo)
    else:
        options.append("logo=") #I hope this doesn't throw an error.

    if include_non_documented:
        options.append("include_non_documented=YES")
    else:
        options.append("include_non_documented=NO")

    if include_privates:
        options.append("include_privates=YES")
    else:
        options.append("include_privates=NO")

    if include_nav_panel:
        options.append("include_nav_panel=YES")
    else:
        options.append("include_nav_panel=NO")

    if include_search:
        options.append("include_search=YES")
    else:
        options.append("include_search=NO")

    if gen_diagrams:
        options.append("gen_diagrams=YES")
        options.append("class_diagrams=NO") #this is just the opposite of the dot graphs - I set it to the opposite here just because it's easier than at deployment
    else:
        options.append("gen_diagrams=NO")
        options.append("class_diagrams=YES")

    return options

<commit_msg>Get request to github changed to use github token.<commit_after>#!/usr/bin/env python

import ConfigParser, os, requests

def parse_docs():

    config = ConfigParser.RawConfigParser(allow_no_value=True)
    config.read('.sauce.ini')

    if not config.getboolean('Docs', 'enable'):
        return None

    branch = config.get('Docs', 'branch')

    deploy_docs = {
        "provider": "script",
        "script": "./.sauce/travis/deploy_docs.sh",
        "skip_cleanup": "true",
        "on": {}
    }

    if branch:
        deploy_docs["on"]["branch"] = branch
    else:
        deploy_docs["on"]["all_branches"] = "true"

    #return deploy_docs
    return ["sh ./.sauce/travis/deploy_docs.sh"]

def get_github_description(api_token):

    headers = {
        "Accept": "application/vnd.github.v3+json",
        "Authorization": "token %s" % os.environ["GH_TOKEN"],
        "User-Agent": os.environ["TRAVIS_REPO_SLUG"].split("/")[0]
    }

    url = "https://api.github.com/repos/%s" % os.environ["TRAVIS_REPO_SLUG"]

    response = requests.get(url, headers=headers)

    if response.status_code != requests.codes.ok:
        print '------------------------------------------------------------------------------------------------------------------------'
        print "Response status code: %s" % response.status_code
        print '------------------------------------------------------------------------------------------------------------------------'
        print "Response history: %s" % response.history
        print '------------------------------------------------------------------------------------------------------------------------'
        raise response.raise_for_status()

    print response
    print response[description]
    return response["description"]

def parse_docs_options(api_token):

    config = ConfigParser.RawConfigParser(allow_no_value=True)
    config.read('.sauce.ini')

    options = []

    projectname = config.get('Docs', 'projectname')
    description = config.get('Docs', 'description')
    logo = config.get('Docs', 'logo')

    include_non_documented = config.getboolean('Docs', 'include_non_documented')
    include_privates = config.getboolean('Docs', 'include_privates')
    include_nav_panel = config.getboolean('Docs', 'include_nav_panel')
    include_search = config.getboolean('Docs', 'include_search')
    gen_diagrams = config.getboolean('Docs', 'gen_diagrams')

    if projectname:
        options.append("projectname=%s" % projectname)
    else:
        options.append("projectname=%s" % os.environ["TRAVIS_REPO_SLUG"].split("/")[1]) #repo name!

    if description:
        options.append("description=%s" % description)
    else:
        options.append("description=%s" % get_github_description(api_token))

    if logo:
        options.append("logo=%s" % logo)
    else:
        options.append("logo=") #I hope this doesn't throw an error.

    if include_non_documented:
        options.append("include_non_documented=YES")
    else:
        options.append("include_non_documented=NO")

    if include_privates:
        options.append("include_privates=YES")
    else:
        options.append("include_privates=NO")

    if include_nav_panel:
        options.append("include_nav_panel=YES")
    else:
        options.append("include_nav_panel=NO")

    if include_search:
        options.append("include_search=YES")
    else:
        options.append("include_search=NO")

    if gen_diagrams:
        options.append("gen_diagrams=YES")
        options.append("class_diagrams=NO") #this is just the opposite of the dot graphs - I set it to the opposite here just because it's easier than at deployment
    else:
        options.append("gen_diagrams=NO")
        options.append("class_diagrams=YES")

    return options

<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
#
# Copyright (C) 2005-2009 Edgewall Software
# Copyright (C) 2005-2007 Christopher Lenz <cmlenz@gmx.de>
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://trac.edgewall.org/wiki/TracLicense.
#
# This software consists of voluntary contributions made by many
# individuals. For the exact contribution history, see the revision
# history and logs, available at http://trac.edgewall.org/log/.

import os
from StringIO import StringIO
import tempfile
import time
import unittest

from trac.config import *
from trac.test import Configuration

class ConfigurationTestCase(unittest.TestCase):

    def setUp(self):
        self.filename = os.path.join(tempfile.gettempdir(), 'trac-test.ini')
        self._write([])
        self._orig_registry = Option.registry
        Option.registry = {}

    def tearDown(self):
        Option.registry = self._orig_registry
        os.remove(self.filename)

    def _read(self):
        return Configuration(self.filename)

    def _write(self, lines):
        fileobj = open(self.filename, 'w')
        try:
            fileobj.write('\n'.join(lines + ['']))
        finally:
            fileobj.close()

    def test_default(self):
        config = self._read()
        self.assertEquals('', config.get('a', 'option'))
        self.assertEquals('value', config.get('a', 'option', 'value'))

        class Foo(object):
            option_a = Option('a', 'option', 'value')

        self.assertEquals('value', config.get('a', 'option'))

    def test_default_bool(self):
        config = self._read()
        self.assertEquals(False, config.getbool('a', 'option'))
        self.assertEquals(True, config.getbool('a', 'option', 'yes'))
        self.assertEquals(True, config.getbool('a', 'option', 1))

        class Foo(object):
            option_a = Option('a', 'option', 'true')

        self.assertEquals(True, config.getbool('a', 'option'))

    def test_default_int(self):
        config = self._read()
        self.assertRaises(ConfigurationError, config.getint, 'a', 'option', 'b')
        self.assertEquals(0, config.getint('a', 'option'))
        self.assertEquals(1, config.getint('a', 'option', '1'))
        self.assertEquals(1, config.getint('a', 'option', 1))

        class Foo(object):
            option_a = Option('a', 'option', '2')

        self.assertEquals(2, config.getint('a', 'option'))

    def test_default_path(self):
        config = self._read()
        class Foo(object):
            option_a = PathOption('a', 'opt1', 'file.ini')
            option_b = PathOption('a', 'opt2', '/somewhere/file.ini')
        self.assertEquals('file.ini', config.get('a', 'opt1'))
        self.assertNotEquals('file.ini', config.getpath('a', 'opt1'))
        self.assertTrue(config.getpath('a', 'opt1').startswith('/'))
        self.assertEquals('/somewhere/file.ini', config.getpath('a', 'opt2'))
        self.assertEquals('/none.ini', config.getpath('a', 'opt3', '/none.ini'))
        self.assertNotEquals('none.ini', config.getpath('a', 'opt3', 'none.ini'))

    def test_read_and_get(self):
        self._write(['[a]', 'option = x'])
        config = self._read()
        self.assertEquals('x', config.get('a', 'option'))
        self.assertEquals('x', config.get('a', 'option', 'y'))
        self.assertEquals('y', config.get('b', 'option2', 'y'))

    def test_read_and_getbool(self):
        self._write(['[a]', 'option = yes'])
        config = self._read()
        self.assertEquals(True, config.getbool('a', 'option'))
        self.assertEquals(True, config.getbool('a', 'option', False))
        self.assertEquals(False, config.getbool('b', 'option2'))
        self.assertEquals(False, config.getbool('b', 'option2', False))
        self.assertEquals(False, config.getbool('b', 'option2', 'disabled'))

    def test_read_and_getint(self):
        self._write(['[a]', 'option = 42'])
        config = self._read()
        self.assertEquals(42, config.getint('a', 'option'))
        self.assertEquals(42, config.getint('a', 'option', 25))
        self.assertEquals(0, config.getint('b', 'option2'))
        self.assertEquals(25, config.getint('b', 'option2', 25))
        self.assertEquals(25, config.getint('b', 'option2', '25'))

    def test_read_and_getlist(self):
        self._write(['[a]', 'option = foo, bar, baz'])
        config = self._read()
        self.assertEquals(['foo', 'bar', 'baz'],
                          config.getlist('a', 'option'))
        self.assertEquals([],
                          config.getlist('b', 'option2'))
        self.assertEquals(['foo', 'bar', 'baz'],
                    config.getlist('b', 'option2', ['foo', 'bar', 'baz']))
        self.assertEquals(['foo', 'bar', 'baz'],
                    config.getlist('b', 'option2', 'foo, bar, baz'))

    def test_read_and_getlist_sep(self):
        self._write(['[a]', 'option = foo | bar | baz'])
        config = self._read()
        self.assertEquals(['foo', 'bar', 'baz'],
                          config.getlist('a', 'option', sep='|'))

    def test_read_and_getlist_keep_empty(self):
        self._write(['[a]', 'option = ,bar,baz'])
        config = self._read()
        self.assertEquals(['bar', 'baz'], config.getlist('a', 'option'))
        self.assertEquals(['', 'bar', 'baz'],
                          config.getlist('a', 'option', keep_empty=True))

    def test_getpath(self):
        config = self._read()
        config.set('a', 'path_a', '/somewhere/file.txt')
        config.set('a', 'path_b', 'file.txt')
        config.set('a', 'path_c', './file.txt')
        self.assertEquals('/somewhere/file.txt', config.getpath('a', 'path_a'))
        self.assertNotEquals('file.txt', config.getpath('a', 'path_b'))
        self.assertEquals(config.getpath('a', 'path_b'),
                          config.getpath('a', 'path_c'))

    def test_set_and_save(self):
        config = self._read()
        config.set('b', 'option0', 'y')
        config.set('a', 'option0', 'x')
        config.set('a', 'option2', "Voilà l'été")  # UTF-8
        config.set('a', 'option1', u"Voilà l'été") # unicode
        # Note: the following would depend on the locale.getpreferredencoding()
        # config.set('a', 'option3', "Voil\xe0 l'\xe9t\xe9") # latin-1
        self.assertEquals('x', config.get('a', 'option0'))
        self.assertEquals(u"Voilà l'été", config.get('a', 'option1'))
        self.assertEquals(u"Voilà l'été", config.get('a', 'option2'))
        config.save()

        configfile = open(self.filename, 'r')
        self.assertEquals(['# -*- coding: utf-8 -*-\n',
                           '\n',
                           '[a]\n',
                           'option0 = x\n',
                           "option1 = Voilà l'été\n",
                           "option2 = Voilà l'été\n",
                           # "option3 = VoilÃ  l'Ã©tÃ©\n",
                           '\n',
                           '[b]\n',
                           'option0 = y\n',
                           '\n'],
                          configfile.readlines())
        configfile.close()
        config2 = Configuration(self.filename)
        self.assertEquals('x', config2.get('a', 'option0'))
        self.assertEquals(u"Voilà l'été", config2.get('a', 'option1'))
        self.assertEquals(u"Voilà l'été", config2.get('a', 'option2'))
        # self.assertEquals(u"Voilà l'été", config2.get('a', 'option3'))

    def test_set_and_save_inherit(self):
        def testcb():
            config = self._read()
            config.set('a', 'option2', "Voilà l'été")  # UTF-8
            config.set('a', 'option1', u"Voilà l'été") # unicode
            self.assertEquals('x', config.get('a', 'option'))
            self.assertEquals(u"Voilà l'été", config.get('a', 'option1'))
            self.assertEquals(u"Voilà l'été", config.get('a', 'option2'))
            config.save()

            configfile = open(self.filename, 'r')
            self.assertEquals(['# -*- coding: utf-8 -*-\n',
                               '\n',
                               '[a]\n',
                               "option1 = Voilà l'été\n",
                               "option2 = Voilà l'été\n",
                               '\n',
                               '[inherit]\n',
                               "file = trac-site.ini\n",
                               '\n'],
                              configfile.readlines())
            configfile.close()
            config2 = Configuration(self.filename)
            self.assertEquals('x', config2.get('a', 'option'))
            self.assertEquals(u"Voilà l'été", config2.get('a', 'option1'))
            self.assertEquals(u"Voilà l'été", config2.get('a', 'option2'))
        self._test_with_inherit(testcb)

    def test_sections(self):
        self._write(['[a]', 'option = x', '[b]', 'option = y'])
        config = self._read()
        self.assertEquals(['a', 'b'], config.sections())

        class Foo(object):
            option_c = Option('c', 'option', 'value')

        self.assertEquals(['a', 'b', 'c'], config.sections())

    def test_options(self):
        self._write(['[a]', 'option = x', '[b]', 'option = y'])
        config = self._read()
        self.assertEquals(('option', 'x'), iter(config.options('a')).next())
        self.assertEquals(('option', 'y'), iter(config.options('b')).next())
        self.assertRaises(StopIteration, iter(config.options('c')).next)

        class Foo(object):
            option_a = Option('a', 'b', 'c')

        self.assertEquals([('option', 'x'), ('b', 'c')],
                                list(config.options('a')))

    def test_has_option(self):
        config = self._read()
        self.assertEquals(False, config.has_option('a', 'option'))
        self._write(['[a]', 'option = x'])
        config = self._read()
        self.assertEquals(True, config.has_option('a', 'option'))

        class Foo(object):
            option_a = Option('a', 'option2', 'x2')

        self.assertEquals(True, config.has_option('a', 'option2'))

    def test_reparse(self):
        self._write(['[a]', 'option = x'])
        config = self._read()
        self.assertEquals('x', config.get('a', 'option'))
        time.sleep(2) # needed because of low mtime granularity,
                      # especially on fat filesystems

        self._write(['[a]', 'option = y'])
        config.parse_if_needed()
        self.assertEquals('y', config.get('a', 'option'))

    def test_inherit_one_level(self):
        def testcb():
            config = self._read()
            self.assertEqual('x', config.get('a', 'option'))
            self.assertEqual(['a', 'inherit'], config.sections())
            config.remove('a', 'option') # Should *not* remove option in parent
            self.assertEqual('x', config.get('a', 'option'))
            self.assertEqual([('option', 'x')], list(config.options('a')))
            self.assertEqual(True, 'a' in config)
        self._test_with_inherit(testcb)

    def _test_with_inherit(self, testcb):
        sitename = os.path.join(tempfile.gettempdir(), 'trac-site.ini')
        sitefile = open(sitename, 'w')
        try:
            try:
                sitefile.write('[a]\noption = x\n')
            finally:
                sitefile.close()

            self._write(['[inherit]', 'file = trac-site.ini'])
            testcb()
        finally:
            os.remove(sitename)

def suite():
    return unittest.makeSuite(ConfigurationTestCase, 'test')

if __name__ == '__main__':
    unittest.main(defaultTest='suite')
<commit_msg>0.12dev: Merged [8307] from 0.11-stable (Windows paths in new config tests).<commit_after># -*- coding: utf-8 -*-
#
# Copyright (C) 2005-2009 Edgewall Software
# Copyright (C) 2005-2007 Christopher Lenz <cmlenz@gmx.de>
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://trac.edgewall.org/wiki/TracLicense.
#
# This software consists of voluntary contributions made by many
# individuals. For the exact contribution history, see the revision
# history and logs, available at http://trac.edgewall.org/log/.

import os
from StringIO import StringIO
import tempfile
import time
import unittest

from trac.config import *
from trac.test import Configuration

class ConfigurationTestCase(unittest.TestCase):

    def setUp(self):
        self.filename = os.path.join(tempfile.gettempdir(), 'trac-test.ini')
        self._write([])
        self._orig_registry = Option.registry
        Option.registry = {}

    def tearDown(self):
        Option.registry = self._orig_registry
        os.remove(self.filename)

    def _read(self):
        return Configuration(self.filename)

    def _write(self, lines):
        fileobj = open(self.filename, 'w')
        try:
            fileobj.write('\n'.join(lines + ['']))
        finally:
            fileobj.close()

    def test_default(self):
        config = self._read()
        self.assertEquals('', config.get('a', 'option'))
        self.assertEquals('value', config.get('a', 'option', 'value'))

        class Foo(object):
            option_a = Option('a', 'option', 'value')

        self.assertEquals('value', config.get('a', 'option'))

    def test_default_bool(self):
        config = self._read()
        self.assertEquals(False, config.getbool('a', 'option'))
        self.assertEquals(True, config.getbool('a', 'option', 'yes'))
        self.assertEquals(True, config.getbool('a', 'option', 1))

        class Foo(object):
            option_a = Option('a', 'option', 'true')

        self.assertEquals(True, config.getbool('a', 'option'))

    def test_default_int(self):
        config = self._read()
        self.assertRaises(ConfigurationError, config.getint, 'a', 'option', 'b')
        self.assertEquals(0, config.getint('a', 'option'))
        self.assertEquals(1, config.getint('a', 'option', '1'))
        self.assertEquals(1, config.getint('a', 'option', 1))

        class Foo(object):
            option_a = Option('a', 'option', '2')

        self.assertEquals(2, config.getint('a', 'option'))

    def test_default_path(self):
        config = self._read()
        class Foo(object):
            option_a = PathOption('a', 'opt1', 'file.ini')
            option_b = PathOption('a', 'opt2', '/somewhere/file.ini')
        self.assertEquals('file.ini', config.get('a', 'opt1'))
        self.assertNotEquals('file.ini', config.getpath('a', 'opt1'))
        self.assertTrue(os.path.isabs(config.getpath('a', 'opt1')))
        self.assertEquals('/somewhere/file.ini', os.path.splitdrive(
                config.getpath('a', 'opt2'))[1].replace('\\', '/'))
        self.assertEquals('/none.ini', os.path.splitdrive(
                config.getpath('a', 'opt3', '/none.ini'))[1].replace('\\', '/'))
        self.assertNotEquals('none.ini', config.getpath('a', 'opt3', 'none.ini'))

    def test_read_and_get(self):
        self._write(['[a]', 'option = x'])
        config = self._read()
        self.assertEquals('x', config.get('a', 'option'))
        self.assertEquals('x', config.get('a', 'option', 'y'))
        self.assertEquals('y', config.get('b', 'option2', 'y'))

    def test_read_and_getbool(self):
        self._write(['[a]', 'option = yes'])
        config = self._read()
        self.assertEquals(True, config.getbool('a', 'option'))
        self.assertEquals(True, config.getbool('a', 'option', False))
        self.assertEquals(False, config.getbool('b', 'option2'))
        self.assertEquals(False, config.getbool('b', 'option2', False))
        self.assertEquals(False, config.getbool('b', 'option2', 'disabled'))

    def test_read_and_getint(self):
        self._write(['[a]', 'option = 42'])
        config = self._read()
        self.assertEquals(42, config.getint('a', 'option'))
        self.assertEquals(42, config.getint('a', 'option', 25))
        self.assertEquals(0, config.getint('b', 'option2'))
        self.assertEquals(25, config.getint('b', 'option2', 25))
        self.assertEquals(25, config.getint('b', 'option2', '25'))

    def test_read_and_getlist(self):
        self._write(['[a]', 'option = foo, bar, baz'])
        config = self._read()
        self.assertEquals(['foo', 'bar', 'baz'],
                          config.getlist('a', 'option'))
        self.assertEquals([],
                          config.getlist('b', 'option2'))
        self.assertEquals(['foo', 'bar', 'baz'],
                    config.getlist('b', 'option2', ['foo', 'bar', 'baz']))
        self.assertEquals(['foo', 'bar', 'baz'],
                    config.getlist('b', 'option2', 'foo, bar, baz'))

    def test_read_and_getlist_sep(self):
        self._write(['[a]', 'option = foo | bar | baz'])
        config = self._read()
        self.assertEquals(['foo', 'bar', 'baz'],
                          config.getlist('a', 'option', sep='|'))

    def test_read_and_getlist_keep_empty(self):
        self._write(['[a]', 'option = ,bar,baz'])
        config = self._read()
        self.assertEquals(['bar', 'baz'], config.getlist('a', 'option'))
        self.assertEquals(['', 'bar', 'baz'],
                          config.getlist('a', 'option', keep_empty=True))

    def test_getpath(self):
        config = self._read()
        config.set('a', 'path_a', '/somewhere/file.txt')
        config.set('a', 'path_b', 'file.txt')
        config.set('a', 'path_c', './file.txt')
        self.assertEquals('/somewhere/file.txt', os.path.splitdrive(
                config.getpath('a', 'path_a'))[1].replace('\\', '/'))
        self.assertNotEquals('file.txt', config.getpath('a', 'path_b'))
        self.assertEquals(config.getpath('a', 'path_b'),
                          config.getpath('a', 'path_c'))

    def test_set_and_save(self):
        config = self._read()
        config.set('b', 'option0', 'y')
        config.set('a', 'option0', 'x')
        config.set('a', 'option2', "Voilà l'été")  # UTF-8
        config.set('a', 'option1', u"Voilà l'été") # unicode
        # Note: the following would depend on the locale.getpreferredencoding()
        # config.set('a', 'option3', "Voil\xe0 l'\xe9t\xe9") # latin-1
        self.assertEquals('x', config.get('a', 'option0'))
        self.assertEquals(u"Voilà l'été", config.get('a', 'option1'))
        self.assertEquals(u"Voilà l'été", config.get('a', 'option2'))
        config.save()

        configfile = open(self.filename, 'r')
        self.assertEquals(['# -*- coding: utf-8 -*-\n',
                           '\n',
                           '[a]\n',
                           'option0 = x\n',
                           "option1 = Voilà l'été\n",
                           "option2 = Voilà l'été\n",
                           # "option3 = VoilÃ  l'Ã©tÃ©\n",
                           '\n',
                           '[b]\n',
                           'option0 = y\n',
                           '\n'],
                          configfile.readlines())
        configfile.close()
        config2 = Configuration(self.filename)
        self.assertEquals('x', config2.get('a', 'option0'))
        self.assertEquals(u"Voilà l'été", config2.get('a', 'option1'))
        self.assertEquals(u"Voilà l'été", config2.get('a', 'option2'))
        # self.assertEquals(u"Voilà l'été", config2.get('a', 'option3'))

    def test_set_and_save_inherit(self):
        def testcb():
            config = self._read()
            config.set('a', 'option2', "Voilà l'été")  # UTF-8
            config.set('a', 'option1', u"Voilà l'été") # unicode
            self.assertEquals('x', config.get('a', 'option'))
            self.assertEquals(u"Voilà l'été", config.get('a', 'option1'))
            self.assertEquals(u"Voilà l'été", config.get('a', 'option2'))
            config.save()

            configfile = open(self.filename, 'r')
            self.assertEquals(['# -*- coding: utf-8 -*-\n',
                               '\n',
                               '[a]\n',
                               "option1 = Voilà l'été\n",
                               "option2 = Voilà l'été\n",
                               '\n',
                               '[inherit]\n',
                               "file = trac-site.ini\n",
                               '\n'],
                              configfile.readlines())
            configfile.close()
            config2 = Configuration(self.filename)
            self.assertEquals('x', config2.get('a', 'option'))
            self.assertEquals(u"Voilà l'été", config2.get('a', 'option1'))
            self.assertEquals(u"Voilà l'été", config2.get('a', 'option2'))
        self._test_with_inherit(testcb)

    def test_sections(self):
        self._write(['[a]', 'option = x', '[b]', 'option = y'])
        config = self._read()
        self.assertEquals(['a', 'b'], config.sections())

        class Foo(object):
            option_c = Option('c', 'option', 'value')

        self.assertEquals(['a', 'b', 'c'], config.sections())

    def test_options(self):
        self._write(['[a]', 'option = x', '[b]', 'option = y'])
        config = self._read()
        self.assertEquals(('option', 'x'), iter(config.options('a')).next())
        self.assertEquals(('option', 'y'), iter(config.options('b')).next())
        self.assertRaises(StopIteration, iter(config.options('c')).next)

        class Foo(object):
            option_a = Option('a', 'b', 'c')

        self.assertEquals([('option', 'x'), ('b', 'c')],
                                list(config.options('a')))

    def test_has_option(self):
        config = self._read()
        self.assertEquals(False, config.has_option('a', 'option'))
        self._write(['[a]', 'option = x'])
        config = self._read()
        self.assertEquals(True, config.has_option('a', 'option'))

        class Foo(object):
            option_a = Option('a', 'option2', 'x2')

        self.assertEquals(True, config.has_option('a', 'option2'))

    def test_reparse(self):
        self._write(['[a]', 'option = x'])
        config = self._read()
        self.assertEquals('x', config.get('a', 'option'))
        time.sleep(2) # needed because of low mtime granularity,
                      # especially on fat filesystems

        self._write(['[a]', 'option = y'])
        config.parse_if_needed()
        self.assertEquals('y', config.get('a', 'option'))

    def test_inherit_one_level(self):
        def testcb():
            config = self._read()
            self.assertEqual('x', config.get('a', 'option'))
            self.assertEqual(['a', 'inherit'], config.sections())
            config.remove('a', 'option') # Should *not* remove option in parent
            self.assertEqual('x', config.get('a', 'option'))
            self.assertEqual([('option', 'x')], list(config.options('a')))
            self.assertEqual(True, 'a' in config)
        self._test_with_inherit(testcb)

    def _test_with_inherit(self, testcb):
        sitename = os.path.join(tempfile.gettempdir(), 'trac-site.ini')
        sitefile = open(sitename, 'w')
        try:
            try:
                sitefile.write('[a]\noption = x\n')
            finally:
                sitefile.close()

            self._write(['[inherit]', 'file = trac-site.ini'])
            testcb()
        finally:
            os.remove(sitename)

def suite():
    return unittest.makeSuite(ConfigurationTestCase, 'test')

if __name__ == '__main__':
    unittest.main(defaultTest='suite')
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
#
# Copyright (c) 2012 TSH Labs <projects@tshlabs.org>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
#   notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
#   notice, this list of conditions and the following disclaimer in the
#   documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#

""" HTTP frontend for handling requests."""

import logging
import multiprocessing

import cherrypy
from cherrypy.wsgiserver import CherryPyWSGIServer

import avalon.models
import avalon.services
import avalon.views

__all__ = [
    'AvalonServerConfig',
    'AvalonServer',
    'AvalonHandler',
    'RequestFilter'
    ]

class JSONOutHandler(object):

    """
    """

    def __init__(self):
        """
        """
        self._encoder = avalon.views.JSONEncoder()

    def __call__(self, *args, **kwargs):
        """
        """
        value = cherrypy.serving.request._json_inner_handler(*args, **kwargs)
        return self._encoder.encode(value)

class AvalonServerConfig(object):

    """ Configuration for our HTTP server.
    """

    def __init__(self):
        self.log = None
        self.bind_addr = None
        self.gateway = None
        self.num_threads = None
        self.request_queue_size = None

class AvalonServer(CherryPyWSGIServer):

    """ Wrap the standard CherryPy server to use our own
        error logging mechanism.
    """

    def __init__(self, config):
        """ Call the parent constructor and set our error logger.
        """
        super(AvalonServer, self).__init__(
            config.bind_addr,
            config.gateway,
            numthreads=config.num_threads,
            request_queue_size=config.request_queue_size)

        self._log = config.log

    def error_log(self, msg='', level=logging.INFO, trackback=False):
        """ Write an error to the log, optionally with a traceback.
        """
        if traceback:
            msg = '%s: %s' % (msg, traceback.format_exc())
        self._log.log(level, msg)

class AvalonHandler(object):

    """ Handle HTTP requests and return result sets in JSON.
    """

    def __init__(self, session_handler):
        """ Set the session handler and optionally, cache to use.
        """
        self._tracks = avalon.services.TrackStore(session_handler)
        self._albums = avalon.services.AlbumStore(session_handler)
        self._artists = avalon.services.ArtistStore(session_handler)
        self._genres = avalon.services.GenreStore(session_handler)
        self._id_cache = avalon.services.IdLookupCache(session_handler)

    def _get_output(self, res=None, err=None):
        """ Render results or an error as an iterable.
        """
        out = RequestOutput()
        if res is not None:
            out.results = res
        if err is not None:
            out.error = err
        return out.render()

    def _reduce(self, *args):
        """ Find the intersection of all of the given non-None sets.
        """
        set_intersect = lambda x, y: x.intersection(y)
        set_filter = lambda x: x is not None

        return reduce(set_intersect, filter(set_filter, args))

    @cherrypy.expose
    @cherrypy.tools.json_out(handler=JSONOutHandler())
    def songs(self, *args, **kwargs):
        """ Return song results based on the given query string
            parameters.
        """
        filters = RequestParams.build(self._id_cache, kwargs)

        # If there are no query string params to filter to input
        # but short circuit and just return all tracks
        if filters.is_empty():
            return self._get_output(self._tracks.all())

        set1 = None
        set2 = None
        set3 = None

        if None is not filters.album_id:
            set1 = self._tracks.by_album(filters.album_id)
        if None is not filters.artist_id:
            set2 = self._tracks.by_artist(filters.artist_id)
        if None is not filters.genre_id:
            set3 = self._tracks.by_genre(filters.genre_id)

        # Return the intersection of any none-None sets
        return self._get_output(res=self._reduce(set1, set2, set3))

    @cherrypy.expose
    @cherrypy.tools.json_out(handler=JSONOutHandler())
    def albums(self, *args, **kwargs):
        """ Return a list of all albums.
        """
        return self._get_output(res=self._albums.all())

    @cherrypy.expose
    @cherrypy.tools.json_out(handler=JSONOutHandler())
    def artists(self, *args, **kwargs):
        """ Return a list of all artists.
        """
        return self._get_output(res=self._artists.all())

    @cherrypy.expose
    @cherrypy.tools.json_out(handler=JSONOutHandler())
    def genres(self, *args, **kwargs):
        """ Return a list of all genres.
        """
        return self._get_output(res=self._genres.all())

class RequestOutput(object):

    """ Render query results or errors in a format that can
        be serialized to JSON.
    """

    def __init__(self):
        """ Initialize errors and results from this query.
        """
        self.error = None
        self.results = []

    def _format_error(self, err):
        """ Format a query error (if there was one).
        """
        out = {
            'error': False,
            'error_code': 0,
            'error_msg': ''
            }
        if err is not None:
            out['error'] = True
            out['error_code'] = err.code
            out['error_msg'] = err.message
        return out

    def _format_results(self, res):
        """ Format query results (if any).
        """
        out = {
            'result_count': 0,
            'results': []
            }

        # The standard JSON encoder doesn't know how
        # to render set objects, which is what the service
        # layer returns, so we convert them to lists.
        if res is not None:
            out['result_count'] = len(res)
            out['results'] = list(res)
        return out

    def render(self):
        """ Format any results or errors as a dictionary to be
            turned into a JSON payload.
        """
        err = self._format_error(self.error)
        res = self._format_results(self.results)

        return {
            'error': err['error'],
            'error_code': err['error_code'],
            'error_msg': err['error_msg'],
            'result_count': res['result_count'],
            'results': res['results']
            }

class RequestParams(object):

    """ Parse and encapsulate object IDs and names from
        query string parameters.
    """

    def __init__(self):
        """ Initialize values for object IDs to None.
        """
        self.album_id = None
        self.artist_id = None
        self.genre_id = None

    def is_empty(self):
        """
        """
        return self.album_id is None and self.artist_id is None and self.genre_id is None

    @classmethod
    def build(cls, cache, kwargs):
        """ Construct a new filter based on the given query
            string parameters and name to ID cache.

            Recognized params: album, album_id, artist, artist_id,
            genre, genre_id
        """
        f = cls()

        for field in ('album', 'artist', 'genre'):
            if field not in kwargs:
                continue
            # Look up a value from the cache and use it to filter
            # the results. We don't care if the cache returned a
            # valid ID since we want the request to return 0
            # results for bad QS params.
            val_id = cache.get_id(field, kwargs[field])
            setattr(f, field + '_id', val_id)

        for field in ('album_id', 'artist_id', 'genre_id'):
            if field not in kwargs:
                continue
            try:
                val_id = int(kwargs[field])
            except ValueError:
                # Use an invalid ID anyway since we want the
                # request to return 0 results for bad QS params.
                val_id = 0
            setattr(f, field, val_id)
        return f

<commit_msg>Wow. That made 0 sense<commit_after># -*- coding: utf-8 -*-
#
# Copyright (c) 2012 TSH Labs <projects@tshlabs.org>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
#   notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
#   notice, this list of conditions and the following disclaimer in the
#   documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#

""" HTTP frontend for handling requests."""

import logging
import multiprocessing

import cherrypy
from cherrypy.wsgiserver import CherryPyWSGIServer

import avalon.models
import avalon.services
import avalon.views

__all__ = [
    'AvalonServerConfig',
    'AvalonServer',
    'AvalonHandler',
    'RequestFilter'
    ]

class JSONOutHandler(object):

    """
    """

    def __init__(self):
        """
        """
        self._encoder = avalon.views.JSONEncoder()

    def __call__(self, *args, **kwargs):
        """
        """
        value = cherrypy.serving.request._json_inner_handler(*args, **kwargs)
        return self._encoder.encode(value)

class AvalonServerConfig(object):

    """ Configuration for our HTTP server.
    """

    def __init__(self):
        self.log = None
        self.bind_addr = None
        self.gateway = None
        self.num_threads = None
        self.request_queue_size = None

class AvalonServer(CherryPyWSGIServer):

    """ Wrap the standard CherryPy server to use our own
        error logging mechanism.
    """

    def __init__(self, config):
        """ Call the parent constructor and set our error logger.
        """
        super(AvalonServer, self).__init__(
            config.bind_addr,
            config.gateway,
            numthreads=config.num_threads,
            request_queue_size=config.request_queue_size)

        self._log = config.log

    def error_log(self, msg='', level=logging.INFO, trackback=False):
        """ Write an error to the log, optionally with a traceback.
        """
        if traceback:
            msg = '%s: %s' % (msg, traceback.format_exc())
        self._log.log(level, msg)

class AvalonHandler(object):

    """ Handle HTTP requests and return result sets in JSON.
    """

    def __init__(self, session_handler):
        """ Set the session handler and optionally, cache to use.
        """
        self._tracks = avalon.services.TrackStore(session_handler)
        self._albums = avalon.services.AlbumStore(session_handler)
        self._artists = avalon.services.ArtistStore(session_handler)
        self._genres = avalon.services.GenreStore(session_handler)
        self._id_cache = avalon.services.IdLookupCache(session_handler)

    def _get_output(self, res=None, err=None):
        """ Render results or an error as an iterable.
        """
        out = RequestOutput()
        if res is not None:
            out.results = res
        if err is not None:
            out.error = err
        return out.render()

    def _reduce(self, *args):
        """ Find the intersection of all of the given non-None sets.
        """
        set_intersect = lambda x, y: x.intersection(y)
        set_filter = lambda x: x is not None

        return reduce(set_intersect, filter(set_filter, args))

    @cherrypy.expose
    @cherrypy.tools.json_out(handler=JSONOutHandler())
    def songs(self, *args, **kwargs):
        """ Return song results based on the given query string
            parameters.
        """
        filters = RequestParams.build(self._id_cache, kwargs)

        # If there are no query string params to filter then short
        # circuit and just return all tracks
        if filters.is_empty():
            return self._get_output(self._tracks.all())

        set1 = None
        set2 = None
        set3 = None

        if None is not filters.album_id:
            set1 = self._tracks.by_album(filters.album_id)
        if None is not filters.artist_id:
            set2 = self._tracks.by_artist(filters.artist_id)
        if None is not filters.genre_id:
            set3 = self._tracks.by_genre(filters.genre_id)

        # Return the intersection of any none-None sets
        return self._get_output(res=self._reduce(set1, set2, set3))

    @cherrypy.expose
    @cherrypy.tools.json_out(handler=JSONOutHandler())
    def albums(self, *args, **kwargs):
        """ Return a list of all albums.
        """
        return self._get_output(res=self._albums.all())

    @cherrypy.expose
    @cherrypy.tools.json_out(handler=JSONOutHandler())
    def artists(self, *args, **kwargs):
        """ Return a list of all artists.
        """
        return self._get_output(res=self._artists.all())

    @cherrypy.expose
    @cherrypy.tools.json_out(handler=JSONOutHandler())
    def genres(self, *args, **kwargs):
        """ Return a list of all genres.
        """
        return self._get_output(res=self._genres.all())

class RequestOutput(object):

    """ Render query results or errors in a format that can
        be serialized to JSON.
    """

    def __init__(self):
        """ Initialize errors and results from this query.
        """
        self.error = None
        self.results = []

    def _format_error(self, err):
        """ Format a query error (if there was one).
        """
        out = {
            'error': False,
            'error_code': 0,
            'error_msg': ''
            }
        if err is not None:
            out['error'] = True
            out['error_code'] = err.code
            out['error_msg'] = err.message
        return out

    def _format_results(self, res):
        """ Format query results (if any).
        """
        out = {
            'result_count': 0,
            'results': []
            }

        # The standard JSON encoder doesn't know how
        # to render set objects, which is what the service
        # layer returns, so we convert them to lists.
        if res is not None:
            out['result_count'] = len(res)
            out['results'] = list(res)
        return out

    def render(self):
        """ Format any results or errors as a dictionary to be
            turned into a JSON payload.
        """
        err = self._format_error(self.error)
        res = self._format_results(self.results)

        return {
            'error': err['error'],
            'error_code': err['error_code'],
            'error_msg': err['error_msg'],
            'result_count': res['result_count'],
            'results': res['results']
            }

class RequestParams(object):

    """ Parse and encapsulate object IDs and names from
        query string parameters.
    """

    def __init__(self):
        """ Initialize values for object IDs to None.
        """
        self.album_id = None
        self.artist_id = None
        self.genre_id = None

    def is_empty(self):
        """
        """
        return self.album_id is None and self.artist_id is None and self.genre_id is None

    @classmethod
    def build(cls, cache, kwargs):
        """ Construct a new filter based on the given query
            string parameters and name to ID cache.

            Recognized params: album, album_id, artist, artist_id,
            genre, genre_id
        """
        f = cls()

        for field in ('album', 'artist', 'genre'):
            if field not in kwargs:
                continue
            # Look up a value from the cache and use it to filter
            # the results. We don't care if the cache returned a
            # valid ID since we want the request to return 0
            # results for bad QS params.
            val_id = cache.get_id(field, kwargs[field])
            setattr(f, field + '_id', val_id)

        for field in ('album_id', 'artist_id', 'genre_id'):
            if field not in kwargs:
                continue
            try:
                val_id = int(kwargs[field])
            except ValueError:
                # Use an invalid ID anyway since we want the
                # request to return 0 results for bad QS params.
                val_id = 0
            setattr(f, field, val_id)
        return f

<|endoftext|>


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

import sys
from functools import wraps
from hashlib import md5
from pprint import pprint
from flask import Flask, request, flash, Response, session, g, redirect, url_for, abort, render_template
import MySQLdb
from AAR_config import AUTH_USERS, SECRET_KEY, CONNECTION_ARGS

silly_text = '''I'm terribly sorry. I've looked everywhere but I can't find that combination of credentials in my records. Perhaps you mistyped your password? Or maybe you simply don't have an account with us yet. I am sorry to be so thick. I'm a bad server, I know, but what can you do: these are the wages of unskilled labor.'''

app = Flask(__name__)
app.config['DEBUG'] = True
app.config['SECRET_KEY'] = SECRET_KEY

@app.route('/')
def index():
    return render_template('index.html')

def logged_in(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if session.get('logged_in') is not None:
            return f(*args, **kwargs)
        else:
            flash('Please log in first...', 'error')
            next_url = request.url
            login_url = '%s?next=%s' % (url_for('login'), next_url)
            return redirect(login_url)
    return decorated_function

@app.route('/logout')
def logout():
    if session.get('username') or session.get('logged_in') or session.pop('role'):
        session.pop('username')
        session.pop('role')
        session.pop('logged_in')
    return redirect(url_for('login'))

@app.route('/login', methods=['GET', 'POST'])
def login():
    error = None
    next = request.args.get('next')

    if request.method == 'POST':
        uname = request.form['username']
        upswd = request.form['password']
        authstr = uname + upswd
        authhash = md5(authstr).hexdigest()
        if authhash not in AUTH_USERS:
            error = silly_text
        else:
            session['logged_in'] = True
            session['username'] = uname
            session['role'] = AUTH_USERS[authhash]['role']

            if session['role'] == 'admin':
                return redirect(url_for('dispacher'))
            elif session['role'] == 'customer':
                return redirect(url_for('tempTest'))

    return render_template('login.html', error=error, session=session)

@app.route('/dispacher')
@logged_in
def dispacher():
    if session.get('role') == 'customer':
        return logout()
    else:
        db = MySQLdb.connect(**CONNECTION_ARGS)
        cur = db.cursor()
        cur.execute("select * from pet where sex = 'f'")
        name, owner, type, sex, bdate, ddate = cur.fetchone()
        legend = """
                mysql> select * from pet;
                +------+---------+---------+------+------------+------------+
                | name | owner   | species | sex  | birth      | death      |
                +------+---------+---------+------+------------+------------+
                | fido | jon     | dog     | m    | 0000-00-00 | 0000-00-00 |
                | odif | deborah | dog     | f    | 2000-01-01 | 2010-01-01 |
                +------+---------+---------+------+------------+------------+
           """
        response = "%s\n%s had a %s whose name was %s. She was born on %s" % (legend, owner.title(), type, name.title(), bdate)

        return render_template("dispacher.html",
            title = "Dispacher Interface",
            user = session['username'],
            reqenviron = request.environ,
            ses = session,
            legend = legend,
            response = response,
            owner = owner.title(),
            type = type,
            name = name.title(),
            bdate = bdate)

@app.route('/testTemplate')
@logged_in
def tempTest():
    session['objects'] = 42
    session.permanent = False
    user = { 'nickname': "Handsome" } # fake user
    return render_template("testTemplate.html",
        title = "Testing",
        user = user,
        reqenviron = request.environ,
        ses = session)

##### Shut down the simple server from the browser address bar #####
def shutdown_server():
    func = request.environ.get('werkzeug.server.shutdown')
    if func is None:
        raise RuntimeError('Not running with the Werkzeug Server')
    func()

@app.route('/shutdown', methods=['GET'])
def shutdown():
    shutdown_server()
    return 'Server shutting down...'

if __name__ == "__main__":
    app.run(port=9229)

### RANDOM JUNK TO GET RID OF ###

#                 if next:
#                     flash('redirected ' + uname + ' to next')
#                     return redirect(next)
#                 else: return redirect(url_for('tempTest'))

<commit_msg>tinkering w/login behavior<commit_after>#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
from functools import wraps
from hashlib import md5
from pprint import pprint
from flask import Flask, request, flash, Response, session, g, redirect, url_for, abort, render_template
import MySQLdb
from AAR_config import AUTH_USERS, SECRET_KEY, CONNECTION_ARGS

silly_text = '''I'm terribly sorry. I've looked everywhere but I can't find that combination of credentials in my records. Perhaps you mistyped your password? Or maybe you simply don't have an account with us yet. I am sorry to be so thick. I'm a bad server, I know, but what can you do: these are the wages of unskilled labor.'''

app = Flask(__name__)
app.config['DEBUG'] = True
app.config['SECRET_KEY'] = SECRET_KEY

@app.route('/')
def index():
    return render_template('index.html')

def logged_in(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if session.get('logged_in') is not None:
            return f(*args, **kwargs)
        else:
            flash('Please log in first...', 'error')
            next_url = request.url
            login_url = '%s?next=%s' % (url_for('login'), next_url)
            return redirect(login_url)
    return decorated_function

<<<<<<>>>>>> 772583266c240c1a7807c1c63495890180eb26b0
@app.route('/login', methods=['GET', 'POST'])
def login():
    error = None
    next = request.args.get('next')

    if request.method == 'POST':
        uname = request.form['username']
        upswd = request.form['password']
        authstr = uname + upswd
        authhash = md5(authstr).hexdigest()
        if authhash not in AUTH_USERS:
            error = silly_text
        else:
<<<<<<< HEAD
            session['logged_in'] = True
            session['username'] = uname
            session['role'] = AUTH_USERS[authhash]['role']

            if session['role'] == 'admin':
                return redirect(url_for('dispacher'))
            elif session['role'] == 'customer':
                return redirect(url_for('tempTest'))
=======
            session['username'] = uname
            session['logged_in'] = True
            role = AUTH_USERS[authhash]['role']

            if role == 'admin':
                return redirect(url_for('dispacher'))
            else:
                if next:
                    flash('redirected ' + uname + ' to next')
                    return redirect(next)
                else: return redirect(url_for('tempTest'))
>>>>>>> 772583266c240c1a7807c1c63495890180eb26b0

    return render_template('login.html', error=error, session=session)

@app.route('/dispacher')
@logged_in
def dispacher():
<<<<<< select * from pet;
                +------+---------+---------+------+------------+------------+
                | name | owner   | species | sex  | birth      | death      |
                +------+---------+---------+------+------------+------------+
                | fido | jon     | dog     | m    | 0000-00-00 | 0000-00-00 |
                | odif | deborah | dog     | f    | 2000-01-01 | 2010-01-01 |
                +------+---------+---------+------+------------+------------+
           """
        response = "%s\n%s had a %s whose name was %s. She was born on %s" % (legend, owner.title(), type, name.title(), bdate)

        return render_template("dispacher.html",
            title = "Dispacher Interface",
            user = session['username'],
            reqenviron = request.environ,
            ses = session,
            legend = legend,
            response = response,
            owner = owner.title(),
            type = type,
            name = name.title(),
            bdate = bdate)

=======
    db = MySQLdb.connect(**CONNECTION_ARGS)
    cur = db.cursor()
    cur.execute("select * from pet where sex = 'f'")
    name, owner, type, sex, bdate, ddate = cur.fetchone()
    legend = """
            mysql> select * from pet;
            +------+---------+---------+------+------------+------------+
            | name | owner   | species | sex  | birth      | death      |
            +------+---------+---------+------+------------+------------+
            | fido | jon     | dog     | m    | 0000-00-00 | 0000-00-00 |
            | odif | deborah | dog     | f    | 2000-01-01 | 2010-01-01 |
            +------+---------+---------+------+------------+------------+
       """
    response = "%s\n%s had a %s whose name was %s. She was born on %s" % (legend, owner.title(), type, name.title(), bdate)

    return render_template("dispacher.html",
        title = "Dispacher Interface",
        user = session['username'],
        reqenviron = request.environ,
        ses = session,
        legend = legend,
        response = response,
        owner = owner.title(),
        type = type,
        name = name.title(),
        bdate = bdate)

@app.route('/logout')
def logout():
    if session.get('username') or session.get('logged_in'):
        session.pop('username')
        session.pop('logged_in')
    return redirect(url_for('login'))

>>>>>>> 772583266c240c1a7807c1c63495890180eb26b0
@app.route('/testTemplate')
@logged_in
def tempTest():
    session['objects'] = 42
    session.permanent = False
    user = { 'nickname': "Handsome" } # fake user
    return render_template("testTemplate.html",
        title = "Testing",
        user = user,
        reqenviron = request.environ,
        ses = session)

##### Shut down the simple server from the browser address bar #####
def shutdown_server():
    func = request.environ.get('werkzeug.server.shutdown')
    if func is None:
        raise RuntimeError('Not running with the Werkzeug Server')
    func()

@app.route('/shutdown', methods=['GET'])
def shutdown():
    shutdown_server()
    return 'Server shutting down...'

if __name__ == "__main__":
    app.run(port=9229)
<<<<<<>>>>>> 772583266c240c1a7807c1c63495890180eb26b0
<|endoftext|>


<commit_before>"""Support for Epson Workforce Printer."""
from datetime import timedelta
import logging

import voluptuous as vol

from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import CONF_HOST, CONF_MONITORED_CONDITIONS
from homeassistant.exceptions import PlatformNotReady
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity

_LOGGER = logging.getLogger(__name__)
MONITORED_CONDITIONS = {
    "black": ["Ink level Black", "%", "mdi:water"],
    "photoblack": ["Ink level Photoblack", "%", "mdi:water"],
    "magenta": ["Ink level Magenta", "%", "mdi:water"],
    "cyan": ["Ink level Cyan", "%", "mdi:water"],
    "yellow": ["Ink level Yellow", "%", "mdi:water"],
    "clean": ["Cleaning level", "%", "mdi:water"],
}
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
    {
        vol.Required(CONF_HOST): cv.string,
        vol.Required(CONF_MONITORED_CONDITIONS): vol.All(
            cv.ensure_list, [vol.In(MONITORED_CONDITIONS)]
        ),
    }
)
SCAN_INTERVAL = timedelta(minutes=60)

def setup_platform(hass, config, add_devices, discovery_info=None):
    """Set up the cartridge sensor."""
    host = config.get(CONF_HOST)

    from epsonprinter_pkg.epsonprinterapi import EpsonPrinterAPI

    api = EpsonPrinterAPI(host)
    if not api.available:
        raise PlatformNotReady()

    sensors = [
        EpsonPrinterCartridge(api, condition)
        for condition in config[CONF_MONITORED_CONDITIONS]
    ]

    add_devices(sensors, True)

class EpsonPrinterCartridge(Entity):
    """Representation of a cartridge sensor."""

    def __init__(self, api, cartridgeidx):
        """Initialize a cartridge sensor."""
        self._api = api

        self._id = cartridgeidx
        self._name = MONITORED_CONDITIONS[self._id][0]
        self._unit = MONITORED_CONDITIONS[self._id][1]
        self._icon = MONITORED_CONDITIONS[self._id][2]

    @property
    def name(self):
        """Return the name of the sensor."""
        return self._name

    @property
    def icon(self):
        """Icon to use in the frontend, if any."""
        return self._icon

    @property
    def unit_of_measurement(self):
        """Return the unit the value is expressed in."""
        return self._unit

    @property
    def state(self):
        """Return the state of the device."""
        return self._api.getSensorValue(self._id)

    @property
    def available(self):
        """Could the device be accessed during the last update call."""
        return self._api.available

    def update(self):
        """Get the latest data from the Epson printer."""
        self._api.update()
<commit_msg>Move epsonworkforce imports at top-level (#29086)<commit_after>"""Support for Epson Workforce Printer."""
from datetime import timedelta
import logging

from epsonprinter_pkg.epsonprinterapi import EpsonPrinterAPI
import voluptuous as vol

from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import CONF_HOST, CONF_MONITORED_CONDITIONS
from homeassistant.exceptions import PlatformNotReady
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity

_LOGGER = logging.getLogger(__name__)
MONITORED_CONDITIONS = {
    "black": ["Ink level Black", "%", "mdi:water"],
    "photoblack": ["Ink level Photoblack", "%", "mdi:water"],
    "magenta": ["Ink level Magenta", "%", "mdi:water"],
    "cyan": ["Ink level Cyan", "%", "mdi:water"],
    "yellow": ["Ink level Yellow", "%", "mdi:water"],
    "clean": ["Cleaning level", "%", "mdi:water"],
}
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
    {
        vol.Required(CONF_HOST): cv.string,
        vol.Required(CONF_MONITORED_CONDITIONS): vol.All(
            cv.ensure_list, [vol.In(MONITORED_CONDITIONS)]
        ),
    }
)
SCAN_INTERVAL = timedelta(minutes=60)

def setup_platform(hass, config, add_devices, discovery_info=None):
    """Set up the cartridge sensor."""
    host = config.get(CONF_HOST)

    api = EpsonPrinterAPI(host)
    if not api.available:
        raise PlatformNotReady()

    sensors = [
        EpsonPrinterCartridge(api, condition)
        for condition in config[CONF_MONITORED_CONDITIONS]
    ]

    add_devices(sensors, True)

class EpsonPrinterCartridge(Entity):
    """Representation of a cartridge sensor."""

    def __init__(self, api, cartridgeidx):
        """Initialize a cartridge sensor."""
        self._api = api

        self._id = cartridgeidx
        self._name = MONITORED_CONDITIONS[self._id][0]
        self._unit = MONITORED_CONDITIONS[self._id][1]
        self._icon = MONITORED_CONDITIONS[self._id][2]

    @property
    def name(self):
        """Return the name of the sensor."""
        return self._name

    @property
    def icon(self):
        """Icon to use in the frontend, if any."""
        return self._icon

    @property
    def unit_of_measurement(self):
        """Return the unit the value is expressed in."""
        return self._unit

    @property
    def state(self):
        """Return the state of the device."""
        return self._api.getSensorValue(self._id)

    @property
    def available(self):
        """Could the device be accessed during the last update call."""
        return self._api.available

    def update(self):
        """Get the latest data from the Epson printer."""
        self._api.update()
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
#
# Copyright (C) 2003-2006 Edgewall Software
# Copyright (C) 2003-2004 Jonas Borgström <jonas@edgewall.com>
# Copyright (C) 2006 Matthew Good <trac@matt-good.net>
# Copyright (C) 2005-2006 Christian Boos <cboos@neuf.fr>
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://trac.edgewall.org/wiki/TracLicense.
#
# This software consists of voluntary contributions made by many
# individuals. For the exact contribution history, see the revision
# history and logs, available at http://trac.edgewall.org/log/.
#
# Author: Jonas Borgström <jonas@edgewall.com>
#         Matthew Good <trac@matt-good.net>

import locale
import sys
import time

# Date/time utilities

def pretty_timedelta(time1, time2=None, resolution=None):
    """Calculate time delta (inaccurately, only for decorative purposes ;-) for
    prettyprinting. If time1 is None, the current time is used."""
    if not time1: time1 = time.time()
    if not time2: time2 = time.time()
    if time1 > time2:
        time2, time1 = time1, time2
    units = ((3600 * 24 * 365, 'year',   'years'),
             (3600 * 24 * 30,  'month',  'months'),
             (3600 * 24 * 7,   'week',   'weeks'),
             (3600 * 24,       'day',    'days'),
             (3600,            'hour',   'hours'),
             (60,              'minute', 'minutes'))
    age_s = int(time2 - time1)
    if resolution and age_s < resolution:
        return ''
    if age_s < 60:
        return '%i second%s' % (age_s, age_s != 1 and 's' or '')
    for u, unit, unit_plural in units:
        r = float(age_s) / float(u)
        if r >= 0.9:
            r = int(round(r))
            return '%d %s' % (r, r == 1 and unit or unit_plural)
    return ''

def format_datetime(t=None, format='%x %X', gmt=False):
    if t is None:
        t = time.time()
    if not isinstance(t, (list, tuple, time.struct_time)):
        if gmt:
            t = time.gmtime(int(t))
        else:
            t = time.localtime(int(t))

    text = time.strftime(format, t)
    encoding = locale.getpreferredencoding()
    if sys.platform != 'win32':
        encoding = locale.getlocale(locale.LC_TIME)[1] or encoding
        # the above is broken on win32, e.g. we'd get '437' instead of 'cp437'
    return unicode(text, encoding, 'replace')

def format_date(t=None, format='%x', gmt=False):
    return format_datetime(t, format, gmt)

def format_time(t=None, format='%X', gmt=False):
    return format_datetime(t, format, gmt)

def get_date_format_hint():
    t = time.localtime(0)
    t = (1999, 10, 29, t[3], t[4], t[5], t[6], t[7], t[8])
    tmpl = format_date(t)
    return tmpl.replace('1999', 'YYYY', 1).replace('99', 'YY', 1) \
               .replace('10', 'MM', 1).replace('29', 'DD', 1)

def get_datetime_format_hint():
    t = time.localtime(0)
    t = (1999, 10, 29, 23, 59, 58, t[6], t[7], t[8])
    tmpl = format_datetime(t)
    return tmpl.replace('1999', 'YYYY', 1).replace('99', 'YY', 1) \
               .replace('10', 'MM', 1).replace('29', 'DD', 1) \
               .replace('23', 'hh', 1).replace('59', 'mm', 1) \
               .replace('58', 'ss', 1)

def http_date(t=None):
    """Format t as a rfc822 timestamp"""
    if t is None:
        t = time.time()
    if not isinstance(t, (list, tuple, time.struct_time)):
        t = time.gmtime(int(t))
    weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
    months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
              'Oct', 'Nov', 'Dec']
    return '%s, %02d %s %04d %02d:%02d:%02d GMT' % (
           weekdays[t.tm_wday], t.tm_mday, months[t.tm_mon - 1], t.tm_year,
           t.tm_hour, t.tm_min, t.tm_sec)

def parse_date(text):
    seconds = None
    text = text.strip()
    for format in ['%x %X', '%x, %X', '%X %x', '%X, %x', '%x', '%c',
                   '%b %d, %Y']:
        try:
            date = time.strptime(text, format)
            seconds = time.mktime(date)
            break
        except ValueError:
            continue
    if seconds == None:
        raise ValueError, '%s is not a known date format.' % text
    return seconds
<commit_msg>Cast timestamp strings into floats instead of ints to avoid problems with custom sql reports. Closes #3476.<commit_after># -*- coding: utf-8 -*-
#
# Copyright (C) 2003-2006 Edgewall Software
# Copyright (C) 2003-2004 Jonas Borgström <jonas@edgewall.com>
# Copyright (C) 2006 Matthew Good <trac@matt-good.net>
# Copyright (C) 2005-2006 Christian Boos <cboos@neuf.fr>
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://trac.edgewall.org/wiki/TracLicense.
#
# This software consists of voluntary contributions made by many
# individuals. For the exact contribution history, see the revision
# history and logs, available at http://trac.edgewall.org/log/.
#
# Author: Jonas Borgström <jonas@edgewall.com>
#         Matthew Good <trac@matt-good.net>

import locale
import sys
import time

# Date/time utilities

def pretty_timedelta(time1, time2=None, resolution=None):
    """Calculate time delta (inaccurately, only for decorative purposes ;-) for
    prettyprinting. If time1 is None, the current time is used."""
    if not time1: time1 = time.time()
    if not time2: time2 = time.time()
    if time1 > time2:
        time2, time1 = time1, time2
    units = ((3600 * 24 * 365, 'year',   'years'),
             (3600 * 24 * 30,  'month',  'months'),
             (3600 * 24 * 7,   'week',   'weeks'),
             (3600 * 24,       'day',    'days'),
             (3600,            'hour',   'hours'),
             (60,              'minute', 'minutes'))
    age_s = int(time2 - time1)
    if resolution and age_s < resolution:
        return ''
    if age_s < 60:
        return '%i second%s' % (age_s, age_s != 1 and 's' or '')
    for u, unit, unit_plural in units:
        r = float(age_s) / float(u)
        if r >= 0.9:
            r = int(round(r))
            return '%d %s' % (r, r == 1 and unit or unit_plural)
    return ''

def format_datetime(t=None, format='%x %X', gmt=False):
    if t is None:
        t = time.time()
    if not isinstance(t, (list, tuple, time.struct_time)):
        if gmt:
            t = time.gmtime(float(t))
        else:
            t = time.localtime(float(t))

    text = time.strftime(format, t)
    encoding = locale.getpreferredencoding()
    if sys.platform != 'win32':
        encoding = locale.getlocale(locale.LC_TIME)[1] or encoding
        # the above is broken on win32, e.g. we'd get '437' instead of 'cp437'
    return unicode(text, encoding, 'replace')

def format_date(t=None, format='%x', gmt=False):
    return format_datetime(t, format, gmt)

def format_time(t=None, format='%X', gmt=False):
    return format_datetime(t, format, gmt)

def get_date_format_hint():
    t = time.localtime(0)
    t = (1999, 10, 29, t[3], t[4], t[5], t[6], t[7], t[8])
    tmpl = format_date(t)
    return tmpl.replace('1999', 'YYYY', 1).replace('99', 'YY', 1) \
               .replace('10', 'MM', 1).replace('29', 'DD', 1)

def get_datetime_format_hint():
    t = time.localtime(0)
    t = (1999, 10, 29, 23, 59, 58, t[6], t[7], t[8])
    tmpl = format_datetime(t)
    return tmpl.replace('1999', 'YYYY', 1).replace('99', 'YY', 1) \
               .replace('10', 'MM', 1).replace('29', 'DD', 1) \
               .replace('23', 'hh', 1).replace('59', 'mm', 1) \
               .replace('58', 'ss', 1)

def http_date(t=None):
    """Format t as a rfc822 timestamp"""
    if t is None:
        t = time.time()
    if not isinstance(t, (list, tuple, time.struct_time)):
        t = time.gmtime(float(t))
    weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
    months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
              'Oct', 'Nov', 'Dec']
    return '%s, %02d %s %04d %02d:%02d:%02d GMT' % (
           weekdays[t.tm_wday], t.tm_mday, months[t.tm_mon - 1], t.tm_year,
           t.tm_hour, t.tm_min, t.tm_sec)

def parse_date(text):
    seconds = None
    text = text.strip()
    for format in ['%x %X', '%x, %X', '%X %x', '%X, %x', '%x', '%c',
                   '%b %d, %Y']:
        try:
            date = time.strptime(text, format)
            seconds = time.mktime(date)
            break
        except ValueError:
            continue
    if seconds == None:
        raise ValueError, '%s is not a known date format.' % text
    return seconds
<|endoftext|>


<commit_before><commit_msg>Fix msvs_guid for gmock and re-add gmock_unittest into base_unittest.<commit_after><|endoftext|>


<commit_before><commit_msg>Fix bad tabs introduced in r56309 and r56311 in base/base.gyp.<commit_after><|endoftext|>