Beispiel #1
0
    def test_rewrite_pyc_check_code_name(self):
        # This one is adapted from cpython's Lib/test/test_import.py
        from os import chmod
        from os.path import join
        from sys import modules, path
        from shutil import rmtree
        from tempfile import mkdtemp

        code = """if 1:
            import sys
            code_filename = sys._getframe().f_code.co_filename
            module_filename = __file__
            constant = 1
            def func():
                pass
            func_filename = func.func_code.co_filename
            """

        module_name = "unlikely_module_name"
        dir_name = mkdtemp(prefix="pypy_test")
        file_name = join(dir_name, module_name + ".py")
        with open(file_name, "wb") as f:
            f.write(code)
        compiled_name = file_name + ("c" if __debug__ else "o")
        chmod(file_name, 0777)

        # Setup
        sys_path = path[:]
        orig_module = modules.pop(module_name, None)
        assert modules.get(module_name) == None
        path.insert(0, dir_name)

        # Test
        import py_compile

        py_compile.compile(file_name, dfile="another_module.py")
        __import__(module_name, globals(), locals())
        mod = modules.get(module_name)

        try:
            # Ensure proper results
            assert mod != orig_module
            assert mod.module_filename == compiled_name
            assert mod.code_filename == file_name
            assert mod.func_filename == file_name
        finally:
            # TearDown
            path[:] = sys_path
            if orig_module is not None:
                modules[module_name] = orig_module
            else:
                try:
                    del modules[module_name]
                except KeyError:
                    pass
            rmtree(dir_name, True)
Beispiel #2
0
def set_type_variables():
    module = modules.get(__name__)

    for symbol in string.ascii_uppercase:  # pylint: disable=W0402
        typevar = type(symbol, (object,), {})  # Equivalent to: class C(object): pass

        setattr(module, symbol, typevar)
        TypeVariable.register(typevar)
Beispiel #3
0
 def test_darwin(self, mock_jsonload):
     old_foundation = modules.get('Foundation')
     old_objc = modules.get('objc')
     old_appkit = modules.get('AppKit')
     modules['Foundation'] = MagicMock()
     modules['objc'] = MagicMock()
     modules['AppKit'] = MagicMock()
     try:
         mock_jsonload.return_value = {
             'backends': ['darwin'],
         }
         ntfy_main(['send', 'foobar'])
     finally:
         if old_foundation is not None:
             modules['Foundation'] = old_foundation
         if old_objc is not None:
             modules['objc'] = old_objc
         if old_appkit is not None:
             modules['AppKit'] = old_appkit
Beispiel #4
0
 def test_win32(self, mock_jsonload):
     old_win32api = modules.get('win32api')
     old_win32gui = modules.get('win32gui')
     old_win32con = modules.get('win32con')
     modules['win32api'] = MagicMock()
     modules['win32gui'] = MagicMock()
     modules['win32con'] = MagicMock()
     try:
         mock_jsonload.return_value = {
             'backends': ['win32'],
         }
         ntfy_main(['send', 'foobar'])
     finally:
         if old_win32api is not None:
             modules['win32api'] = old_win32api
         if old_win32gui is not None:
             modules['win32gui'] = old_win32gui
         if old_win32con is not None:
             modules['win32con'] = old_win32con
Beispiel #5
0
 def test_linux(self, mock_jsonload):
     old_dbus = modules.get('dbus')
     modules['dbus'] = MagicMock()
     try:
         mock_jsonload.return_value = {
             'backends': ['linux'],
         }
         ntfy_main(['send', 'foobar'])
     finally:
         if old_dbus is not None:
             modules['dbus'] = old_dbus
Beispiel #6
0
 def test_default(self, mock_bot, mock_yamlload):
     old_dbus = modules.get('dbus')
     modules['dbus'] = MagicMock()
     try:
         mock_yamlload.return_value = {
             'backends': ['default'],
         }
         ntfy_main(['send', 'foobar'])
     finally:
         if old_dbus is not None:
             modules['dbus'] = old_dbus
Beispiel #7
0
    def set_do_funcs(name):
        # 
        # 动态绑定外部方法
        #
        # 从 sys.modules[name] 中查找所有符合签名的函数,动态绑定到 SHELL。
        # 采用 lambda 包装,提供 self 参数。
        # 函数签名: do_*(line)
        #
        from sys import modules
        from inspect import getmembers, isfunction

        module = modules.get(name, None)
        if module:
            funcs = getmembers(module, lambda m: isfunction(m) and m.__name__.startswith("do_"))
            for name, func in funcs:
                f = lambda self, line: func(line)   # 包装函数,符合签名需要。
                setattr(Shell, name, f)             # 添加 do_* 实例方法
Beispiel #8
0
    def get_root_path(self, name):
        """
        Attempt to compute a root path for a (hopefully importable) name.

        Based in part on Flask's `root_path` calculation. See:

            https://github.com/mitsuhiko/flask/blob/master/flask/helpers.py#L777

        """
        module = modules.get(name)
        if module is not None and hasattr(module, '__file__'):
            return dirname(abspath(module.__file__))

        # Flask keeps looking at this point. We instead set the root path to None,
        # assume that the user doesn't need resource loading, and raise an error
        # when resolving the resource path.
        return None
Beispiel #9
0
    def _find_encoder(self, obj_type):
        from sys import modules

        for type_, enc in list(iteritems(self._encoders)):
            if type(type_) is tuple:
                modname, typename = type_
                imported_type = getattr(modules.get(modname), typename, None)
                if imported_type is not None:
                    del self._encoders[type_]
                    self._encoders[imported_type] = enc
                    type_ = imported_type
                else:  # pragma: nocover
                    continue

            if issubclass(obj_type, type_):
                self._encoders[obj_type] = enc
                return enc

        return None
Beispiel #10
0
def main():
    global invoke
    plugins = [i[:-3] for i in os.listdir(os.path.dirname(__file__)) if
               i.startswith('v8_plugin_') and i.endswith('.py')]
    plugins.sort(reverse=True)

    for plugin in plugins:
        if plugin in modules:
            module = reload(modules.get(plugin))
            invoke = module.invoke
            return

    prompt = '\n\t'.join(['[%d] %s' % (index, value) for index, value in enumerate(plugins)])
    prompt = 'Supported Version:\n\t%s\nPlease choose one [Default: 0]: ' % prompt
    try:
        choose = int(input(prompt))
        if choose >= len(plugins):
            raise RuntimeError
    except:
        print('Choosing default 0')
        choose = 0
    module = __import__(plugins[choose])
    invoke = module.invoke
Beispiel #11
0
    def importExploits(self, files, route, refresh=False):
        """
        Import all exploits that we found and want to import.
        :param files: the files that will import
        :param route: generic or specific
        :param refresh: True if we want to re-import, False otherwise
        :return: exploits imported
        """
        exploits = []
        try:
            for exploit in files:
                name = 'rexploit.modules.{0}.{1}'.format(route, exploit)

                if refresh:
                    try:
                        modules.pop(name)
                    except KeyError:
                        break

                # Reload all modules
                if name in modules.keys():
                    # Get a module
                    e = modules.get(name)
                else:
                    # Import a new module
                    e = import_module('.modules.{0}.{1}'.format(route, exploit), 'rexploit')

                # Create an exploit object and we set IP and MAC
                e = e.Exploit()
                e.ip = self.__IP
                e.mac = self.__MAC

                exploits.append(e)
            return exploits
        except ImportError:
            return exploits
Beispiel #12
0
def get_bl_info():
    # .__module__ is the 'name of package.module', so strip after dot
    packageName = dummy.__module__.partition('.')[0]
    return modules.get(packageName).bl_info
# -*- coding: UTF-8 -*-
# Copyright 2017 Red Hat, Inc.
# Part of clufter project
# Licensed under GPLv2+ (a copy included | http://gnu.org/licenses/gpl-2.0.txt)

from __future__ import print_function

"""Testing `simpleconfig2needlexml' filter"""
__author__ = "Jan Pokorný <jpokorny @at@ Red Hat .dot. com>"

from os.path import join, dirname; from sys import modules as m  # 2/3 compat
b = m.get('builtins', m.get('__builtin__')); e, E, h = 'exec', 'execfile', hash
c = lambda x: compile(x.read(), x.name, 'exec')
with open(join(dirname(dirname(__file__)), '_go')) as f:
    getattr(b, e, getattr(b, E, h)(f.name).__repr__.__name__.__ne__)(c(f))


from os.path import dirname, join
from unittest import TestCase

from .filter_manager import FilterManager
from .formats.simpleconfig import simpleconfig
from .utils_2to3 import bytes_enc

flt = 'simpleconfig2needlexml'
simpleconfig2needlexml = FilterManager.init_lookup(flt).filters[flt]


class FiltersSimpleconfig2NeedlexmlTestCase(TestCase):
    def testSimpleconfig2Needlexml(self):
        result = simpleconfig2needlexml(simpleconfig('struct',
Beispiel #14
0
# -*- coding: UTF-8 -*-
# Copyright 2018 Red Hat, Inc.
# Part of clufter project
# Licensed under GPLv2+ (a copy included | http://gnu.org/licenses/gpl-2.0.txt)

from __future__ import print_function
"""Testing destilling XSLT from the sparse tree-organized snippets"""
__author__ = "Jan Pokorný <jpokorny @at@ Red Hat .dot. com>"

from os.path import join, dirname
from sys import modules as m  # 2/3 compat
b = m.get('builtins', m.get('__builtin__'))
e, E, h = 'exec', 'execfile', hash
c = lambda x: compile(x.read(), x.name, 'exec')
with open(join(dirname(__file__), '_go')) as f:
    getattr(b, e, getattr(b, E, h)(f.name).__repr__.__name__.__ne__)(c(f))

from unittest import TestCase
from os.path import dirname, join
from sys import modules

from lxml import etree

from .filter import XMLFilter
from .format_manager import FormatManager
from .utils_2to3 import str_enc

WALK_DIR = join(dirname(modules[XMLFilter.__module__].__file__), 'filters')


class Ccs2NeedleXsltViewOnly(TestCase):
def get_bl_info():
    # .__module__ is the 'name of package.module', so strip after dot
    packageName = dummy.__module__.partition('.')[0]
    return modules.get(packageName).bl_info
Beispiel #16
0
 def _imp(name, fromlist, prefix=''):
     module = modules.get(prefix + name)
     if module is not None:
         if fromlist or ('.' not in name):
             return module
         return modules[prefix + name.split('.')[0]]
Beispiel #17
0
# -*- coding: UTF-8 -*-
# Copyright 2017 Red Hat, Inc.
# Part of clufter project
# Licensed under GPLv2+ (a copy included | http://gnu.org/licenses/gpl-2.0.txt)
"""Testing XML helpers"""
__author__ = "Jan Pokorný <jpokorny @at@ Red Hat .dot. com>"

from os.path import join, dirname; from sys import modules as m  # 2/3 compat
b = m.get('builtins', m.get('__builtin__')); e, E, h = 'exec', 'execfile', hash
c = lambda x: compile(x.read(), x.name, 'exec')
with open(join(dirname(__file__), '_go')) as f:
    getattr(b, e, getattr(b, E, h)(f.name).__repr__.__name__.__ne__)(c(f))


from unittest import TestCase

from lxml import etree
from os.path import dirname, join

from .utils_xml import rng_pivot


class TestRngPivot(TestCase):
    def test_rng_pivot(self):
        #p = join(dirname_x(__file__, 2), 'formats', 'corosync', 'corosync.rng')
        p = join(dirname(__file__), 'corosync.rng')
        with open(p) as f:
            et = etree.parse(f)
        rng_pivot(et, 'logging')
        p = join(dirname(__file__), 'corosync.rng.exp')
        if False:  # to regenerate the expected file (manual review)
Beispiel #18
0
    'rain':                '40', #Rain
    'snow':                '41', #Snow
    '42':                  '42', #Same as 41
    '43':                  '43', #Windy/Snow
    'mostly_sunny':        '44', #Same as 30
    'night_rain':          '45', #Rain/Night
    'night_snow':          '46', #Snow/Night
    'night_thunderstorm':  '47', #Thunder Showers/Night
    }


import os
from sys import modules


weather = modules.get( 'resources.lib.weather' ) or modules.get( 'weather' ) or modules[ '__main__' ]


def getIcon( uri, usenight=False ):
    PREFIX_ICON_ADDON = ( "", "night_" )[ usenight ]
    google_code = os.path.splitext( os.path.basename( uri ) )[ 0 ]
    xbmc_code   = usenight and code.get( PREFIX_ICON_ADDON + google_code )
    xbmc_code   = xbmc_code or code.get( google_code, 'na' )

    #default icon
    icon = "%s.png" % xbmc_code

    # icons of addon
    if weather.ICONS_SET == 0:
        if not usenight: icon = weather.WEATHER_ICONS + icon
        else: icon = os.path.join( weather.WEATHER_ICONS + "night", icon )
from jira import JIRAError

from sys import stderr

import bugdex.environment_tools
from bugdex.jira_tools import (
    connect_to_jira,
    deep_create_jira_bug,
    JiraBug,
)
from bugdex.core import deep_delete_source_specific_bug
from bugdex.vendor_to_jira import update_external_bug_to_jira

from sys import modules

if not (cache := modules.get('cache')):
    cache = ModuleType('cache')
    cache.jira_server = None
    modules['cache'] = cache


def get_jira_server():
    if cache.jira_server:
        return cache.jira_server
    else:
        print('connecting to jira server')
        cache.jira_server = connect_to_jira()
        return cache.jira_server


def alt_description() -> str:
Beispiel #20
0
                    copystat(src, dst)
                except IOError as e:
                    raise DistutilsSetupError(str(e))
    # class pkg_prepare

    return pkg_prepare


# =========================================================================

self_discovery_plan = ['__project__']
while True:
    pkg, backup_mod, project = {}, None, self_discovery_plan.pop()
    try:
        # XXX check relative import
        backup_mod = sys_modules.get(project)
        if backup_mod:
            if not hasattr(backup_mod, '__path__'):  # not the case for builtins
                continue
            backup_mod = sys_modules.pop(project)
        backup_path, sys_path[:] = sys_path[:], [here]
        pkg = __import__(project, globals=pkg)
        break
    except ImportError:
        sys_path[:] = backup_path
        if backup_mod:
            sys_modules[project] = backup_mod
        if project == '__project__':
            from glob import iglob
            self_discovery_plan.extend(p[:-len('.egg-info')].split('-', 1)[0]
                                       for p in iglob('*.egg-info'))
Beispiel #21
0
from flask_caching import Cache
from flask_sqlalchemy import SQLAlchemy

from xss_receiver import JWTAuth
from xss_receiver.Config import URL_PREFIX
from xss_receiver.Utils import NoServerHeaderFlask
from xss_receiver.asserts.ip2region import Ip2Region

app = NoServerHeaderFlask(__name__, static_folder=None, template_folder=None)
app.config.from_pyfile('Config.py')
app.config['SESSION_COOKIE_PATH'] = f'{URL_PREFIX}/admin/'
JWTAuth.init_app(app)
cache = Cache()

if modules.get('uwsgi'):
    cache.init_app(app,
                   config={
                       'CACHE_TYPE': 'uwsgi',
                       'CACHE_UWSGI_NAME': 'xss',
                       'CACHE_DEFAULT_TIMEOUT': 0
                   })
else:
    cache.init_app(app,
                   config={
                       'CACHE_TYPE': 'filesystem',
                       'CACHE_DIR': '/dev/shm/',
                       'CACHE_OPTIONS': {
                           'mode': 0o600
                       },
                       'CACHE_DEFAULT_TIMEOUT': 0
 def test_render_ship_figure(self):
     mock_player = Mock(ship="frigate", color="#00FF00", name="dummy", coordinates=(1, 2))
     self._board.render_ship_figure(mock_player)
     self.assertIn("frigate_#00FF00", modules.get("assets").Gallery._pictures)
 def tearDown(self):
     modules.get("assets").Gallery._raw_images = {}
     modules.get("assets").Gallery._raw_images = {}
Beispiel #24
0
 def _imp(name, fromlist, prefix=''):
     module = modules.get(prefix+name)
     if module is not None:
         if fromlist or ('.' not in name):
             return module
         return modules[prefix+name.split('.')[0]]
Beispiel #25
0
                except IOError, e:
                    raise DistutilsSetupError(str(e))

    # class pkg_prepare

    return pkg_prepare


# =========================================================================

self_discovery_plan = ['__project__']
while True:
    pkg, backup_mod, project = {}, None, self_discovery_plan.pop()
    try:
        # XXX check relative import
        backup_mod = sys_modules.get(project)
        if backup_mod:
            if not hasattr(backup_mod,
                           '__path__'):  # not the case for builtins
                continue
            backup_mod = sys_modules.pop(project)
        backup_path, sys_path[:] = sys_path[:], [here]
        pkg = __import__(project, globals=pkg)
        break
    except ImportError:
        sys_path[:] = backup_path
        if backup_mod:
            sys_modules[project] = backup_mod
        if project == '__project__':
            from glob import iglob
            self_discovery_plan.extend(p[:-len('.egg-info')].split('-', 1)[0]
Beispiel #26
0
    'thunderstorm': '38',  #Lightning
    'chance_of_rain': '39',  #Rain/Day
    'rain': '40',  #Rain
    'snow': '41',  #Snow
    '42': '42',  #Same as 41
    '43': '43',  #Windy/Snow
    'mostly_sunny': '44',  #Same as 30
    'night_rain': '45',  #Rain/Night
    'night_snow': '46',  #Snow/Night
    'night_thunderstorm': '47',  #Thunder Showers/Night
}

import os
from sys import modules

weather = modules.get('resources.lib.weather') or modules.get(
    'weather') or modules['__main__']


def getIcon(uri, usenight=False):
    PREFIX_ICON_ADDON = ("", "night_")[usenight]
    google_code = os.path.splitext(os.path.basename(uri))[0]
    xbmc_code = usenight and code.get(PREFIX_ICON_ADDON + google_code)
    xbmc_code = xbmc_code or code.get(google_code, 'na')

    #default icon
    icon = "%s.png" % xbmc_code

    # icons of addon
    if weather.ICONS_SET == 0:
        if not usenight: icon = weather.WEATHER_ICONS + icon