ubuntuone-dev-tools-13.10/0000755000202700020270000000000012225022242015667 5ustar dobeydobey00000000000000ubuntuone-dev-tools-13.10/ubuntuone/0000755000202700020270000000000012225022242017713 5ustar dobeydobey00000000000000ubuntuone-dev-tools-13.10/ubuntuone/__init__.py0000664000202700020270000000264312166632147022052 0ustar dobeydobey00000000000000# Copyright 2009-2012 Canonical Ltd. # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR # PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program. If not, see . # # In addition, as a special exception, the copyright holders give # permission to link the code of portions of this program with the # OpenSSL library under certain conditions as described in each # individual source file, and distribute linked combinations # including the two. # You must obey the GNU General Public License in all respects # for all of the code used other than OpenSSL. If you modify # file(s) with this exception, you may extend this exception to your # version of the file(s), but you are not obligated to do so. If you # do not wish to do so, delete this exception statement from your # version. If you delete this exception statement from all source # files in the program, then also delete it here. """ubuntuone package""" __import__('pkg_resources').declare_namespace(__name__) ubuntuone-dev-tools-13.10/ubuntuone/devtools/0000755000202700020270000000000012225022242021552 5ustar dobeydobey00000000000000ubuntuone-dev-tools-13.10/ubuntuone/devtools/reactors/0000755000202700020270000000000012225022242023374 5ustar dobeydobey00000000000000ubuntuone-dev-tools-13.10/ubuntuone/devtools/reactors/twisted.py0000664000202700020270000000312012166632147025446 0ustar dobeydobey00000000000000# Copyright 2011-2012 Canonical Ltd. # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR # PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program. If not, see . # # In addition, as a special exception, the copyright holders give # permission to link the code of portions of this program with the # OpenSSL library under certain conditions as described in each # individual source file, and distribute linked combinations # including the two. # You must obey the GNU General Public License in all respects # for all of the code used other than OpenSSL. If you modify # file(s) with this exception, you may extend this exception to your # version of the file(s), but you are not obligated to do so. If you # do not wish to do so, delete this exception statement from your # version. If you delete this exception statement from all source # files in the program, then also delete it here. """The standard twisted reactor for testing.""" def install(options=None): """Install the reactor and parse any options we might need.""" # The twisted reactor installs when imported __import__('twisted.internet', None, None, ['reactor']) ubuntuone-dev-tools-13.10/ubuntuone/devtools/reactors/__init__.py0000664000202700020270000000004412166632147025524 0ustar dobeydobey00000000000000"""Twisted reactors for testing.""" ubuntuone-dev-tools-13.10/ubuntuone/devtools/reactors/txnp.py0000664000202700020270000000332612166632147024764 0ustar dobeydobey00000000000000# -*- coding: utf-8 -*- # # Author: Manuel de la Pena manuel@canonical.com # # Copyright 2011-2012 Canonical Ltd. # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR # PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program. If not, see . # # In addition, as a special exception, the copyright holders give # permission to link the code of portions of this program with the # OpenSSL library under certain conditions as described in each # individual source file, and distribute linked combinations # including the two. # You must obey the GNU General Public License in all respects # for all of the code used other than OpenSSL. If you modify # file(s) with this exception, you may extend this exception to your # version of the file(s), but you are not obligated to do so. If you # do not wish to do so, delete this exception statement from your # version. If you delete this exception statement from all source # files in the program, then also delete it here. """The NamedPipes integration reactor for testing on Windows.""" REACTOR_URL = 'https://launchpad.net/txnamedpipes' def install(options=None): """Install the reactor and parse any options we might need.""" txnpreactor = __import__('txnamedpipes.reactor', None, None, ['']) txnpreactor.install() ubuntuone-dev-tools-13.10/ubuntuone/devtools/reactors/gi.py0000664000202700020270000000437012166632147024372 0ustar dobeydobey00000000000000# Copyright 2009-2012 Canonical Ltd. # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR # PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program. If not, see . # # In addition, as a special exception, the copyright holders give # permission to link the code of portions of this program with the # OpenSSL library under certain conditions as described in each # individual source file, and distribute linked combinations # including the two. # You must obey the GNU General Public License in all respects # for all of the code used other than OpenSSL. If you modify # file(s) with this exception, you may extend this exception to your # version of the file(s), but you are not obligated to do so. If you # do not wish to do so, delete this exception statement from your # version. If you delete this exception statement from all source # files in the program, then also delete it here. """The introspection based main loop integration reactor for testing.""" REACTOR_URL = 'http://twistedmatrix.com/trac/ticket/4558' def load_reactor(reactor_name=None): """Load the reactor module and return it.""" return __import__(reactor_name, None, None, ['']) def install(options=None): """Install the reactor and parse any options we might need.""" reactor = None if options is not None and options['gui']: try: reactor = load_reactor('twisted.internet.gtk3reactor') except ImportError: print('Falling back to gtk2reactor module.') reactor = load_reactor('twisted.internet.gtk2reactor') else: try: reactor = load_reactor('twisted.internet.gireactor') except ImportError: print('Falling back to glib2reactor module.') reactor = load_reactor('twisted.internet.glib2reactor') reactor.install() ubuntuone-dev-tools-13.10/ubuntuone/devtools/reactors/qt4.py0000664000202700020270000000433212166632147024501 0ustar dobeydobey00000000000000# Author: Manuel de la Pena manuel@canonical.com # # Copyright 2010-2012 Canonical Ltd. # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR # PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program. If not, see . # # In addition, as a special exception, the copyright holders give # permission to link the code of portions of this program with the # OpenSSL library under certain conditions as described in each # individual source file, and distribute linked combinations # including the two. # You must obey the GNU General Public License in all respects # for all of the code used other than OpenSSL. If you modify # file(s) with this exception, you may extend this exception to your # version of the file(s), but you are not obligated to do so. If you # do not wish to do so, delete this exception statement from your # version. If you delete this exception statement from all source # files in the program, then also delete it here. """The Qt main loop integration reactor for testing.""" import sys REACTOR_URL = 'https://github.com/ghtdak/qtreactor' def install(options=None): """Install the reactor and parse any options we might need.""" if options is not None and options['gui']: from PyQt4.QtGui import QApplication # We must assign this to a variable, or we will get crashes in Qt # pylint: disable=W0612 app = QApplication(sys.argv) # pylint: enable=W0612 assert(app) try: qt4reactor = __import__('qt4reactor', None, None, ['']) except ImportError: # Leave this import in place for a couple of weeks # until all the devs are using the packaged qt4reactor # (nessita, 11-11-11) qt4reactor = __import__('qtreactor.qt4reactor', None, None, ['']) qt4reactor.install() ubuntuone-dev-tools-13.10/ubuntuone/devtools/reactors/glib.py0000664000202700020270000000341712166632147024711 0ustar dobeydobey00000000000000# Copyright 2009-2012 Canonical Ltd. # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR # PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program. If not, see . # # In addition, as a special exception, the copyright holders give # permission to link the code of portions of this program with the # OpenSSL library under certain conditions as described in each # individual source file, and distribute linked combinations # including the two. # You must obey the GNU General Public License in all respects # for all of the code used other than OpenSSL. If you modify # file(s) with this exception, you may extend this exception to your # version of the file(s), but you are not obligated to do so. If you # do not wish to do so, delete this exception statement from your # version. If you delete this exception statement from all source # files in the program, then also delete it here. """The default glib/gtk main loop integration reactor for testing.""" def install(options=None): """Install the reactor and parse any options we might need.""" reactor_name = None if options is not None and options['gui']: reactor_name = 'twisted.internet.gtk2reactor' else: reactor_name = 'twisted.internet.glib2reactor' glibreactor = __import__(reactor_name, None, None, ['']) glibreactor.install() ubuntuone-dev-tools-13.10/ubuntuone/devtools/errors.py0000664000202700020270000000311512166632147023461 0ustar dobeydobey00000000000000# Copyright 2012 Canonical Ltd. # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR # PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program. If not, see . # # In addition, as a special exception, the copyright holders give # permission to link the code of portions of this program with the # OpenSSL library under certain conditions as described in each # individual source file, and distribute linked combinations # including the two. # You must obey the GNU General Public License in all respects # for all of the code used other than OpenSSL. If you modify # file(s) with this exception, you may extend this exception to your # version of the file(s), but you are not obligated to do so. If you # do not wish to do so, delete this exception statement from your # version. If you delete this exception statement from all source # files in the program, then also delete it here. """Custom error types for Ubuntu One developer tools.""" class TestError(Exception): """An error occurred in attempting to load or start the tests.""" class UsageError(Exception): """An error occurred in parsing the command line arguments.""" ubuntuone-dev-tools-13.10/ubuntuone/devtools/__init__.py0000664000202700020270000000006412166632147023704 0ustar dobeydobey00000000000000"""Testing utilities for Ubuntu One client code.""" ubuntuone-dev-tools-13.10/ubuntuone/devtools/testing/0000755000202700020270000000000012225022242023227 5ustar dobeydobey00000000000000ubuntuone-dev-tools-13.10/ubuntuone/devtools/testing/__init__.py0000664000202700020270000000002712166632147025360 0ustar dobeydobey00000000000000"""Testing helpers.""" ubuntuone-dev-tools-13.10/ubuntuone/devtools/testing/txcheck.py0000664000202700020270000003031312166632147025253 0ustar dobeydobey00000000000000# -*- coding: utf-8 -*- # Author: Tim Cole # # Copyright 2011-2012 Canonical Ltd. # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR # PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program. If not, see . # # In addition, as a special exception, the copyright holders give # permission to link the code of portions of this program with the # OpenSSL library under certain conditions as described in each # individual source file, and distribute linked combinations # including the two. # You must obey the GNU General Public License in all respects # for all of the code used other than OpenSSL. If you modify # file(s) with this exception, you may extend this exception to your # version of the file(s), but you are not obligated to do so. If you # do not wish to do so, delete this exception statement from your # version. If you delete this exception statement from all source # files in the program, then also delete it here. """Utilities for performing correctness checks.""" import sys import ast from inspect import getsource from textwrap import dedent from itertools import takewhile from unittest import TestCase, TestSuite, TestResult from twisted.trial.unittest import TestCase as TwistedTestCase def type_to_name(type_obj): """Return a name for a type.""" package_name = getattr(type_obj, '__module__', None) if package_name: return "%s.%s" % (package_name, type_obj.__name__) else: return type_obj.__name__ class Problem(AssertionError): """An object representing a problem in a method.""" def __init__(self, method, test_class, ancestor_class): """Initialize an instance.""" super(Problem, self).__init__() self.method = method self.test_class = test_class self.ancestor_class = ancestor_class def __eq__(self, other): """Test equality.""" return type(self) == type(other) and self.__dict__ == other.__dict__ def __ne__(self, other): """Test inequality.""" return not (self == other) def __hash__(self): """Return hash.""" member_hash = 0 for (key, value) in self.__dict__.items(): member_hash ^= hash(key) ^ hash(value) return hash(type(self)) ^ member_hash def __str__(self): """Return a friendlier representation.""" if self.ancestor_class != self.test_class: method_string = ("%s in ancestor method %s.%s" % (type_to_name(self.test_class), type_to_name(self.ancestor_class), self.method)) else: method_string = ("%s.%s" % (type_to_name(self.test_class), self.method)) return ("%s for %s" % (type(self).__name__, method_string)) def __repr__(self): """Return representation string.""" return "<%s %r>" % (type(self), self.__dict__) class MethodShadowed(Problem): """Problem when trial's run method is shadowed.""" class SuperResultDiscarded(Problem): """Problem when callback chains are broken.""" class SuperNotCalled(Problem): """Problem when super isn't called.""" class MissingInlineCallbacks(Problem): """Problem when the inlineCallbacks decorator is missing.""" class MissingReturnValue(Problem): """Problem when there's no return value.""" def match_type(expected_type): """Return predicate matching nodes of given type.""" return lambda node: isinstance(node, expected_type) def match_equal(expected_value): """Return predicate matching nodes equaling the given value.""" return lambda node: expected_value == node def match_in(expected_values): """Return predicate matching node if in collection of expected values.""" return lambda node: node in expected_values def match_not_none(): """Returns a predicate matching nodes which are not None.""" return lambda node: node is not None def match_any(*subtests): """Return short-circuiting predicate matching any given subpredicate.""" if len(subtests) == 1: return subtests[0] else: def test(node): """Try each subtest until we find one that passes.""" for subtest in subtests: if subtest(node): return True return False return test def match_all(*subtests): """Return short-circuiting predicate matching all given subpredicates.""" if len(subtests) == 1: return subtests[0] else: def test(node): """Try each subtest until we find one that fails.""" for subtest in subtests: if not subtest(node): return False return True return test def match_attr(attr_name, *tests): """Return predicate matching subpredicates against an attribute value.""" return lambda node: match_all(*tests)(getattr(node, attr_name)) def match_path(initial_test, *components): """Return predicate which recurses into the tree via given attributes.""" components = list(components) components.reverse() test = lambda node: True for component in components: attr_name = component[0] subtests = component[1:] test = match_attr(attr_name, match_all(match_all(*subtests), test)) return match_all(initial_test, test) def match_child(*tests): """Return predicate which tests any child.""" subtest = match_all(*tests) def test(node): """Try each child until we find one that matches.""" for child in ast.iter_child_nodes(node): if subtest(child): return True return False return test def match_descendant(subtest, prune): """Return predicate which tests a node and any descendants.""" def test(node): """Recursively (breadth-first) search for a matching node.""" for child in ast.iter_child_nodes(node): if prune(child): continue if subtest(child) or test(child): return True return False return test def matches(node, *tests): """Convenience function to try predicates on a node.""" return match_all(*tests)(node) def any_matches(nodes, *tests): """Convenience function to try predicates on any of a sequence of nodes.""" test = match_all(*tests) for node in nodes: if test(node): return True return False def iter_matching_child_nodes(node, *tests): """Yields every matching child node.""" test = match_all(*tests) for child in ast.iter_child_nodes(node): if test(child): yield child SETUP_FUNCTION_NAMES = ('setUp', 'tearDown') SETUP_FUNCTION = match_path(match_type(ast.FunctionDef), ('name', match_in(SETUP_FUNCTION_NAMES))) SUPER = match_path(match_type(ast.Call), ('func', match_type(ast.Attribute)), ('value', match_type(ast.Call)), ('func', match_type(ast.Name)), ('id', match_equal("super"))) BARE_SUPER = match_path(match_type(ast.Expr), ('value', SUPER)) YIELD = match_type(ast.Yield) INLINE_CALLBACKS_DECORATOR = \ match_any(match_path(match_type(ast.Attribute), ('attr', match_equal('inlineCallbacks'))), match_path(match_type(ast.Name), ('id', match_equal('inlineCallbacks')))) RETURN_VALUE = \ match_path(match_type(ast.Return), ('value', match_not_none())) DEFS = match_any(match_type(ast.ClassDef), match_type(ast.FunctionDef)) def find_problems(class_to_check): """Check twisted test setup in a given test class.""" mro = class_to_check.__mro__ if TwistedTestCase not in mro: return set() problems = set() ancestry = takewhile(lambda c: c != TwistedTestCase, mro) for ancestor_class in ancestry: if 'run' in ancestor_class.__dict__: problem = MethodShadowed(method='run', test_class=class_to_check, ancestor_class=ancestor_class) problems.add(problem) source = dedent(getsource(ancestor_class)) tree = ast.parse(source) # the top level of the tree is a Module class_node = tree.body[0] # Check setUp/tearDown for def_node in iter_matching_child_nodes(class_node, SETUP_FUNCTION): if matches(def_node, match_child(BARE_SUPER)): # Superclass method called, but its result wasn't used problem = SuperResultDiscarded(method=def_node.name, test_class=class_to_check, ancestor_class=ancestor_class) problems.add(problem) if not matches(def_node, match_descendant(SUPER, DEFS)): # The call to the overridden superclass method is missing problem = SuperNotCalled(method=def_node.name, test_class=class_to_check, ancestor_class=ancestor_class) problems.add(problem) decorators = def_node.decorator_list if matches(def_node, match_descendant(YIELD, DEFS)): # Yield was used, making this a generator if not any_matches(decorators, INLINE_CALLBACKS_DECORATOR): # ...but the inlineCallbacks decorator is missing problem = MissingInlineCallbacks( method=def_node.name, test_class=class_to_check, ancestor_class=ancestor_class) problems.add(problem) else: if not matches(def_node, match_descendant(RETURN_VALUE, DEFS)): # The function fails to return a deferred problem = MissingReturnValue( method=def_node.name, test_class=class_to_check, ancestor_class=ancestor_class) problems.add(problem) return problems def get_test_classes(suite): """Return all the unique test classes involved in a suite.""" classes = set() def find_classes(suite_or_test): """Recursively find all the test classes.""" if isinstance(suite_or_test, TestSuite): for subtest in suite_or_test: find_classes(subtest) else: classes.add(type(suite_or_test)) find_classes(suite) return classes def make_check_testcase(tests): """Make TestCase which checks the given twisted tests.""" class TXCheckTest(TestCase): """Test case which checks the test classes for problems.""" def runTest(self): # pylint: disable=C0103 """Do nothing.""" def run(self, result=None): """Check all the test classes for problems.""" if result is None: result = TestResult() test_classes = set() for test_object in tests: test_classes |= get_test_classes(test_object) for test_class in test_classes: problems = find_problems(test_class) for problem in problems: try: raise problem except Problem: result.addFailure(self, sys.exc_info()) return TXCheckTest() class TXCheckSuite(TestSuite): """Test suite which checks twisted tests.""" def __init__(self, tests=()): """Initialize with the given tests, and add a special test.""" tests = list(tests) tests.insert(0, make_check_testcase(self)) super(TXCheckSuite, self).__init__(tests) ubuntuone-dev-tools-13.10/ubuntuone/devtools/testing/txwebserver.py0000664000202700020270000001123012166632147026177 0ustar dobeydobey00000000000000# -*- coding: utf-8 -*- # Copyright 2012 Canonical Ltd. # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR # PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program. If not, see . # # In addition, as a special exception, the copyright holders give # permission to link the code of portions of this program with the # OpenSSL library under certain conditions as described in each # individual source file, and distribute linked combinations # including the two. # You must obey the GNU General Public License in all respects # for all of the code used other than OpenSSL. If you modify # file(s) with this exception, you may extend this exception to your # version of the file(s), but you are not obligated to do so. If you # do not wish to do so, delete this exception statement from your # version. If you delete this exception statement from all source # files in the program, then also delete it here. """A tx based web server.""" from __future__ import unicode_literals from twisted.internet import defer, reactor, ssl from twisted.protocols.policies import WrappingFactory from twisted.web import server from ubuntuone.devtools.testcases.txsocketserver import server_protocol_factory # no init method + twisted common warnings # pylint: disable=W0232, C0103, E1101 class BaseWebServer(object): """Webserver used to perform requests in tests.""" def __init__(self, root_resource, scheme): """Create and start the instance. The ssl_settings parameter contains a dictionary with the key and cert that will be used to perform ssl connections. The root_resource contains the resource with all its childre. """ self.root = root_resource self.scheme = scheme self.port = None # use an http.HTTPFactory that was modified to ensure that we have # clean close connections self.site = server.Site(self.root, timeout=None) self.wrapper = WrappingFactory(self.site) self.wrapper.testserver_on_connection_lost = defer.Deferred() self.wrapper.protocol = server_protocol_factory(self.wrapper.protocol) self.wrapper._disconnecting = False def listen(self, site): """Listen a port to allow the tests.""" raise NotImplementedError('Base abstract class.') def get_iri(self): """Build the iri for this mock server.""" return "{scheme}://127.0.0.1:{port}/".format(scheme=self.scheme, port=self.get_port()) def get_port(self): """Return the port where we are listening.""" return self.port.getHost().port def start(self): """Start the service.""" self.port = self.listen(self.wrapper) def stop(self): """Shut it down.""" if self.port: self.wrapper._disconnecting = True connected = self.wrapper.protocols.keys() if connected: for con in connected: con.transport.loseConnection() else: self.wrapper.testserver_on_connection_lost = \ defer.succeed(None) d = defer.maybeDeferred(self.port.stopListening) return defer.gatherResults( [d, self.wrapper.testserver_on_connection_lost]) return defer.succeed(None) class HTTPWebServer(BaseWebServer): """A Webserver that listens to http connections.""" def __init__(self, root_resource): """Create a new instance.""" super(HTTPWebServer, self).__init__(root_resource, 'http') def listen(self, site): """Listen a port to allow the tests.""" return reactor.listenTCP(0, site) class HTTPSWebServer(BaseWebServer): """A WebServer that listens to https connections.""" def __init__(self, root_resource, ssl_settings=None): """Create a new instance.""" super(HTTPSWebServer, self).__init__(root_resource, 'https') self.ssl_settings = ssl_settings def listen(self, site): """Listen a port to allow the tests.""" ssl_context = ssl.DefaultOpenSSLContextFactory( self.ssl_settings['key'], self.ssl_settings['cert']) return reactor.listenSSL(0, site, ssl_context) ubuntuone-dev-tools-13.10/ubuntuone/devtools/services/0000755000202700020270000000000012225022242023375 5ustar dobeydobey00000000000000ubuntuone-dev-tools-13.10/ubuntuone/devtools/services/squid.py0000664000202700020270000002601612216607771025123 0ustar dobeydobey00000000000000# # Copyright 2011-2013 Canonical Ltd. # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR # PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program. If not, see . # # In addition, as a special exception, the copyright holders give # permission to link the code of portions of this program with the # OpenSSL library under certain conditions as described in each # individual source file, and distribute linked combinations # including the two. # You must obey the GNU General Public License in all respects # for all of the code used other than OpenSSL. If you modify # file(s) with this exception, you may extend this exception to your # version of the file(s), but you are not obligated to do so. If you # do not wish to do so, delete this exception statement from your # version. If you delete this exception statement from all source # files in the program, then also delete it here. """Utilities for finding and running a squid proxy for testing.""" from __future__ import print_function import errno import random import signal # pylint:disable=W0402 import string # pylint:enable=W0402 import subprocess import sys import time from json import dumps, loads from os import environ, kill, makedirs, unlink from os.path import abspath, exists, join from distutils.spawn import find_executable from ubuntuone.devtools.services import ( find_config_file, get_arbitrary_port, ) NCSA_BASIC_PREFIX = 'basic_' if sys.platform == 'win32': AUTH_PROCESS_PATH = 'C:\\squid\\libexec\\' AUTH_PROCESS_NAME = 'ncsa_auth.exe' SQUID_START_ARGS = ['-f'] else: AUTH_PROCESS_PATH = '/usr/lib/%s/' AUTH_PROCESS_NAME = 'ncsa_auth' SQUID_START_ARGS = ['-N', '-X', '-f'] SQUID_CONFIG_FILE = 'squid.conf.in' SQUID_DIR = 'squid' SPOOL_DIR = 'spool' AUTH_FILE = 'htpasswd' PROXY_ENV_VAR = 'SQUID_PROXY_SETTINGS' def format_config_path(path): """Return the path correctly formatted for the config file.""" # squid cannot handle correctly paths with a single \ return path.replace('\\', '\\\\') def get_auth_process_path(squid_version): """Return the path to the auth executable.""" if sys.platform == 'win32': path = find_executable('ncsa_auth') if path is None: path = AUTH_PROCESS_PATH + NCSA_BASIC_PREFIX + AUTH_PROCESS_NAME if not exists(path): path = AUTH_PROCESS_PATH + AUTH_PROCESS_NAME return format_config_path(path) else: squid = 'squid3' if squid_version == 3 else 'squid' auth_path = (AUTH_PROCESS_PATH % squid) path = auth_path + NCSA_BASIC_PREFIX + AUTH_PROCESS_NAME if not exists(path): path = auth_path + AUTH_PROCESS_NAME return path def get_squid_executable(): """Return the squid executable of the system.""" # try with squid and if not present try with squid3 for newer systems # (Ubuntu P). We also return the path to the auth process so that we can # point to the correct one. squid = find_executable('squid3') version = 3 if squid is None: version = 2 squid = find_executable('squid') auth_process = get_auth_process_path(version) return squid, auth_process def get_htpasswd_executable(): """Return the htpasswd executable.""" return find_executable('htpasswd') def kill_squid(squid_pid): """Kill the squid process.""" if sys.platform == 'win32': # pylint: disable=F0401 import win32api import win32con # pylint: enable=F0401 handle = win32api.OpenProcess(win32con.PROCESS_TERMINATE, 0, squid_pid) win32api.TerminateProcess(handle, 0) win32api.CloseHandle(handle) else: # pylint: disable=E1101 kill(squid_pid, signal.SIGKILL) # pylint: enable=E1101 def _make_random_string(count): """Make a random string of the given length.""" entropy = random.SystemRandom() return ''.join([entropy.choice(string.letters) for _ in range(count)]) def _get_basedir(tempdir): """Return the base squid config.""" basedir = join(tempdir, SQUID_DIR) basedir = abspath(basedir) if not exists(basedir): makedirs(basedir) return basedir def _get_spool_temp_path(tempdir=''): """Return the temp dir to be used for spool.""" basedir = _get_basedir(tempdir) path = join(basedir, SPOOL_DIR) path = abspath(path) if not exists(path): makedirs(path) return format_config_path(path) def _get_squid_temp_path(tempdir=''): """Return the temp dir to be used by squid.""" basedir = _get_basedir(tempdir) path = join(basedir, SQUID_DIR) path = abspath(path) if not exists(path): makedirs(path) return format_config_path(join(path, '')) def _get_auth_temp_path(tempdir=''): """Return the path for the auth file.""" basedir = _get_basedir(tempdir) auth_file = join(basedir, AUTH_FILE) if not exists(basedir): makedirs(basedir) return format_config_path(auth_file) def store_proxy_settings(settings): """Store the proxy setting in an env var.""" environ[PROXY_ENV_VAR] = dumps(settings) def retrieve_proxy_settings(): """Return the proxy settings of the env.""" if PROXY_ENV_VAR in environ: return loads(environ[PROXY_ENV_VAR]) return None def delete_proxy_settings(): """Delete the proxy env settings.""" if PROXY_ENV_VAR in environ: del environ[PROXY_ENV_VAR] class SquidLaunchError(Exception): """Error while launching squid.""" class SquidRunner(object): """Class for running a squid proxy with the local config.""" def __init__(self): """Create a new instance.""" self.squid, self.auth_process = get_squid_executable() if self.squid is None: raise SquidLaunchError('Could not locate "squid".') self.htpasswd = get_htpasswd_executable() if self.htpasswd is None: raise SquidLaunchError('Could not locate "htpasswd".') self.settings = dict(noauth_port=None, auth_port=None, username=None, password=None) self.squid_pid = None self.running = False self.config_file = None self.auth_file = None def _generate_config_file(self, tempdir=''): """Find the first appropiate squid.conf to use.""" # load the config file path = find_config_file(SQUID_CONFIG_FILE) # replace config settings basedir = join(tempdir, 'squid') basedir = abspath(basedir) if not exists(basedir): makedirs(basedir) self.config_file = join(basedir, 'squid.conf') with open(path) as in_file: template = string.Template(in_file.read()) self.settings['noauth_port'] = get_arbitrary_port() self.settings['auth_port'] = get_arbitrary_port() spool_path = _get_spool_temp_path(tempdir) squid_path = _get_squid_temp_path(tempdir) with open(self.config_file, 'w') as out_file: out_file.write( template.safe_substitute( auth_file=self.auth_file, auth_process=self.auth_process, noauth_port_number=self.settings['noauth_port'], auth_port_number=self.settings['auth_port'], spool_temp=spool_path, squid_temp=squid_path)) def _generate_swap(self, config_file): """Generate the squid swap files.""" squid_args = ['-z', '-f', config_file] sp = subprocess.Popen([self.squid] + squid_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) sp.wait() def _generate_auth_file(self, tempdir=''): """Generates a auth file using htpasswd.""" if self.settings['username'] is None: self.settings['username'] = _make_random_string(10) if self.settings['password'] is None: self.settings['password'] = _make_random_string(10) self.auth_file = _get_auth_temp_path(tempdir) # remove possible old auth file if exists(self.auth_file): unlink(self.auth_file) # create a new htpasswrd htpasswd_args = ['-bc', self.auth_file, self.settings['username'], self.settings['password']] sp = subprocess.Popen([self.htpasswd] + htpasswd_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) sp.wait() def _is_squid_running(self): """Return if squid is running.""" squid_args = ['-k', 'check', '-f', self.config_file] print('Starting squid version...') message = 'Waiting for squid to start...' for timeout in (0.4, 0.1, 0.1, 0.2, 0.5, 1, 3, 5): try: # Do not use stdout=PIPE or stderr=PIPE with this function. subprocess.check_call([self.squid] + squid_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) return True except subprocess.CalledProcessError: message += '.' print(message) time.sleep(timeout) return False def start_service(self, tempdir=None): """Start our own proxy.""" # generate auth, config and swap dirs self._generate_auth_file(tempdir) self._generate_config_file(tempdir) self._generate_swap(self.config_file) squid_args = SQUID_START_ARGS squid_args.append(self.config_file) sp = subprocess.Popen([self.squid] + squid_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) store_proxy_settings(self.settings) if not self._is_squid_running(): # grab the stdout and stderr to provide more information output = sp.stdout.read() err = sp.stderr.read() msg = 'Could not start squid:\nstdout:\n%s\nstderr\n%s' % ( output, err) raise SquidLaunchError(msg) self.squid_pid = sp.pid self.running = True def stop_service(self): """Stop our proxy,""" try: kill_squid(self.squid_pid) except OSError as err: # If the process already died, ignore the error if err.errno == errno.ESRCH: pass else: raise delete_proxy_settings() self.running = False unlink(self.config_file) unlink(self.auth_file) self.config_file = None ubuntuone-dev-tools-13.10/ubuntuone/devtools/services/dbus.py0000664000202700020270000001044212166632147024726 0ustar dobeydobey00000000000000# # Author: Guillermo Gonzalez # # Copyright 2009-2012 Canonical Ltd. # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR # PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program. If not, see . # # In addition, as a special exception, the copyright holders give # permission to link the code of portions of this program with the # OpenSSL library under certain conditions as described in each # individual source file, and distribute linked combinations # including the two. # You must obey the GNU General Public License in all respects # for all of the code used other than OpenSSL. If you modify # file(s) with this exception, you may extend this exception to your # version of the file(s), but you are not obligated to do so. If you # do not wish to do so, delete this exception statement from your # version. If you delete this exception statement from all source # files in the program, then also delete it here. """Utilities for finding and running a dbus session bus for testing.""" from __future__ import unicode_literals import os import signal import subprocess from distutils.spawn import find_executable # pylint: disable=F0401,E0611 try: from urllib.parse import quote except ImportError: from urllib import quote # pylint: enable=F0401,E0611 from ubuntuone.devtools.services import find_config_file DBUS_CONFIG_FILE = 'dbus-session.conf.in' class DBusLaunchError(Exception): """Error while launching dbus-daemon""" pass class NotFoundError(Exception): """Not found error""" pass class DBusRunner(object): """Class for running dbus-daemon with a private session.""" def __init__(self): self.dbus_address = None self.dbus_pid = None self.running = False self.config_file = None def _generate_config_file(self, tempdir=None): """Find the first appropriate dbus-session.conf to use.""" # load the config file path = find_config_file(DBUS_CONFIG_FILE) # replace config settings self.config_file = os.path.join(tempdir, 'dbus-session.conf') dbus_address = 'unix:tmpdir=%s' % quote(tempdir) with open(path) as in_file: content = in_file.read() with open(self.config_file, 'w') as out_file: out_file.write(content.replace('@ADDRESS@', dbus_address)) def start_service(self, tempdir=None): """Start our own session bus daemon for testing.""" dbus = find_executable("dbus-daemon") if not dbus: raise NotFoundError("dbus-daemon was not found.") self._generate_config_file(tempdir) dbus_args = ["--fork", "--config-file=" + self.config_file, "--print-address=1", "--print-pid=2"] sp = subprocess.Popen([dbus] + dbus_args, bufsize=4096, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # Call wait here as under the qt4 reactor we get an error about # interrupted system call if we don't. sp.wait() self.dbus_address = b"".join(sp.stdout.readlines()).strip() self.dbus_pid = int(b"".join(sp.stderr.readlines()).strip()) if self.dbus_address != "": os.environ["DBUS_SESSION_BUS_ADDRESS"] = \ self.dbus_address.decode("utf8") else: os.kill(self.dbus_pid, signal.SIGKILL) raise DBusLaunchError("There was a problem launching dbus-daemon.") self.running = True def stop_service(self): """Stop our DBus session bus daemon.""" try: del os.environ["DBUS_SESSION_BUS_ADDRESS"] except KeyError: pass os.kill(self.dbus_pid, signal.SIGKILL) self.running = False os.unlink(self.config_file) self.config_file = None ubuntuone-dev-tools-13.10/ubuntuone/devtools/services/__init__.py0000664000202700020270000000506612166632147025536 0ustar dobeydobey00000000000000# # Copyright 2011-2012 Canonical Ltd. # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR # PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program. If not, see . # # In addition, as a special exception, the copyright holders give # permission to link the code of portions of this program with the # OpenSSL library under certain conditions as described in each # individual source file, and distribute linked combinations # including the two. # You must obey the GNU General Public License in all respects # for all of the code used other than OpenSSL. If you modify # file(s) with this exception, you may extend this exception to your # version of the file(s), but you are not obligated to do so. If you # do not wish to do so, delete this exception statement from your # version. If you delete this exception statement from all source # files in the program, then also delete it here. """Service runners for testing.""" import os import socket from dirspec.basedir import load_data_paths def find_config_file(in_config_file): """Find the first appropriate conf to use.""" # In case we're running from within the source tree path = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir, os.path.pardir, os.path.pardir, "data", in_config_file)) if not os.path.exists(path): # Use the installed file in $pkgdatadir as source for path in load_data_paths("ubuntuone-dev-tools", in_config_file): if os.path.exists(path): break # Check to make sure we didn't just fall out of the loop if not os.path.exists(path): raise IOError('Could not locate suitable %s' % in_config_file) return path def get_arbitrary_port(): """ Find an unused port, and return it. There might be a small race condition here, but we aren't worried about it. """ sock = socket.socket() sock.bind(('localhost', 0)) _, port = sock.getsockname() sock.close() return port ubuntuone-dev-tools-13.10/ubuntuone/devtools/utils.py0000664000202700020270000001453612166632147023316 0ustar dobeydobey00000000000000# Copyright 2009-2012 Canonical Ltd. # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR # PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program. If not, see . # # In addition, as a special exception, the copyright holders give # permission to link the code of portions of this program with the # OpenSSL library under certain conditions as described in each # individual source file, and distribute linked combinations # including the two. # You must obey the GNU General Public License in all respects # for all of the code used other than OpenSSL. If you modify # file(s) with this exception, you may extend this exception to your # version of the file(s), but you are not obligated to do so. If you # do not wish to do so, delete this exception statement from your # version. If you delete this exception statement from all source # files in the program, then also delete it here. """Utilities for Ubuntu One developer tools.""" from __future__ import print_function, unicode_literals import getopt import sys from ubuntuone.devtools.errors import UsageError __all__ = ['OptionParser'] def accumulate_list_attr(class_obj, attr, list_obj, base_class=None): """Get all of the list attributes of attr from the class hierarchy, and return a list of the lists.""" for base in class_obj.__bases__: accumulate_list_attr(base, attr, list_obj) if base_class is None or base_class in class_obj.__bases__: list_obj.extend(class_obj.__dict__.get(attr, [])) def unpack_padded(length, sequence, default=None): """Pads a sequence to length with value of default. Returns a list containing the original and padded values. """ newlist = [default] * length newlist[:len(sequence)] = list(sequence) return newlist class OptionParser(dict): """Base options for our test runner.""" def __init__(self, *args, **kwargs): super(OptionParser, self).__init__(*args, **kwargs) # Store info about the options and defaults self.long_opts = [] self.short_opts = '' self.docs = {} self.defaults = {} self.synonyms = {} self.dispatch = {} # Get the options and defaults for _get in [self._get_flags, self._get_params]: # We don't use variable 'syns' here. It's just to pad the result. # pylint: disable=W0612 (long_opts, short_opts, docs, defaults, syns, dispatch) = _get() # pylint: enable=W0612 self.long_opts.extend(long_opts) self.short_opts = self.short_opts + short_opts self.docs.update(docs) self.update(defaults) self.defaults.update(defaults) self.synonyms.update(syns) self.dispatch.update(dispatch) # We use some camelcase names for trial compatibility here. # pylint: disable=C0103 def parseOptions(self, options=None): """Parse the options.""" if options is None: options = sys.argv[1:] try: opts, args = getopt.getopt(options, self.short_opts, self.long_opts) except getopt.error as e: raise UsageError(e) for opt, arg in opts: if opt[1] == '-': opt = opt[2:] else: opt = opt[1:] if (opt not in self.synonyms.keys()): raise UsageError('No such options: "%s"' % opt) opt = self.synonyms[opt] if self.defaults[opt] is False: self[opt] = True else: self.dispatch[opt](arg) try: self.parseArgs(*args) except TypeError: raise UsageError('Wrong number of arguments.') self.postOptions() def postOptions(self): """Called after options are parsed.""" def parseArgs(self, *args): """Override to handle extra arguments specially.""" # pylint: enable=C0103 def _parse_arguments(self, arg_type=None, has_default=False): """Parse the arguments as either flags or parameters.""" long_opts, short_opts = [], '' docs, defaults, syns, dispatch = {}, {}, {}, {} _args = [] accumulate_list_attr(self.__class__, arg_type, _args) for _arg in _args: try: if has_default: l_opt, s_opt, default, doc = unpack_padded(4, _arg) else: default = False l_opt, s_opt, doc = unpack_padded(3, _arg) except ValueError: raise ValueError('Failed to parse argument: %s' % _arg) if not l_opt: raise ValueError('An option must have a long name.') opt_m_name = 'opt_' + l_opt.replace('-', '_') opt_method = getattr(self, opt_m_name, None) if opt_method is not None: docs[l_opt] = getattr(opt_method, '__doc__', None) dispatch[l_opt] = opt_method if docs[l_opt] is None: docs[l_opt] = doc else: docs[l_opt] = doc dispatch[l_opt] = lambda arg: True defaults[l_opt] = default if has_default: long_opts.append(l_opt + '=') else: long_opts.append(l_opt) syns[l_opt] = l_opt if s_opt is not None: short_opts = short_opts + s_opt if has_default: short_opts = short_opts + ':' syns[s_opt] = l_opt return long_opts, short_opts, docs, defaults, syns, dispatch def _get_flags(self): """Get the flag options.""" return self._parse_arguments(arg_type='optFlags', has_default=False) def _get_params(self): """Get the parameters options.""" return self._parse_arguments(arg_type='optParameters', has_default=True) ubuntuone-dev-tools-13.10/ubuntuone/devtools/testcases/0000755000202700020270000000000012225022242023550 5ustar dobeydobey00000000000000ubuntuone-dev-tools-13.10/ubuntuone/devtools/testcases/squid.py0000664000202700020270000000550312166632147025273 0ustar dobeydobey00000000000000# -*- coding: utf-8 -*- # # Copyright 2011-2012 Canonical Ltd. # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR # PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program. If not, see . # # In addition, as a special exception, the copyright holders give # permission to link the code of portions of this program with the # OpenSSL library under certain conditions as described in each # individual source file, and distribute linked combinations # including the two. # You must obey the GNU General Public License in all respects # for all of the code used other than OpenSSL. If you modify # file(s) with this exception, you may extend this exception to your # version of the file(s), but you are not obligated to do so. If you # do not wish to do so, delete this exception statement from your # version. If you delete this exception statement from all source # files in the program, then also delete it here. """Base squid tests cases and test utilities.""" from ubuntuone.devtools.testcases import BaseTestCase, skipIf from ubuntuone.devtools.services.squid import ( SquidRunner, SquidLaunchError, get_squid_executable, get_htpasswd_executable, retrieve_proxy_settings) # pylint: disable=C0103 squid, _ = get_squid_executable() htpasswd = get_htpasswd_executable() # pylint: enable=C0103 @skipIf(squid is None or htpasswd is None, 'The test requires squid and htpasswd.') class SquidTestCase(BaseTestCase): """Test that uses a proxy.""" def required_services(self): """Return the list of required services for DBusTestCase.""" services = super(SquidTestCase, self).required_services() services.extend([SquidRunner]) return services def get_nonauth_proxy_settings(self): """Return the settings of the noneauth proxy.""" settings = retrieve_proxy_settings() if settings is None: raise SquidLaunchError('Proxy is not running.') return dict(host='localhost', port=settings['noauth_port']) def get_auth_proxy_settings(self): """Return the settings of the auth proxy.""" settings = retrieve_proxy_settings() if settings is None: raise SquidLaunchError('Proxy is not running.') return dict(host='localhost', port=settings['auth_port'], username=settings['username'], password=settings['password']) ubuntuone-dev-tools-13.10/ubuntuone/devtools/testcases/dbus.py0000664000202700020270000001171612166632147025106 0ustar dobeydobey00000000000000# -*- coding: utf-8 -*- # # Copyright 2009-2012 Canonical Ltd. # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR # PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program. If not, see . # # In addition, as a special exception, the copyright holders give # permission to link the code of portions of this program with the # OpenSSL library under certain conditions as described in each # individual source file, and distribute linked combinations # including the two. # You must obey the GNU General Public License in all respects # for all of the code used other than OpenSSL. If you modify # file(s) with this exception, you may extend this exception to your # version of the file(s), but you are not obligated to do so. If you # do not wish to do so, delete this exception statement from your # version. If you delete this exception statement from all source # files in the program, then also delete it here. """Base dbus tests cases and test utilities.""" from __future__ import absolute_import, with_statement import os from twisted.internet import defer from ubuntuone.devtools.testcases import BaseTestCase, skipIf # DBusRunner for DBusTestCase using tests from ubuntuone.devtools.services.dbus import DBusRunner # pylint: disable=F0401,C0103,W0406,E0611 try: import dbus except ImportError as e: dbus = None try: import dbus.service as service except ImportError: service = None try: from dbus.mainloop.glib import DBusGMainLoop except ImportError: DBusGMainLoop = None # pylint: enable=F0401,C0103,W0406,E0611 class InvalidSessionBus(Exception): """Error when we are connected to the wrong session bus in tests.""" class FakeDBusInterface(object): """A fake DBusInterface...""" def shutdown(self, with_restart=False): """...that only knows how to go away""" @skipIf(dbus is None or service is None or DBusGMainLoop is None, "The test requires dbus.") class DBusTestCase(BaseTestCase): """Test the DBus event handling.""" def required_services(self): """Return the list of required services for DBusTestCase.""" services = super(DBusTestCase, self).required_services() services.extend([DBusRunner]) return services @defer.inlineCallbacks def setUp(self): """Setup the infrastructure fo the test (dbus service).""" # Class 'BaseTestCase' has no 'setUp' member # pylint: disable=E1101 # dbus modules will be imported by the decorator # pylint: disable=E0602 yield super(DBusTestCase, self).setUp() # We need to ensure DBUS_SESSION_BUS_ADDRESS is private here # pylint: disable=F0401,E0611 try: from urllib.parse import unquote except ImportError: from urllib import unquote # pylint: enable=F0401,E0611 bus_address = os.environ.get('DBUS_SESSION_BUS_ADDRESS', None) if os.path.dirname(unquote(bus_address.split(',')[0].split('=')[1])) \ != os.path.dirname(os.getcwd()): raise InvalidSessionBus('DBUS_SESSION_BUS_ADDRESS is wrong.') # Set up the main loop and bus connection self.loop = DBusGMainLoop(set_as_default=True) # NOTE: The address_or_type value must remain explicitly as # str instead of anything from ubuntuone.devtools.compat. dbus # expects this to be str regardless of version. self.bus = dbus.bus.BusConnection(address_or_type=str(bus_address), mainloop=self.loop) # Monkeypatch the dbus.SessionBus/SystemBus methods, to ensure we # always point at our own private bus instance. self.patch(dbus, 'SessionBus', lambda: self.bus) self.patch(dbus, 'SystemBus', lambda: self.bus) # Check that we are on the correct bus for real # Disable this for now, because our tests are extremely broken :( # bus_names = self.bus.list_names() # if len(bus_names) > 2: # raise InvalidSessionBus('Too many bus connections: %s (%r)' % # (len(bus_names), bus_names)) # monkeypatch busName.__del__ to avoid errors on gc # we take care of releasing the name in shutdown service.BusName.__del__ = lambda _: None yield self.bus.set_exit_on_disconnect(False) self.signal_receivers = set() @defer.inlineCallbacks def tearDown(self): """Cleanup the test.""" yield self.bus.flush() yield self.bus.close() yield super(DBusTestCase, self).tearDown() ubuntuone-dev-tools-13.10/ubuntuone/devtools/testcases/txsocketserver.py0000664000202700020270000003122412166632147027240 0ustar dobeydobey00000000000000# -*- coding: utf-8 -*- # Copyright 2012 Canonical Ltd. # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR # PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program. If not, see . # # In addition, as a special exception, the copyright holders give # permission to link the code of portions of this program with the # OpenSSL library under certain conditions as described in each # individual source file, and distribute linked combinations # including the two. # You must obey the GNU General Public License in all respects # for all of the code used other than OpenSSL. If you modify # file(s) with this exception, you may extend this exception to your # version of the file(s), but you are not obligated to do so. If you # do not wish to do so, delete this exception statement from your # version. If you delete this exception statement from all source # files in the program, then also delete it here. """Base test case for twisted servers.""" import os import shutil import tempfile from twisted.internet import defer, endpoints, protocol from twisted.spread import pb from ubuntuone.devtools.testcases import BaseTestCase # no init method + twisted common warnings # pylint: disable=W0232, C0103, E1101 def server_protocol_factory(cls): """Factory to create tidy protocols.""" if cls is None: cls = protocol.Protocol class ServerTidyProtocol(cls): """A tidy protocol.""" def connectionLost(self, *args): """Lost the connection.""" cls.connectionLost(self, *args) # lets tell everyone # pylint: disable=W0212 if (self.factory._disconnecting and self.factory.testserver_on_connection_lost is not None and not self.factory.testserver_on_connection_lost.called): self.factory.testserver_on_connection_lost.callback(self) # pylint: enable=W0212 return ServerTidyProtocol def server_factory_factory(cls): """Factory that creates special types of factories for tests.""" if cls is None: cls = protocol.ServerFactory class TidyServerFactory(cls): """A tidy factory.""" testserver_on_connection_lost = None def buildProtocol(self, addr): prot = cls.buildProtocol(self, addr) self.testserver_on_connection_lost = defer.Deferred() return prot return TidyServerFactory def client_protocol_factory(cls): """Factory to create tidy protocols.""" if cls is None: cls = protocol.Protocol class ClientTidyProtocol(cls): """A tidy protocol.""" def connectionLost(self, *a): """Connection list.""" cls.connectionLost(self, *a) # pylint: disable=W0212 if (self.factory._disconnecting and self.factory.testserver_on_connection_lost is not None and not self.factory.testserver_on_connection_lost.called): self.factory.testserver_on_connection_lost.callback(self) # pylint: enable=W0212 return ClientTidyProtocol class TidySocketServer(object): """Ensure that twisted servers are correctly managed in tests. Closing a twisted server is a complicated matter. In order to do so you have to ensure that three different deferreds are fired: 1. The server must stop listening. 2. The client connection must disconnect. 3. The server connection must disconnect. This class allows to create a server and a client that will ensure that the reactor is left clean by following the pattern described at http://mumak.net/stuff/twisted-disconnect.html """ def __init__(self): """Create a new instance.""" self.listener = None self.server_factory = None self.connector = None self.client_factory = None def get_server_endpoint(self): """Return the server endpoint description.""" raise NotImplementedError('To be implemented by child classes.') def get_client_endpoint(self): """Return the client endpoint description.""" raise NotImplementedError('To be implemented by child classes.') @defer.inlineCallbacks def listen_server(self, server_class, *args, **kwargs): """Start a server in a random port.""" from twisted.internet import reactor tidy_class = server_factory_factory(server_class) self.server_factory = tidy_class(*args, **kwargs) self.server_factory._disconnecting = False self.server_factory.protocol = server_protocol_factory( self.server_factory.protocol) endpoint = endpoints.serverFromString(reactor, self.get_server_endpoint()) self.listener = yield endpoint.listen(self.server_factory) defer.returnValue(self.server_factory) @defer.inlineCallbacks def connect_client(self, client_class, *args, **kwargs): """Conect a client to a given server.""" from twisted.internet import reactor if self.server_factory is None: raise ValueError('Server Factory was not provided.') if self.listener is None: raise ValueError('%s has not started listening.', self.server_factory) self.client_factory = client_class(*args, **kwargs) self.client_factory._disconnecting = False self.client_factory.protocol = client_protocol_factory( self.client_factory.protocol) self.client_factory.testserver_on_connection_lost = defer.Deferred() endpoint = endpoints.clientFromString(reactor, self.get_client_endpoint()) self.connector = yield endpoint.connect(self.client_factory) defer.returnValue(self.client_factory) def clean_up(self): """Action to be performed for clean up.""" if self.server_factory is None or self.listener is None: # nothing to clean return defer.succeed(None) if self.listener and self.connector: # clean client and server self.server_factory._disconnecting = True self.client_factory._disconnecting = True d = defer.maybeDeferred(self.listener.stopListening) self.connector.transport.loseConnection() if self.server_factory.testserver_on_connection_lost: return defer.gatherResults( [d, self.client_factory.testserver_on_connection_lost, self.server_factory.testserver_on_connection_lost]) else: return defer.gatherResults( [d, self.client_factory.testserver_on_connection_lost]) if self.listener: # just clean the server since there is no client # pylint: disable=W0201 self.server_factory._disconnecting = True return defer.maybeDeferred(self.listener.stopListening) # pylint: enable=W0201 class TidyTCPServer(TidySocketServer): """A tidy tcp domain sockets server.""" client_endpoint_pattern = 'tcp:host=127.0.0.1:port=%s' server_endpoint_pattern = 'tcp:0:interface=127.0.0.1' def get_server_endpoint(self): """Return the server endpoint description.""" return self.server_endpoint_pattern def get_client_endpoint(self): """Return the client endpoint description.""" if self.server_factory is None: raise ValueError('Server Factory was not provided.') if self.listener is None: raise ValueError('%s has not started listening.', self.server_factory) return self.client_endpoint_pattern % self.listener.getHost().port class TidyUnixServer(TidySocketServer): """A tidy unix domain sockets server.""" client_endpoint_pattern = 'unix:path=%s' server_endpoint_pattern = 'unix:%s' def __init__(self): """Create a new instance.""" super(TidyUnixServer, self).__init__() self.temp_dir = tempfile.mkdtemp() self.path = os.path.join(self.temp_dir, 'tidy_unix_server') def get_server_endpoint(self): """Return the server endpoint description.""" return self.server_endpoint_pattern % self.path def get_client_endpoint(self): """Return the client endpoint description.""" return self.client_endpoint_pattern % self.path def clean_up(self): """Action to be performed for clean up.""" result = super(TidyUnixServer, self).clean_up() # remove the dir once we are disconnected result.addCallback(lambda _: shutil.rmtree(self.temp_dir)) return result class ServerTestCase(BaseTestCase): """Base test case for tidy servers.""" @defer.inlineCallbacks def setUp(self): """Set the diff tests.""" yield super(ServerTestCase, self).setUp() try: self.server_runner = self.get_server() except NotImplementedError: self.server_runner = None self.server_factory = None self.client_factory = None self.server_disconnected = None self.client_connected = None self.client_disconnected = None self.listener = None self.connector = None self.addCleanup(self.tear_down_server_client) def get_server(self): """Return the server to be used to run the tests.""" raise NotImplementedError('To be implemented by child classes.') @defer.inlineCallbacks def listen_server(self, server_class, *args, **kwargs): """Listen a server. The method takes the server class and the arguments that should be passed to the server constructor. """ self.server_factory = yield self.server_runner.listen_server( server_class, *args, **kwargs) self.server_disconnected = \ self.server_factory.testserver_on_connection_lost self.listener = self.server_runner.listener @defer.inlineCallbacks def connect_client(self, client_class, *args, **kwargs): """Connect the client. The method takes the client factory class and the arguments that should be passed to the client constructor. """ self.client_factory = yield self.server_runner.connect_client( client_class, *args, **kwargs) self.client_disconnected = \ self.client_factory.testserver_on_connection_lost self.connector = self.server_runner.connector def tear_down_server_client(self): """Clean the server and client.""" if self.server_runner: return self.server_runner.clean_up() class TCPServerTestCase(ServerTestCase): """Test that uses a single twisted server.""" def get_server(self): """Return the server to be used to run the tests.""" return TidyTCPServer() class UnixServerTestCase(ServerTestCase): """Test that uses a single twisted server.""" def get_server(self): """Return the server to be used to run the tests.""" return TidyUnixServer() class PbServerTestCase(ServerTestCase): """Test a pb server.""" def get_server(self): """Return the server to be used to run the tests.""" raise NotImplementedError('To be implemented by child classes.') @defer.inlineCallbacks def listen_server(self, *args, **kwargs): """Listen a pb server.""" yield super(PbServerTestCase, self).listen_server(pb.PBServerFactory, *args, **kwargs) @defer.inlineCallbacks def connect_client(self, *args, **kwargs): """Connect a pb client.""" yield super(PbServerTestCase, self).connect_client(pb.PBClientFactory, *args, **kwargs) class TCPPbServerTestCase(PbServerTestCase): """Test a pb server over TCP.""" def get_server(self): """Return the server to be used to run the tests.""" return TidyTCPServer() class UnixPbServerTestCase(PbServerTestCase): """Test a pb server over Unix domain sockets.""" def get_server(self): """Return the server to be used to run the tests.""" return TidyUnixServer() ubuntuone-dev-tools-13.10/ubuntuone/devtools/testcases/__init__.py0000664000202700020270000001435712166632147025714 0ustar dobeydobey00000000000000# -*- coding: utf-8 -*- # # Copyright 2009-2012 Canonical Ltd. # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR # PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program. If not, see . # # In addition, as a special exception, the copyright holders give # permission to link the code of portions of this program with the # OpenSSL library under certain conditions as described in each # individual source file, and distribute linked combinations # including the two. # You must obey the GNU General Public License in all respects # for all of the code used other than OpenSSL. If you modify # file(s) with this exception, you may extend this exception to your # version of the file(s), but you are not obligated to do so. If you # do not wish to do so, delete this exception statement from your # version. If you delete this exception statement from all source # files in the program, then also delete it here. """Base tests cases and test utilities.""" from __future__ import with_statement import contextlib import os import shutil import sys from functools import wraps from twisted.trial.unittest import TestCase, SkipTest @contextlib.contextmanager def environ(env_var, new_value): """context manager to replace/add an environ value""" old_value = os.environ.get(env_var, None) os.environ[env_var] = new_value yield if old_value is None: os.environ.pop(env_var) else: os.environ[env_var] = old_value def _id(obj): """Return the obj calling the funct.""" return obj # pylint: disable=C0103 def skipTest(reason): """Unconditionally skip a test.""" def decorator(test_item): """Decorate the test so that it is skipped.""" if not (isinstance(test_item, type) and issubclass(test_item, TestCase)): @wraps(test_item) def skip_wrapper(*args, **kwargs): """Skip a test method raising an exception.""" raise SkipTest(reason) test_item = skip_wrapper # tell twisted.trial.unittest to skip the test, pylint will complain # since it thinks we are redefining a name out of the scope # pylint: disable=W0621,W0612 test_item.skip = reason # pylint: enable=W0621,W0612 # because the item was skipped, we will make sure that no # services are started for it if hasattr(test_item, "required_services"): # pylint: disable=W0612 test_item.required_services = lambda *args, **kwargs: [] # pylint: enable=W0612 return test_item return decorator def skipIf(condition, reason): """Skip a test if the condition is true.""" if condition: return skipTest(reason) return _id def skipIfOS(current_os, reason): """Skip test for a particular os or lists of them.""" if os: if sys.platform in current_os or sys.platform == current_os: return skipTest(reason) return _id return _id def skipIfNotOS(current_os, reason): """Skip test we are not in a particular os.""" if os: if sys.platform not in current_os or \ sys.platform != current_os: return skipTest(reason) return _id return _id def skipIfJenkins(current_os, reason): """Skip test for a particular os or lists of them when running on Jenkins.""" if os.getenv("JENKINS", False) and (sys.platform in current_os or sys.platform == current_os): return skipTest(reason) return _id # pylint: enable=C0103 class BaseTestCase(TestCase): """Base TestCase with helper methods to handle temp dir. This class provides: mktemp(name): helper to create temporary dirs rmtree(path): support read-only shares makedirs(path): support read-only shares """ def required_services(self): """Return the list of required services for DBusTestCase.""" return [] def mktemp(self, name='temp'): """Customized mktemp that accepts an optional name argument.""" tempdir = os.path.join(self.tmpdir, name) if os.path.exists(tempdir): self.rmtree(tempdir) self.makedirs(tempdir) return tempdir @property def tmpdir(self): """Default tmpdir: module/class/test_method.""" # check if we already generated the root path root_dir = getattr(self, '__root', None) if root_dir: return root_dir max_filename = 32 # some platforms limit lengths of filenames base = os.path.join(self.__class__.__module__[:max_filename], self.__class__.__name__[:max_filename], self._testMethodName[:max_filename]) # use _trial_temp dir, it should be os.gwtcwd() # define the root temp dir of the testcase, pylint: disable=W0201 self.__root = os.path.join(os.getcwd(), base) return self.__root def rmtree(self, path): """Custom rmtree that handle ro parent(s) and childs.""" if not os.path.exists(path): return # change perms to rw, so we can delete the temp dir if path != getattr(self, '__root', None): os.chmod(os.path.dirname(path), 0o755) if not os.access(path, os.W_OK): os.chmod(path, 0o755) # pylint: disable=W0612 for dirpath, dirs, files in os.walk(path): for dirname in dirs: if not os.access(os.path.join(dirpath, dirname), os.W_OK): os.chmod(os.path.join(dirpath, dirname), 0o777) shutil.rmtree(path) def makedirs(self, path): """Custom makedirs that handle ro parent.""" parent = os.path.dirname(path) if os.path.exists(parent): os.chmod(parent, 0o755) os.makedirs(path) ubuntuone-dev-tools-13.10/ubuntuone/devtools/runners/0000755000202700020270000000000012225022242023246 5ustar dobeydobey00000000000000ubuntuone-dev-tools-13.10/ubuntuone/devtools/runners/txrunner.py0000664000202700020270000001131312166632147025525 0ustar dobeydobey00000000000000# Copyright 2009-2012 Canonical Ltd. # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR # PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program. If not, see . # # In addition, as a special exception, the copyright holders give # permission to link the code of portions of this program with the # OpenSSL library under certain conditions as described in each # individual source file, and distribute linked combinations # including the two. # You must obey the GNU General Public License in all respects # for all of the code used other than OpenSSL. If you modify # file(s) with this exception, you may extend this exception to your # version of the file(s), but you are not obligated to do so. If you # do not wish to do so, delete this exception statement from your # version. If you delete this exception statement from all source # files in the program, then also delete it here. """The twisted test runner and options.""" from __future__ import print_function, unicode_literals import sys from twisted.scripts import trial from twisted.trial.runner import TrialRunner from ubuntuone.devtools.errors import TestError from ubuntuone.devtools.runners import BaseTestOptions, BaseTestRunner __all__ = ['TestRunner', 'TestOptions'] class TestRunner(BaseTestRunner, TrialRunner): """The twisted test runner implementation.""" def __init__(self, options=None): # Handle running trial in debug or dry-run mode self.config = options try: reactor_name = ('ubuntuone.devtools.reactors.%s' % self.config['reactor']) reactor = __import__(reactor_name, None, None, ['']) except ImportError: raise TestError('The specified reactor is not supported.') else: try: reactor.install(options=self.config) except ImportError: raise TestError( 'The Python package providing the requested reactor is ' 'not installed. You can find it here: %s' % reactor.REACTOR_URL) mode = None if self.config['debug']: mode = TrialRunner.DEBUG if self.config['dry-run']: mode = TrialRunner.DRY_RUN # Hook up to the parent test runner super(TestRunner, self).__init__( options=options, reporterFactory=self.config['reporter'], mode=mode, profile=self.config['profile'], logfile=self.config['logfile'], tracebackFormat=self.config['tbformat'], realTimeErrors=self.config['rterrors'], uncleanWarnings=self.config['unclean-warnings'], forceGarbageCollection=self.config['force-gc']) # Named for trial compatibility. # pylint: disable=C0103 self.workingDirectory = self.working_dir # pylint: enable=C0103 def run_tests(self, suite): """Run the twisted test suite.""" if self.config['until-failure']: result = self.runUntilFailure(suite) else: result = self.run(suite) return result.wasSuccessful() def _get_default_reactor(): """Return the platform-dependent default reactor to use.""" default_reactor = 'gi' if sys.platform in ['darwin', 'win32']: default_reactor = 'twisted' return default_reactor class TestOptions(trial.Options, BaseTestOptions): """Class for twisted options handling.""" optFlags = [["help-reactors", None], ] optParameters = [["reactor", "r", _get_default_reactor()], ] def __init__(self, *args, **kwargs): super(TestOptions, self).__init__(*args, **kwargs) self['rterrors'] = True def opt_coverage(self, option): """Handle special flags.""" self['coverage'] = True opt_c = opt_coverage def opt_help_reactors(self): """Help on available reactors for use with tests""" synopsis = ('') print(synopsis) print('Need to get list of reactors and print them here.\n') sys.exit(0) def opt_reactor(self, option): """Which reactor to use (see --help-reactors for a list of possibilities) """ self['reactor'] = option opt_r = opt_reactor ubuntuone-dev-tools-13.10/ubuntuone/devtools/runners/__init__.py0000664000202700020270000002602312166632221025374 0ustar dobeydobey00000000000000# Copyright 2009-2012 Canonical Ltd. # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR # PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program. If not, see . # # In addition, as a special exception, the copyright holders give # permission to link the code of portions of this program with the # OpenSSL library under certain conditions as described in each # individual source file, and distribute linked combinations # including the two. # You must obey the GNU General Public License in all respects # for all of the code used other than OpenSSL. If you modify # file(s) with this exception, you may extend this exception to your # version of the file(s), but you are not obligated to do so. If you # do not wish to do so, delete this exception statement from your # version. If you delete this exception statement from all source # files in the program, then also delete it here. """The base test runner object.""" from __future__ import print_function, unicode_literals import coverage import gc import inspect import os import re import sys import unittest from ubuntuone.devtools.errors import TestError, UsageError from ubuntuone.devtools.testing.txcheck import TXCheckSuite from ubuntuone.devtools.utils import OptionParser from ubuntuone.devtools.compat import text_type __all__ = ['BaseTestOptions', 'BaseTestRunner', 'main'] def _is_in_ignored_path(testcase, paths): """Return if the testcase is in one of the ignored paths.""" for ignored_path in paths: if testcase.startswith(ignored_path): return True return False class BaseTestRunner(object): """The base test runner type. Does not actually run tests.""" def __init__(self, options=None, *args, **kwargs): super(BaseTestRunner, self).__init__(*args, **kwargs) # set $HOME to the _trial_temp dir, to avoid breaking user files trial_temp_dir = os.environ.get('TRIAL_TEMP_DIR', os.getcwd()) homedir = os.path.join(trial_temp_dir, options['temp-directory']) os.environ['HOME'] = homedir # setup $XDG_*_HOME variables and create the directories xdg_cache = os.path.join(homedir, 'xdg_cache') xdg_config = os.path.join(homedir, 'xdg_config') xdg_data = os.path.join(homedir, 'xdg_data') os.environ['XDG_CACHE_HOME'] = xdg_cache os.environ['XDG_CONFIG_HOME'] = xdg_config os.environ['XDG_DATA_HOME'] = xdg_data if not os.path.exists(xdg_cache): os.makedirs(xdg_cache) if not os.path.exists(xdg_config): os.makedirs(xdg_config) if not os.path.exists(xdg_data): os.makedirs(xdg_data) # setup the ROOTDIR env var os.environ['ROOTDIR'] = os.getcwd() # Need an attribute for tempdir so we can use it later self.tempdir = homedir self.working_dir = os.path.join(self.tempdir, 'trial') self.source_files = [] self.required_services = [] def _load_unittest(self, relpath): """Load unit tests from a Python module with the given 'relpath'.""" assert relpath.endswith(".py"), ( "%s does not appear to be a Python module" % relpath) if not os.path.basename(relpath).startswith('test_'): return modpath = relpath.replace(os.path.sep, ".")[:-3] module = __import__(modpath, None, None, [""]) # If the module specifies required_services, make sure we get them members = [x[1] for x in inspect.getmembers(module, inspect.isclass)] for member_type in members: if hasattr(member_type, 'required_services'): member = member_type() for service in member.required_services(): if service not in self.required_services: self.required_services.append(service) del member gc.collect() # If the module has a 'suite' or 'test_suite' function, use that # to load the tests. if hasattr(module, "suite"): return module.suite() elif hasattr(module, "test_suite"): return module.test_suite() else: return unittest.defaultTestLoader.loadTestsFromModule(module) def _collect_tests(self, path, test_pattern, ignored_modules, ignored_paths): """Return the set of unittests.""" suite = TXCheckSuite() if test_pattern: pattern = re.compile('.*%s.*' % test_pattern) else: pattern = None # Disable this lint warning as we need to access _tests in the # test suites, to collect the tests # pylint: disable=W0212 if path: try: module_suite = self._load_unittest(path) if pattern: for inner_suite in module_suite._tests: for test in inner_suite._tests: if pattern.match(test.id()): suite.addTest(test) else: suite.addTests(module_suite) return suite except AssertionError: pass else: raise TestError('Path should be defined.') # We don't use the dirs variable, so ignore the warning # pylint: disable=W0612 for root, dirs, files in os.walk(path): for test in files: filepath = os.path.join(root, test) if test.endswith(".py") and test not in ignored_modules and \ not _is_in_ignored_path(filepath, ignored_paths): self.source_files.append(filepath) if test.startswith("test_"): module_suite = self._load_unittest(filepath) if pattern: for inner_suite in module_suite._tests: for test in inner_suite._tests: if pattern.match(test.id()): suite.addTest(test) else: suite.addTests(module_suite) return suite def get_suite(self, config): """Get the test suite to use.""" suite = unittest.TestSuite() for path in config['tests']: suite.addTest(self._collect_tests(path, config['test'], config['ignore-modules'], config['ignore-paths'])) if config['loop']: old_suite = suite suite = unittest.TestSuite() for _ in range(config['loop']): suite.addTest(old_suite) return suite def run_tests(self, suite): """Run the test suite.""" return False class BaseTestOptions(OptionParser): """Base options for our test runner.""" optFlags = [['coverage', 'c', 'Generate a coverage report for the tests.'], ['gui', None, 'Use the GUI mode of some runners.'], ['help', 'h', ''], ['help-runners', None, 'List information about test runners.'], ] optParameters = [['test', 't', None, None], ['loop', None, 1, None], ['ignore-modules', 'i', '', None], ['ignore-paths', 'p', '', None], ['runner', None, 'txrunner', None], ['temp-directory', None, b'_trial_temp', None], ] def __init__(self, *args, **kwargs): super(BaseTestOptions, self).__init__(*args, **kwargs) def opt_help_runners(self): """List the runners which are supported.""" sys.exit(0) def opt_ignore_modules(self, option): """Comma-separate list of test modules to ignore, e.g: test_gtk.py, test_account.py """ self['ignore-modules'] = list(map(text_type.strip, option.split(','))) def opt_ignore_paths(self, option): """Comma-separated list of relative paths to ignore, e.g: tests/platform/windows, tests/platform/macosx """ self['ignore-paths'] = list(map(text_type.strip, option.split(','))) def opt_loop(self, option): """Loop tests the specified number of times.""" try: self['loop'] = int(option) except ValueError: raise UsageError('A positive integer value must be specified.') def opt_temp_directory(self, option): """Path to use as a working directory for tests. [default: _trial_temp] """ self['temp-directory'] = option def opt_test(self, option): """Run specific tests, e.g: className.methodName""" self['test'] = option # We use some camelcase names for trial compatibility here. def parseArgs(self, *args): """Handle the extra arguments.""" if isinstance(self.tests, set): self['tests'].update(args) elif isinstance(self.tests, list): self['tests'].extend(args) def _get_runner_options(runner_name): """Return the test runner module, and its options object.""" module_name = 'ubuntuone.devtools.runners.%s' % runner_name runner = __import__(module_name, None, None, ['']) options = None if getattr(runner, 'TestOptions', None) is not None: options = runner.TestOptions() if options is None: options = BaseTestOptions() return (runner, options) def main(): """Do the deed.""" if len(sys.argv) == 1: sys.argv.append('--help') try: pos = sys.argv.index('--runner') runner_name = sys.argv.pop(pos + 1) sys.argv.pop(pos) except ValueError: runner_name = 'txrunner' finally: runner, options = _get_runner_options(runner_name) options.parseOptions() test_runner = runner.TestRunner(options=options) suite = test_runner.get_suite(options) if options['coverage']: coverage.erase() coverage.start() running_services = [] succeeded = False try: # Start any required services for service_obj in test_runner.required_services: service = service_obj() service.start_service(tempdir=test_runner.tempdir) running_services.append(service) succeeded = test_runner.run_tests(suite) finally: # Stop all the running services for service in running_services: service.stop_service() if options['coverage']: coverage.stop() coverage.report(test_runner.source_files, ignore_errors=True, show_missing=False) sys.exit(not succeeded) ubuntuone-dev-tools-13.10/ubuntuone/devtools/handlers.py0000664000202700020270000000721512166632147023752 0ustar dobeydobey00000000000000# -*- coding: utf-8 -*- # Author: Guillermo Gonzalez # Author: Facundo Batista # # Copyright 2009-2012 Canonical Ltd. # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR # PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program. If not, see . # # In addition, as a special exception, the copyright holders give # permission to link the code of portions of this program with the # OpenSSL library under certain conditions as described in each # individual source file, and distribute linked combinations # including the two. # You must obey the GNU General Public License in all respects # for all of the code used other than OpenSSL. If you modify # file(s) with this exception, you may extend this exception to your # version of the file(s), but you are not obligated to do so. If you # do not wish to do so, delete this exception statement from your # version. If you delete this exception statement from all source # files in the program, then also delete it here. """Set of helpers handlers.""" from __future__ import print_function import logging class MementoHandler(logging.Handler): """ A handler class which store logging records in a list """ def __init__(self, *args, **kwargs): """ Create the instance, and add a records attribute. """ logging.Handler.__init__(self, *args, **kwargs) self.records = [] self.debug = False def emit(self, record): """ Just add the record to self.records. """ self.format(record) self.records.append(record) def dump_contents(self, msgs): """Dumps the contents of the MementoHandler.""" if self.debug: print("Expecting:") for msg in msgs: print("\t", msg) print("MementoHandler contents:") for rec in self.records: print("\t", rec.exc_info) print("\t", logging.getLevelName(rec.levelno)) print("\t\t", rec.message) print("\t\t", rec.exc_text) def check(self, level, *msgs): """Verifies that the msgs are logged in the specified level""" for rec in self.records: if rec.levelno == level and all(m in rec.message for m in msgs): return rec self.dump_contents(msgs) return False def check_debug(self, *msgs): """Shortcut for checking in DEBUG.""" return self.check(logging.DEBUG, *msgs) def check_info(self, *msgs): """Shortcut for checking in INFO.""" return self.check(logging.INFO, *msgs) def check_warning(self, *msgs): """Shortcut for checking in WARNING.""" return self.check(logging.WARNING, *msgs) def check_error(self, *msgs): """Shortcut for checking in ERROR.""" return self.check(logging.ERROR, *msgs) def check_exception(self, exception_info, *msgs): """Shortcut for checking exceptions.""" for rec in self.records: if rec.levelno == logging.ERROR and \ all(m in rec.exc_text + rec.message for m in msgs) and \ exception_info in rec.exc_info: return True return False ubuntuone-dev-tools-13.10/ubuntuone/devtools/compat.py0000664000202700020270000000354112166632147023433 0ustar dobeydobey00000000000000# -*- coding: utf-8 -*- # # Copyright 2012 Canonical Ltd. # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR # PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program. If not, see . # # In addition, as a special exception, the copyright holders give # permission to link the code of portions of this program with the # OpenSSL library under certain conditions as described in each # individual source file, and distribute linked combinations # including the two. # You must obey the GNU General Public License in all respects # for all of the code used other than OpenSSL. If you modify # file(s) with this exception, you may extend this exception to your # version of the file(s), but you are not obligated to do so. If you # do not wish to do so, delete this exception statement from your # version. If you delete this exception statement from all source # files in the program, then also delete it here. """Python 2 and 3 compatibility.""" from __future__ import unicode_literals # The following approach was outlined in Lennart Regebro's # "Porting to Python 3" book. # http://python3porting.com/noconv.html#more-bytes-strings-and-unicode import sys # Disable redefined builtin, invalid name warning # pylint: disable=W0622,C0103 if sys.version_info < (3,): text_type = unicode binary_type = str basestring = basestring else: text_type = str binary_type = bytes basestring = str ubuntuone-dev-tools-13.10/LICENSE.OpenSSL0000664000202700020270000001547312166632147020211 0ustar dobeydobey00000000000000Certain source files in this program permit linking with the OpenSSL library (http://www.openssl.org), which otherwise wouldn't be allowed under the (A)GPL. For purposes of identifying OpenSSL, most source files giving this permission limit it to versions of OpenSSL having a license identical to that listed in this file (LICENSE.OpenSSL). It is not necessary for the copyright years to match between this file and the OpenSSL version in question. However, note that because this file is an extension of the license statements of these source files, this file may not be changed except with permission from all copyright holders of source files in this program which reference this file. LICENSE ISSUES ============== The OpenSSL toolkit stays under a dual license, i.e. both the conditions of the OpenSSL License and the original SSLeay license apply to the toolkit. See below for the actual license texts. Actually both licenses are BSD-style Open Source licenses. In case of any license issues related to OpenSSL please contact openssl-core@openssl.org. OpenSSL License --------------- /* ==================================================================== * Copyright (c) 1998-2004 The OpenSSL Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. 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. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * openssl-core@openssl.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.openssl.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED 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 OpenSSL PROJECT OR * ITS 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. * ==================================================================== * * This product includes cryptographic software written by Eric Young * (eay@cryptsoft.com). This product includes software written by Tim * Hudson (tjh@cryptsoft.com). * */ Original SSLeay License ----------------------- /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * * This package is an SSL implementation written * by Eric Young (eay@cryptsoft.com). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson (tjh@cryptsoft.com). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes cryptographic software written by * Eric Young (eay@cryptsoft.com)" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``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 AUTHOR 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. * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ ubuntuone-dev-tools-13.10/data/0000755000202700020270000000000012225022242016600 5ustar dobeydobey00000000000000ubuntuone-dev-tools-13.10/data/squid.conf.in0000664000202700020270000000677712216607771021244 0ustar dobeydobey00000000000000auth_param basic casesensitive on # Use a default auth using ncsa and the passed generated file. auth_param basic program ${auth_process} ${auth_file} #Recommended minimum configuration: acl localhost src 127.0.0.1/32 acl to_localhost dst 127.0.0.0/32 # # Example rule allowing access from your local networks. # Adapt to list your (internal) IP networks from where browsing # should be allowed acl all src all acl localnet src 10.0.0.0/8 # RFC1918 possible internal network acl localnet src 172.16.0.0/12 # RFC1918 possible internal network acl localnet src 192.168.0.0/16 # RFC1918 possible internal network # acl SSL_ports port 443 # https acl SSL_ports port 563 # snews acl SSL_ports port 873 # rsync acl Safe_ports port 80 # http acl Safe_ports port 21 # ftp acl Safe_ports port 443 # https acl Safe_ports port 70 # gopher acl Safe_ports port 210 # wais acl Safe_ports port 1025-65535 # unregistered ports acl Safe_ports port 280 # http-mgmt acl Safe_ports port 488 # gss-http acl Safe_ports port 591 # filemaker acl Safe_ports port 777 # multiling http acl Safe_ports port 631 # cups acl Safe_ports port 873 # rsync acl Safe_ports port 901 # SWAT acl purge method PURGE acl CONNECT method CONNECT # make an acl for users that have auth acl password proxy_auth REQUIRED myportname ${auth_port_number} acl auth_port_connected myportname ${auth_port_number} acl nonauth_port_connected myportname ${noauth_port_number} # Settings used for the tests: # Allow users connected to the nonauth port # Allow users authenticated AND connected to the auth port http_access allow nonauth_port_connected http_access allow password #Recommended minimum configuration: # # Only allow purge requests from localhost http_access allow purge localhost http_access deny purge # Deny requests to unknown ports http_access deny !Safe_ports # Deny CONNECT to other than SSL ports http_access deny CONNECT !SSL_ports # Example rule allowing access from your local networks. # Adapt localnet in the ACL section to list your (internal) IP networks # from where browsing should be allowed #http_access allow localnet http_access allow localhost # And finally deny all other access to this proxy http_access deny all icp_access allow localnet icp_access deny all # Squid normally listens to port 3128 but we are going to listento two # different ports, one for auth one for nonauth. http_port ${noauth_port_number} http_port ${auth_port_number} #We recommend you to use at least the following line. hierarchy_stoplist cgi-bin ? # Default cache settings. cache_dir ufs ${spool_temp} 1000 16 256 # access log settings access_log ${squid_temp}access.log squid # cache log settings cache_log ${squid_temp}cache.log # cache store log settings cache_store_log ${squid_temp}store.log # mime table conf # mime_table /usr/share/squid/mime.conf #Default pid file name pid_filename ${squid_temp}squid.pid # debug options (Full debugging) debug_options ALL,1 #Default netdb_filename #Suggested default: refresh_pattern ^ftp: 1440 20% 10080 refresh_pattern ^gopher: 1440 0% 1440 refresh_pattern -i (/cgi-bin/|\?) 0 0% 0 refresh_pattern (Release|Packages(.gz)*)$ 0 20% 2880 # example line deb packages refresh_pattern . 0 20% 4320 # Don't upgrade ShoutCast responses to HTTP acl shoutcast rep_header X-HTTP09-First-Line ^ICY.[0-9] # Apache mod_gzip and mod_deflate known to be broken so don't trust # Apache to signal ETag correctly on such responses acl apache rep_header Server ^Apache hosts_file /etc/hosts # Leave coredumps in the first cache dir coredump_dir ${spool_temp}squid ubuntuone-dev-tools-13.10/data/dbus-session.conf.in0000664000202700020270000000537212166632147022522 0ustar dobeydobey00000000000000 session @ADDRESS@ dbus-session /etc/dbus-1/session.d 60000 session-local.conf contexts/dbus_contexts 1000000000 1000000000 1000000000 120000 240000 100000 10000 100000 10000 50000 50000 50000 300000 ubuntuone-dev-tools-13.10/LICENSE0000664000202700020270000000261612166632147016722 0ustar dobeydobey00000000000000# This is the Ubuntu One development tools package. # # Copyright (C) 2009-2012 Canonical Ltd. # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR # PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program. If not, see . # # In addition, as a special exception, the copyright holders give # permission to link the code of portions of this program with the # OpenSSL library under certain conditions as described in each # individual source file, and distribute linked combinations # including the two. # You must obey the GNU General Public License in all respects # for all of the code used other than OpenSSL. If you modify # file(s) with this exception, you may extend this exception to your # version of the file(s), but you are not obligated to do so. If you # do not wish to do so, delete this exception statement from your # version. If you delete this exception statement from all source # files in the program, then also delete it here. ubuntuone-dev-tools-13.10/PKG-INFO0000644000202700020270000000040512225022242016763 0ustar dobeydobey00000000000000Metadata-Version: 1.0 Name: ubuntuone-dev-tools Version: 13.10 Summary: Ubuntu One development tools and utilities Home-page: http://launchpad.net/ubuntuone-dev-tools Author: UNKNOWN Author-email: UNKNOWN License: UNKNOWN Description: UNKNOWN Platform: UNKNOWN ubuntuone-dev-tools-13.10/run-tests0000775000202700020270000000173312166632147017606 0ustar dobeydobey00000000000000#!/bin/bash # # Copyright 2010-2013 Canonical Ltd. # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR # PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program. If not, see . set -e PYTHON="python" if [ "$1" = "-3" ] then PYTHON="python3" fi $PYTHON bin/u1trial -i "test_squid_windows.py" -c ubuntuone $PYTHON bin/u1trial --reactor=twisted -i "test_squid_windows.py" ubuntuone echo "Running style checks..." $PYTHON bin/u1lint pep8 --repeat . bin/* --exclude=*.bat,.pc rm -rf _trial_temp rm -rf .coverage ubuntuone-dev-tools-13.10/man/0000755000202700020270000000000012225022242016442 5ustar dobeydobey00000000000000ubuntuone-dev-tools-13.10/man/u1lint.10000664000202700020270000000056712166632147017771 0ustar dobeydobey00000000000000.TH U1LINT 1 .SH NAME u1lint \- Python lint tool wrapper and output formatter .SH SYNOPSIS .B u1lint .SH DESCRIPTION u1lint is a Python lint tool wrapper. It parses the output from supported Python lint tools, and reformats, grouping warnings by affected files, in a simple list output. .SH AUTHOR This manual page was written by Rodney Dawes . ubuntuone-dev-tools-13.10/man/u1trial.10000664000202700020270000000243412166632147020131 0ustar dobeydobey00000000000000.TH U1TRIAL 1 .SH NAME u1trial \- Python unit test runner for using DBus and Twisted together .SH SYNOPSIS .B u1trial [\fIoptions\fR] \fIpath\fR .SH DESCRIPTION u1trial is a Python unit test runner. It provides a main loop using the Twisted reactor and glib, for running tests based on these libraries. It also provides a private DBus session daemon for running the tests under, to avoid interaction with the DBus daemon in a live session. .PP .SH OPTIONS .TP \fB\-h\fR, \fB\-\-help\fR show this help message and exit .TP \fB\-t\fR TEST, \fB\-\-test\fR=\fITEST\fR run specific tests, e.g: className.methodName .TP \fB\-l\fR LOOPS, \fB\-\-loop\fR=\fILOOPS\fR loop selected tests LOOPS number of times .TP \fB\-c\fR, \fB\-\-coverage\fR print a coverage report when finished .TP \fB\-i\fR MODULES, \fB\-\-ignored-modules\fR=MODULES\fR comma-separated test modules to ignore, e.g: "test_gtk.py, test_account.py" .TP \fB\-p\fR PATHS, \fB\-\-ignored-paths\fR=PATHS\fR comma-separated relative paths to ignore, e.g: "tests/platform/windows, tests/platform/macosx" .TP \fB\-\-reactor\fR=REACTOR\fR Run the tests using the REACTOR for twisted main loop integration. .TP \fB\-\-gui\fR Use the GUI mode of the specified reactor. .SH AUTHOR This manual page was written by Rodney Dawes . ubuntuone-dev-tools-13.10/setup.py0000775000202700020270000000623512225022214017413 0ustar dobeydobey00000000000000#!/usr/bin/python # # Copyright 2010-2013 Canonical Ltd. # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR # PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program. If not, see . # # In addition, as a special exception, the copyright holders give # permission to link the code of portions of this program with the # OpenSSL library under certain conditions as described in each # individual source file, and distribute linked combinations # including the two. # You must obey the GNU General Public License in all respects # for all of the code used other than OpenSSL. If you modify # file(s) with this exception, you may extend this exception to your # version of the file(s), but you are not obligated to do so. If you # do not wish to do so, delete this exception statement from your # version. If you delete this exception statement from all source # files in the program, then also delete it here. """setup.py""" import os import subprocess import sys from distutils.core import setup, Command from dirspec import basedir PACKAGE = 'ubuntuone-dev-tools' VERSION = '13.10' U1LINT = 'bin/u1lint' class Lint(Command): """Command to run the lint checks.""" description = 'run python lint checks' user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): """Run u1lint to check the code.""" retcode = subprocess.call([U1LINT]) if retcode != 0: sys.exit(retcode) scripts = ['bin/u1lint', 'bin/u1trial'] if sys.platform == 'win32': # lets add the .bat so that windows users are happy scripts.extend(['bin/u1lint.bat', 'bin/u1trial.bat']) DATA_FILES = [(os.path.join(basedir.default_data_path, PACKAGE), ['data/dbus-session.conf.in', 'data/squid.conf.in']), ] else: DATA_FILES = [('share/%s' % PACKAGE, ['data/dbus-session.conf.in', 'data/squid.conf.in']), ('share/man/man1', ['man/u1lint.1', 'man/u1trial.1']), ] setup(name=PACKAGE, version=VERSION, description='Ubuntu One development tools and utilities', url='http://launchpad.net/ubuntuone-dev-tools', packages=['ubuntuone', 'ubuntuone.devtools', 'ubuntuone.devtools.reactors', 'ubuntuone.devtools.runners', 'ubuntuone.devtools.services', 'ubuntuone.devtools.testing', 'ubuntuone.devtools.testcases'], extra_path='ubuntuone-dev-tools', scripts=scripts, data_files=DATA_FILES, cmdclass={'lint': Lint, }, ) ubuntuone-dev-tools-13.10/ubuntuone.devtools.pth0000664000202700020270000000002512166632147022304 0ustar dobeydobey00000000000000ubuntuone-dev-tools ubuntuone-dev-tools-13.10/COPYING0000664000202700020270000010437412166632147016754 0ustar dobeydobey00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ubuntuone-dev-tools-13.10/MANIFEST.in0000664000202700020270000000026112166632147017445 0ustar dobeydobey00000000000000include MANIFEST.in include COPYING LICENSE LICENSE.OpenSSL pylintrc run-tests include *.pth recursive-include data *.conf recursive-include man *.1 recursive-include bin *.bat ubuntuone-dev-tools-13.10/bin/0000755000202700020270000000000012225022242016437 5ustar dobeydobey00000000000000ubuntuone-dev-tools-13.10/bin/u1lint0000775000202700020270000001744112166632147017631 0ustar dobeydobey00000000000000#!/usr/bin/python # # Copyright 2009-2013 Canonical Ltd. # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR # PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program. If not, see . # # In addition, as a special exception, the copyright holders give # permission to link the code of portions of this program with the # OpenSSL library under certain conditions as described in each # individual source file, and distribute linked combinations # including the two. # You must obey the GNU General Public License in all respects # for all of the code used other than OpenSSL. If you modify # file(s) with this exception, you may extend this exception to your # version of the file(s), but you are not obligated to do so. If you # do not wish to do so, delete this exception statement from your # version. If you delete this exception statement from all source # files in the program, then also delete it here. """Wrapper script for pyflakes command.""" from __future__ import print_function import os import subprocess import sys SRCDIR = os.environ.get('SRCDIR', os.getcwd()) # Define a dummy WindowsError class to keep pyflakes happy on !Windows # In the future we should remove this, when pyflakes handles platform-specific # code more correctly by ignoring some warnings while on other platforms. if sys.platform != 'win32': class WindowsError(OSError): """Dummy WindowsError wrapper to make pyflakes happy.""" class InvalidSetupException(Exception): """Raised when the env is not correctly setup.""" def find_python_installation_path(): """Return the path where python was installed.""" assert(sys.platform == 'win32') # To get the correct path of the script we need the installation path # of python. To get the installation path we first check on the path, # then read the registry. for path in os.getenv("Path", "").split(";"): if os.path.exists(os.path.join(path, "python.exe")): return path try: import winreg except ImportError: import _winreg as winreg software_key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, 'Software') python_key = None try: python_key = winreg.OpenKey(software_key, 'Python') except WindowsError: try: # look in the WoW6432node, we are running python # 32 on a 64 machine wow6432node_key = winreg.OpenKey(software_key, 'WoW6432Node') python_key = winreg.OpenKey(wow6432node_key, 'Python') except WindowsError: raise InvalidSetupException( 'Could not located python installation path.') try: core_key = winreg.OpenKey(python_key, 'PythonCore') version_key = winreg.OpenKey(core_key, sys.winver) return winreg.QueryValue(version_key, 'InstallPath') except WindowsError: raise InvalidSetupException( 'Could not located python installation path.') def find_script_path(script, python_path=None): """Return the path of the given script to be executed by subprocess.""" if sys.platform == 'win32': if python_path is None: python_path = find_python_installation_path() # In a buildout the scripts go next to python.exe, no Scripts folder. if os.path.exists(os.path.join(python_path, script)): return os.path.join(python_path, script) else: return os.path.join(python_path, 'Scripts', script) else: # the default is to return the name of the script beacuse we expect it # to be executable and in the path. return script def get_subprocess_start_info(script): """Return the basic info used by subprocess to start a script.""" if sys.platform == 'win32': # the basic setup in windows is not to have python in the path and not # to have .py assigned to be ran with python, therefore we assume this # scenario python_path = find_python_installation_path() return [os.path.join(python_path, 'python.exe'), find_script_path(script, python_path)] else: # the default is to assume that the script is executable and that it # can be found in the path return [script, ] def _group_lines_by_file(data): """Format file:line:message output as lines grouped by file.""" did_fail = False outputs = [] filename = "" for line in data.splitlines(): current = line.split(":", 3) if line.startswith(" "): outputs.append(" " + current[0] + "") elif line.startswith("build/") or len(current) < 3: pass elif filename == current[0]: if not "[W0511]" in current[2]: did_fail = True outputs.append(" " + current[1] + ": " + current[2]) elif filename != current[0]: filename = current[0] outputs.append("") outputs.append(filename + ":") if not "[W0511]" in current[2]: did_fail = True outputs.append(" " + current[1] + ": " + current[2]) return (did_fail, "\n".join(outputs)) def _find_files(): """Find all Python files under the current tree.""" pyfiles = [] for root, dirs, files in os.walk(SRCDIR, topdown=False): for filename in files: filepath = root + os.path.sep # Skip files in build/ builddir = os.path.join(SRCDIR, 'build') + os.path.sep if filepath.startswith(builddir): continue # Skip protobuf-generated and backup files if filename.endswith("_pb2.py") \ or filename.endswith("~") \ or filename.endswith(".bat"): continue if filename.endswith(".py") \ or filepath.endswith("bin" + os.path.sep): pyfiles.append(os.path.join(root, filename)) pyfiles.sort() return pyfiles def main(options=None, args=None): """Do the deed.""" from optparse import OptionParser usage = '%prog [options]' parser = OptionParser(usage=usage) parser.add_option('-i', '--ignore', dest='ignored', default=None, help='comma-separated paths or files, to ignore') (options, args) = parser.parse_args() failed = False ignored = [] if options.ignored: ignored.extend([os.path.join(SRCDIR, item) for item in map(str.strip, options.ignored.split(','))]) pylint_args = get_subprocess_start_info('pyflakes') for path in _find_files(): is_build = path.startswith(os.path.join(SRCDIR, "_build")) is_ignored = False if path in ignored: continue for ignored_path in ignored: if path.startswith(ignored_path): is_ignored = True break if is_build or is_ignored: continue pylint_args.append(path) sp = subprocess.Popen(pylint_args, bufsize=4096, stdout=subprocess.PIPE) notices = sp.stdout output = "".join(notices.readlines()) if output != "": print("== Python Lint Notices ==") (failed, grouped) = _group_lines_by_file(output) print(grouped, end="\n\n") returncode = sp.wait() if failed: if returncode != 0: exit(returncode) else: exit(1) if __name__ == '__main__': main() ubuntuone-dev-tools-13.10/bin/u1lint.bat0000664000202700020270000000274412166632147020373 0ustar dobeydobey00000000000000:: :: Copyright 2012 Canonical Ltd. :: :: This program is free software: you can redistribute it and/or modify it :: under the terms of the GNU General Public License version 3, as published :: by the Free Software Foundation. :: :: This program is distributed in the hope that it will be useful, but :: WITHOUT ANY WARRANTY; without even the implied warranties of :: MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR :: PURPOSE. See the GNU General Public License for more details. :: :: You should have received a copy of the GNU General Public License along :: with this program. If not, see . :: :: In addition, as a special exception, the copyright holders give :: permission to link the code of portions of this program with the :: OpenSSL library under certain conditions as described in each :: individual source file, and distribute linked combinations :: including the two. :: You must obey the GNU General Public License in all respects :: for all of the code used other than OpenSSL. If you modify :: file(s) with this exception, you may extend this exception to your :: version of the file(s), but you are not obligated to do so. If you :: do not wish to do so, delete this exception statement from your :: version. If you delete this exception statement from all source :: files in the program, then also delete it here. :: Use python to execute the script having the same name as this batch python "%~dpn0" %* ubuntuone-dev-tools-13.10/bin/u1trial.bat0000664000202700020270000000274412166632147020540 0ustar dobeydobey00000000000000:: :: Copyright 2012 Canonical Ltd. :: :: This program is free software: you can redistribute it and/or modify it :: under the terms of the GNU General Public License version 3, as published :: by the Free Software Foundation. :: :: This program is distributed in the hope that it will be useful, but :: WITHOUT ANY WARRANTY; without even the implied warranties of :: MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR :: PURPOSE. See the GNU General Public License for more details. :: :: You should have received a copy of the GNU General Public License along :: with this program. If not, see . :: :: In addition, as a special exception, the copyright holders give :: permission to link the code of portions of this program with the :: OpenSSL library under certain conditions as described in each :: individual source file, and distribute linked combinations :: including the two. :: You must obey the GNU General Public License in all respects :: for all of the code used other than OpenSSL. If you modify :: file(s) with this exception, you may extend this exception to your :: version of the file(s), but you are not obligated to do so. If you :: do not wish to do so, delete this exception statement from your :: version. If you delete this exception statement from all source :: files in the program, then also delete it here. :: Use python to execute the script having the same name as this batch python "%~dpn0" %* ubuntuone-dev-tools-13.10/bin/u1trial0000775000202700020270000000310012166632147017761 0ustar dobeydobey00000000000000#!/usr/bin/python # # Copyright 2009-2012 Canonical Ltd. # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR # PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program. If not, see . # # In addition, as a special exception, the copyright holders give # permission to link the code of portions of this program with the # OpenSSL library under certain conditions as described in each # individual source file, and distribute linked combinations # including the two. # You must obey the GNU General Public License in all respects # for all of the code used other than OpenSSL. If you modify # file(s) with this exception, you may extend this exception to your # version of the file(s), but you are not obligated to do so. If you # do not wish to do so, delete this exception statement from your # version. If you delete this exception statement from all source # files in the program, then also delete it here. """Test runner which works with special services and main loops.""" import os import sys sys.path.insert(0, os.path.abspath(".")) from ubuntuone.devtools.runners import main if __name__ == '__main__': main()