def test_make_content(self):
        """Make content."""
        mocker = Mocker()

        # node 'old gen'
        node = mocker.mock()
        expect(node.generation).result('new_generation')
        expect(node.make_content('original_hash', 'hash_hint', 'crc32_hint',
                                 'inflated_size_hint', 'deflated_size_hint',
                                 'storage_key', 'magic_hash'))

        # user
        user = mocker.mock()
        expect(user.volume('volume_id').get_node('node_id')).result(node)
        self.dal._get_user = lambda *a: user

        with mocker:
            d = dict(user_id='user_id', volume_id='volume_id',
                     node_id='node_id', original_hash='original_hash',
                     hash_hint='hash_hint', crc32_hint='crc32_hint',
                     inflated_size_hint='inflated_size_hint',
                     deflated_size_hint='deflated_size_hint',
                     storage_key='storage_key', magic_hash='magic_hash',
                     session_id=None)
            result = self.dal.make_content(**d)
        self.assertEqual(result, dict(generation='new_generation'))
    def test_get_share(self):
        """Get a share."""
        mocker = Mocker()

        # the share
        share = mocker.mock()
        expect(share.id).result("share_id")
        expect(share.root_id).result("share_root_id")
        expect(share.name).result("name")
        expect(share.shared_by_id).result("shared_by_id")
        expect(share.shared_to_id).result("shared_to_id")
        expect(share.accepted).result(True)
        expect(share.access).result(1)

        # user
        user = mocker.mock()
        self.dal._get_user = lambda *a: user
        expect(user.get_share("share_id")).result(share)

        with mocker:
            result = self.dal.get_share("user_id", "share_id")
        should = dict(
            share_id="share_id",
            share_root_id="share_root_id",
            name="name",
            shared_by_id="shared_by_id",
            accepted=True,
            shared_to_id="shared_to_id",
            access=1,
        )
        self.assertEqual(result, should)
    def test_make_file_with_content(self):
        """Make a file with content associated."""
        mocker = Mocker()

        # node, with a generation attribute
        node = mocker.mock()
        expect(node.id).result("node_id")
        expect(node.generation).result(123)

        # user, with the chained calls to the operation
        user = mocker.mock()
        expect(
            user.volume("vol_id")
            .dir("parent_id")
            .make_file_with_content("name", "hash", "crc32", "size", "deflated_size", "storage_key")
        ).result(node)
        self.dal._get_user = lambda *a: user

        with mocker:
            kwargs = dict(
                user_id="user_id",
                volume_id="vol_id",
                name="name",
                parent_id="parent_id",
                crc32="crc32",
                size="size",
                node_hash="hash",
                deflated_size="deflated_size",
                storage_key="storage_key",
                session_id="session_id",
            )
            result = self.dal.make_file_with_content(**kwargs)

        self.assertEqual(result, dict(generation=123, node_id="node_id"))
示例#4
0
 def test(c):
     if c.eol != "\n":
         c.input = c.input.replace("\n", c.eol)
         c.output = c.output.replace("\n", c.eol)
     result = TestConfig()
     default = False
     m = Mocker()
     tv = m.mock(ak.NSTextView)
     (tv.doc_view.document.indent_mode << c.mode).count(0, None)
     (tv.doc_view.document.indent_size << c.size).count(0, None)
     (tv.doc_view.document.eol << c.eol).count(0, None)
     sel = fn.NSMakeRange(*c.oldsel); (tv.selectedRange() << sel).count(0, None)
     (tv.string() << fn.NSString.stringWithString_(c.input)).count(0, None)
     (tv.shouldChangeTextInRange_replacementString_(ANY, ANY) << True).count(0, None)
     ts = m.mock(ak.NSTextStorage); (tv.textStorage() << ts).count(0, None)
     c.setup(m, c, TestConfig(locals()))
     def do_text(sel, repl):
         result.text = c.input[:sel[0]] + repl + c.input[sel[0] + sel[1]:]
     expect(ts.replaceCharactersInRange_withString_(ANY, ANY)).call(do_text).count(0, None)
     def do_sel(sel):
         result.sel = sel
     expect(tv.setSelectedRange_(ANY)).call(do_sel).count(0, None)
     expect(tv.didChangeText()).count(0, None)
     if c.scroll:
         tv.scrollRangeToVisible_(ANY)
     with m:
         c.method(tv, None, None)
         if "text" in result:
             eq_(result.text, c.output)
         else:
             eq_(c.output, SAME)
         if "sel" in result:
             eq_(result.sel, c.newsel)
    def test_list_volumes_root_and_quota(self):
        """List volumes, check root and quota."""
        mocker = Mocker()

        # root
        root = mocker.mock()
        expect(root.generation).result(123)
        expect(root.root_id).result("root_id")

        # quota
        quota = mocker.mock()
        expect(quota.free_bytes).result(4567890)

        # user
        user = mocker.mock()
        self.dal._get_user = lambda *a: user
        expect(user.volume().get_volume()).result(root)
        expect(user.get_shared_to(accepted=True)).result([])
        expect(user.get_udfs()).result([])
        expect(user.get_quota()).result(quota)

        with mocker:
            result = self.dal.list_volumes("user_id")

        self.assertEqual(sorted(result), ["free_bytes", "root", "shares", "udfs"])
        self.assertEqual(result["root"], dict(generation=123, root_id="root_id"))
        self.assertEqual(result["free_bytes"], 4567890)
    def test_add_part_to_uploadjob(self):
        """Delete an uploadjob."""
        mocker = Mocker()

        # upload job
        uj = mocker.mock()
        expect(
            uj.add_part(
                "chunk_size", "inflated_size", "crc32", "hash_context", "magic_hash_context", "decompress_context"
            )
        )

        # user
        user = mocker.mock()
        self.dal._get_user = lambda *a: user
        expect(user.get_uploadjob("uploadjob_id")).result(uj)

        with mocker:
            d = dict(
                user_id="user_id",
                uploadjob_id="uploadjob_id",
                chunk_size="chunk_size",
                inflated_size="inflated_size",
                crc32="crc32",
                hash_context="hash_context",
                magic_hash_context="magic_hash_context",
                decompress_context="decompress_context",
            )
            result = self.dal.add_part_to_uploadjob(**d)

        self.assertEqual(result, {})
    def test_create_share(self):
        """Create a share."""
        mocker = Mocker()

        # patch the DAL method to get the other user id from the username
        to_user = mocker.mock()
        expect(to_user.id).result('to_user_id')
        fake = mocker.mock()
        expect(fake(username='******')).result(to_user)
        self.patch(dal_backend.services, 'get_storage_user', fake)

        # share
        share = mocker.mock()
        expect(share.id).result('share_id')

        # user, with the chained calls to the operation
        user = mocker.mock()
        expect(user.volume().dir('node_id').share(
            'to_user_id', 'name', True)).result(share)
        self.dal._get_user = lambda *a: user

        with mocker:
            result = self.dal.create_share('user_id', 'node_id',
                                           'to_username', 'name', True)
        self.assertEqual(result, dict(share_id='share_id'))
    def test_get_share(self):
        """Get a share."""
        mocker = Mocker()

        # the share
        share = mocker.mock()
        expect(share.id).result('share_id')
        expect(share.root_id).result('share_root_id')
        expect(share.name).result('name')
        expect(share.shared_by_id).result('shared_by_id')
        expect(share.shared_to_id).result('shared_to_id')
        expect(share.accepted).result(True)
        expect(share.access).result(1)

        # user
        user = mocker.mock()
        self.dal._get_user = lambda *a: user
        expect(user.get_share('share_id')).result(share)

        with mocker:
            result = self.dal.get_share('user_id', 'share_id')
        should = dict(share_id='share_id', share_root_id='share_root_id',
                      name='name', shared_by_id='shared_by_id', accepted=True,
                      shared_to_id='shared_to_id', access=1)
        self.assertEqual(result, should)
    def test_add_part_to_uploadjob(self):
        """Delete an uploadjob."""
        mocker = Mocker()

        # upload job
        uj = mocker.mock()
        expect(uj.add_part('chunk_size', 'inflated_size', 'crc32',
                           'hash_context', 'magic_hash_context',
                           'decompress_context'))

        # user
        user = mocker.mock()
        self.dal._get_user = lambda *a: user
        expect(user.volume('volume_id')
               .get_uploadjob('uploadjob_id')).result(uj)

        with mocker:
            d = dict(user_id='user_id', uploadjob_id='uploadjob_id',
                     chunk_size='chunk_size', inflated_size='inflated_size',
                     crc32='crc32', hash_context='hash_context',
                     magic_hash_context='magic_hash_context',
                     decompress_context='decompress_context',
                     volume_id='volume_id')
            result = self.dal.add_part_to_uploadjob(**d)

        self.assertEqual(result, {})
    def test_make_file_with_content(self):
        """Make a file with content associated."""
        mocker = Mocker()

        # node, with a generation attribute
        node = mocker.mock()
        expect(node.id).result('node_id')
        expect(node.generation).result(123)

        # user, with the chained calls to the operation
        user = mocker.mock()
        expect(user.volume('vol_id').dir('parent_id')
               .make_file_with_content('name', 'hash', 'crc32', 'size',
                                       'deflated_size', 'storage_key')
               ).result(node)
        self.dal._get_user = lambda *a: user

        with mocker:
            kwargs = dict(user_id='user_id', volume_id='vol_id', name='name',
                          parent_id='parent_id', crc32='crc32', size='size',
                          node_hash='hash', deflated_size='deflated_size',
                          storage_key='storage_key', session_id='session_id')
            result = self.dal.make_file_with_content(**kwargs)

        self.assertEqual(result, dict(generation=123, node_id='node_id'))
示例#11
0
def test_wrap_to_margin_guide():
    m = Mocker()
    tv = m.mock(ak.NSTextView)
    wrap = m.replace(mod, 'wrap_selected_lines')
    wrap(tv, mod.Options(wrap_column=const.DEFAULT_RIGHT_MARGIN, indent=True))
    with m:
        mod.wrap_at_margin(tv, None, None)
示例#12
0
 def test(c):
     m = Mocker()
     options = make_options(c)
     tv = m.mock(TextView)
     tv.selectedRange() >> fn.NSMakeRange(0, 16)
     tv.string() >> fn.NSString.alloc().initWithString_(c.text)
     if not isinstance(c.expect, Exception):
         result = [c.text]
         def replace(range, value):
             start, end = range
             text = result[0]
             result[0] = text[:start] + value + text[start + end:]
         tv.shouldChangeTextInRange_replacementString_(ANY, ANY) >> True
         expect(tv.textStorage().replaceCharactersInRange_withString_(
             ANY, ANY)).call(replace)
         tv.didChangeText()
         tv.setNeedsDisplay_(True)
     finder = Finder((lambda: tv), options)
     with m:
         if isinstance(c.expect, Exception):
             def check(err):
                 print(err)
                 eq_(str(err), str(c.expect))
             with assert_raises(type(c.expect), msg=check):
                 getattr(finder, c.action)(None)
         else:
             getattr(finder, c.action)(None)
             eq_(result[0], c.expect)
示例#13
0
def test_set_main_view_of_window():
    proj = Project.create()
    m = Mocker()
    view = m.mock(NSView)
    win = m.mock(NSWindow)
    with m:
        proj.set_main_view_of_window(view, win) # for now this does nothing
示例#14
0
 def test(c):
     m = Mocker()
     sv = ThinSplitView.alloc().init()
     nsanim = m.replace(NSViewAnimation, passthrough=False)
     nsdict = m.replace(NSDictionary, passthrough=False)
     nsval = m.replace(NSValue, passthrough=False)
     nsarr = m.replace(NSArray, passthrough=False)
     view = m.mock(NSView)
     rect = m.mock(NSRect)
     rval = nsval.valueWithRect_(rect) >> m.mock()
     resize = nsdict.dictionaryWithObjectsAndKeys_(
         view, NSViewAnimationTargetKey, rval, NSViewAnimationEndFrameKey, None
     ) >> m.mock(NSDictionary)
     anims = nsarr.arrayWithObject_(resize) >> m.mock(NSArray)
     anim = nsanim.alloc() >> m.mock(NSViewAnimation)
     anim.initWithViewAnimations_(anims) >> anim
     anim.setDuration_(0.5)
     if c.delegate:
         delegate = m.mock(RedrawOnAnimationEndedDelegate)
         anim.setDelegate_(delegate)
     else:
         delegate = None
     anim.startAnimation()
     with m:
         sv._animate_view(view, rect, delegate)
    def test_collect_process_info_new_report(self):
        """Check how the process info is collected first time."""
        mocker = Mocker()
        assert not self.worker.process_cache

        # patch Process to return our mock for test pid
        Process = mocker.mock()
        self.patch(stats_worker.psutil, 'Process', Process)
        proc = mocker.mock()
        pid = 1234
        expect(Process(pid)).result(proc)

        # patch ProcessReport to return or mock for given proc
        ProcessReport = mocker.mock()
        self.patch(stats_worker, 'ProcessReport', ProcessReport)
        proc_report = mocker.mock()
        expect(ProcessReport(proc)).result(proc_report)

        # expect to get called with some info, return some results
        name = 'test_proc'
        result = object()
        expect(proc_report.get_memory_and_cpu(prefix=name)).result(result)

        with mocker:
            real = self.worker._collect_process(pid, name)
        self.assertIdentical(real, result)
示例#16
0
文件: test_app.py 项目: editxt/editxt
 def test(action, app_method):
     delegate = mod.AppDelegate.alloc().init()
     m = Mocker()
     delegate.app = app = m.mock(Application)
     getattr(app, app_method)()
     with m:
         getattr(delegate, action)(None)
示例#17
0
 def test(c):
     m = Mocker()
     beep = m.replace(mod, "beep")
     options = make_options(c)
     editor = m.mock(Editor)
     editor.selection >> c.select
     (editor.text << Text(c.text)).count(0, None)
     tv = m.mock(ak.NSTextView)
     (editor.text_view << tv).count(0, 1)
     (tv.shouldChangeTextInRange_replacementString_(ANY, ANY) << True).count(0, 1)
     expect(tv.didChangeText()).count(0, 1)
     expect(tv.setNeedsDisplay_(True)).count(0, 1)
     if c.expect is BEEP:
         beep()
     finder = Finder((lambda: editor), options, None)
     with m:
         if isinstance(c.expect, Exception):
             def check(err):
                 print(err)
                 eq_(str(err), str(c.expect))
             with assert_raises(type(c.expect), msg=check):
                 getattr(finder, c.action)(None)
         else:
             getattr(finder, c.action)(None)
             if c.expect is BEEP:
                 eq_(editor.text[:], c.text)
             else:
                 eq_(editor.text[:], c.expect)
示例#18
0
def test_reload_config():
    from editxt.config import Config
    m = Mocker()
    tv = m.mock(ak.NSTextView)
    tv.app.reload_config()
    with m:
        mod.reload_config(tv, None)
    def test_move(self):
        """Move."""
        mocker = Mocker()

        # node, with a generation attribute
        node = mocker.mock()
        expect(node.generation).result(123)
        expect(node.mimetype).result("mime")

        # user, with the chained calls to the operation
        user = mocker.mock()
        new_parent_id = uuid.uuid4()
        expect(user.volume("vol_id").node("node_id").move(new_parent_id, "new_name")).result(node)
        self.dal._get_user = lambda *a: user

        with mocker:
            kwargs = dict(
                user_id="user_id",
                volume_id="vol_id",
                node_id="node_id",
                new_parent_id=new_parent_id,
                new_name="new_name",
                session_id="session_id",
            )
            result = self.dal.move(**kwargs)

        self.assertEqual(result, dict(generation=123, mimetype="mime"))
示例#20
0
 def test(c):
     if c.eol != "\n":
         c.input = c.input.replace("\n", c.eol)
         c.output = c.output.replace("\n", c.eol)
     result = []
     m = Mocker()
     tv = m.mock(NSTextView)
     reset = (c.new == "\t")
     if c.old != c.new or reset:
         tv.string() >> c.input
         rng = NSMakeRange(0, len(c.input))
         tv.shouldChangeTextInRange_replacementString_(rng, c.output) >> True
         if reset:
             doc = tv.doc_view.document >> m.mock(TextDocument)
             doc.reset_text_attributes(c.size)
         if c.input != c.output:
             sel = tv.selectedRange() >> NSRange(*c.sel)
             ts = tv.textStorage() >> m.mock(NSTextStorage)
             ts.replaceCharactersInRange_withString_(rng, c.output)
             if sel.location > len(c.output):
                 sel = NSRange(len(c.output), 0)
             elif sel.location + sel.length > len(c.output):
                 sel = NSRange(sel.location, len(c.output) - sel.location)
             tv.setSelectedRange_(sel)
         tv.didChangeText()
     with m:
         mod.change_indentation(tv, c.old, c.new, c.size)
示例#21
0
    def test(c):
        m = Mocker()
        beep = m.replace(mod, "beep")

        @command(
            arg_parser=CommandParser(
                Choice(("selection", True), ("all", False)),
                Choice(("no", False), ("yes", True)),
                Regex("sort_regex", True),
            )
        )
        def cmd(editor, args):
            raise NotImplementedError("should not get here")

        @command(
            arg_parser=CommandParser(Regex("search_pattern", replace=c.replace), Choice(("yep", False), ("yes", True))),
            lookup_with_arg_parser=True,
        )
        def search(editor, args):
            raise NotImplementedError("should not get here")

        @command(arg_parser=CommandParser(IllBehaved("bang")))
        def ill(editor, args):
            raise NotImplementedError("should not get here")

        bar = CommandTester(cmd, search, ill)
        with m:
            eq_(bar.get_placeholder(c.text), c.expect)
示例#22
0
 def test(c):
     m = Mocker()
     menu = m.mock(ak.NSMenu)
     ctl = CommandManager("<history>")
     for command in c.commands:
         ctl.add_command(command, None, menu)
     eq_(ctl.lookup(c.lookup), c.result)
示例#23
0
    def test_call_no_unicode_and_no_error_desc(self):
        reg = getUtility(IRegistry).forInterface(ICollectiveFlattr)
        reg.access_token = u''

        mocker = Mocker()
        func = mocker.replace('collective.flattr.browser.flattr.Flattr.getAccessToken')
        func(u'un8Vzv7pNMXNuAQY3uRgjYfM4V3Feirz')
        mocker.result({'access_token': u'NEW_ACCESS_TOKEN',
            'token_type': u'bearer', 'error': u'blubber'})

        with as_manager(self.portal) as view:
            from collective.flattr.browser.flattr import Flattr
            with mocker:
                self.layer['request']['code'] = 'un8Vzv7pNMXNuAQY3uRgjYfM4V3Feirz'
                view = Flattr(self.portal, self.layer['request'])

                ret = view()
                self.assertEquals(reg.access_token, u'')
                self.assertEquals(self.layer['request'].response\
                    .headers['location'], 'http://nohost/plone')
                ret = IStatusMessage(self.layer['request'])\
                    .showStatusMessages()
                self.assertEquals(ret[0].message,
                    u'undefined: Undefined error while getting access token')
                self.assertEquals(ret[0].type, u'error')
示例#24
0
 def test(app, path, prompt=False):
     prompt = (True,) if prompt else ()
     initial_content = None if "missing" in path else "initial"
     with make_file(path, content=initial_content) as real_path:
         m = Mocker()
         window = app.windows[0]
         editor = window.projects[0].editors[0]
         document = editor.document
         save_document_as = m.method(window.save_document_as)
         prompt_to_overwrite = m.method(window.prompt_to_overwrite)
         has_path_changed = m.method(document.file_changed_since_save)
         if os.path.isabs(path):
             document.file_path = path = real_path
         elif path:
             document.file_path = path
         document.text = "saved text"
         def save_prompt(document, callback):
             if "nodir" in path:
                 os.mkdir(os.path.dirname(real_path))
             print("saving as", real_path)
             callback(real_path)
         if prompt or path != real_path or "nodir" in path or "missing" in path:
             expect(save_document_as(editor, ANY)).call(save_prompt)
         elif has_path_changed() >> ("moved" in path):
             expect(prompt_to_overwrite(editor, ANY)).call(save_prompt)
         calls = []
         def callback(saved):
             calls.append(saved)
         with m:
             editor.save(*prompt, callback=callback)
             eq_(get_content(real_path), "saved text")
             eq_(calls, [True])
示例#25
0
    def test_call_invalid_request(self):
        reg = getUtility(IRegistry).forInterface(ICollectiveFlattr)
        reg.access_token = u''

        mocker = Mocker()
        func = mocker.replace('collective.flattr.browser.flattr.Flattr.getAccessToken')
        func(u'un8Vzv7pNMXNuAQY3uRgjYfM4V3Feirz')
        mocker.result({'error': u'invalid_request',
            'error_description': u'error desc'})

        with as_manager(self.portal) as view:
            ## need the real class here, not the wrapped one, to get mocker
            ## working
            from collective.flattr.browser.flattr import Flattr

            with mocker:
                view = Flattr(self.portal, self.layer['request'])
                self.layer['request']['code'] = u'un8Vzv7pNMXNuAQY3uRgjYfM4V3Feirz'
                ret = view()
                self.assertEquals(self.layer['request'].response\
                    .headers['location'], 'http://nohost/plone')
                ret = IStatusMessage(self.layer['request'])\
                    .showStatusMessages()[0]
                self.assertEquals(ret.message, u'invalid_request: error desc')
                self.assertEquals(ret.type, u'error')
示例#26
0
    def test_call_valid(self):
        reg = getUtility(IRegistry).forInterface(ICollectiveFlattr)
        reg.access_token = u''

        mocker = Mocker()
        func = mocker.replace('collective.flattr.browser.flattr.Flattr.getAccessToken')
        func(u'un8Vzv7pNMXNuAQY3uRgjYfM4V3Feirz')
        mocker.result({'access_token': u'NEW_ACCESS_TOKEN',
            'token_type': u'bearer'})

        with as_manager(self.portal) as view:
            ## need the real class here, not the wrapped one, to get mocker
            ## working
            from collective.flattr.browser.flattr import Flattr

            with mocker:
                self.layer['request']['code'] = u'un8Vzv7pNMXNuAQY3uRgjYfM4V3Feirz'
                view = Flattr(self.portal, self.layer['request'])

                ret = view()
                self.assertEquals(reg.access_token, u'NEW_ACCESS_TOKEN')
                self.assertEquals(self.layer['request'].response\
                    .headers['location'], 'http://nohost/plone')
                ret = IStatusMessage(self.layer['request'])\
                    .showStatusMessages()[0]
                self.assertEquals(ret.message,
                    u'collective.flattr successfully configured')
                self.assertEquals(ret.type, u'info')
示例#27
0
def test_SyntaxFactory_index_definitions():
    from editxt.valuetrans import SyntaxDefTransformer
    class FakeDef(object):
        def __init__(self, name):
            self.name = name
        def __repr__(self):
            return "<%s %x>" % (self.name, id(self))
    text1 = FakeDef("Plain Text")
    text2 = FakeDef("Plain Text")
    python = FakeDef("Python")
    sf = SyntaxFactory()
    sf.registry = {
        "*.txt": text1,
        "*.text": text2,
        "*.txtx": text1,
        "*.py": python,
    }
    defs = sorted([text1, text2, python], key=lambda d:(d.name, id(d)))
    m = Mocker()
    vt = m.replace(NSValueTransformer, passthrough=False)
    st = vt.valueTransformerForName_("SyntaxDefTransformer") >> \
        m.mock(SyntaxDefTransformer)
    st.update_definitions(defs)
    with m:
        sf.index_definitions()
    eq_(sf.definitions, defs)
示例#28
0
def test_wrap_to_margin_guide():
    m = Mocker()
    editor = m.mock()
    wrap = m.replace(mod, 'wrap_selected_lines')
    wrap(editor, mod.Options(wrap_column=const.DEFAULT_WRAP_COLUMN, indent=True))
    with m:
        mod.wrap_at_margin(editor, None)
示例#29
0
 def test(c):
     with test_app() as app:
         m = Mocker()
         fc = FindController(app)
         fc.options = make_options(c)
         beep = m.replace(mod, "beep")
         sheet = m.replace(ak, "NSBeginAlertSheet")
         gui = m.replace(fc, "gui")
         ftext = m.mock(ak.NSTextField)
         if c.search != mod.LITERAL:
             if c.ftext is None:
                 gui.find_text >> None
             else:
                 (gui.find_text << ftext).count(1, None)
                 ftext.stringValue() >> c.ftext
             if not c.expect:
                 beep()
                 sheet(
                     ANY,
                     "OK", None, None,
                     gui.window >> "<window>", None, None, None, 0,
                     ANY,
                 );
         with m:
             result = fc.validate_expression()
             eq_(result, c.expect)
示例#30
0
    def test(c):
        m = Mocker()
        beep = m.replace(mod, "beep")
        options = make_options(c)
        editor = m.mock(Editor)
        (editor.selection << c.select).count(0, None)
        (editor.text << Text(c.text)).count(0, None)

        def put(text, rng, select=False):
            editor.text[rng] = text
        (editor.put(ANY, ANY) << (c.expect is not BEEP)).call(put).count(0, 1)
        if c.expect is BEEP:
            beep()
        finder = Finder((lambda: editor), options, None)
        with m:
            if isinstance(c.expect, Exception):
                def check(err):
                    print(err)
                    eq_(str(err), str(c.expect))
                with assert_raises(type(c.expect), msg=check):
                    getattr(finder, c.action)(None)
            else:
                getattr(finder, c.action)(None)
                if c.expect is BEEP:
                    eq_(editor.text[:], c.text)
                else:
                    eq_(editor.text[:], c.expect)
示例#31
0
class TestResolveOGUIDView(MockTestCase, TestCase):

    def setUp(self):
        super(TestResolveOGUIDView, self).setUp()

        self.testcase_mocker = Mocker()
        expect = Expect(self.testcase_mocker)

        sm = getGlobalSiteManager()
        siteroot = self.create_dummy(
            id='siteroot',
            getSiteManager=lambda: sm)
        alsoProvides(siteroot, IPloneSiteRoot)
        setSite(siteroot)

        registry = self.testcase_mocker.mock()
        self.mock_utility(registry, IRegistry)

        proxy = self.create_dummy(client_id='client1')
        expect(registry.forInterface(IClientConfiguration)).result(
            proxy).count(0, None)

        self.testcase_mocker.replay()

    def tearDown(self):
        setSite(None)

        self.testcase_mocker.restore()
        self.testcase_mocker.verify()

    def test_check_permissions_fails_with_nobody(self):
        mtool = self.mocker.mock()
        self.expect(mtool.getAuthenticatedMember()).result(
            SpecialUsers.nobody)
        self.mock_tool(mtool, 'portal_membership')

        self.replay()

        view = ResolveOGUIDView(object(), object())

        with TestCase.assertRaises(self, Unauthorized):
            view._check_permissions(object())


    def test_check_permission_fails_without_view_permission(self):
        obj = self.mocker.mock()

        mtool = self.mocker.mock()
        self.expect(mtool.getAuthenticatedMember().checkPermission(
                'View', obj)).result(False)
        self.mock_tool(mtool, 'portal_membership')

        self.replay()

        view = ResolveOGUIDView(object(), object())

        with TestCase.assertRaises(self, Unauthorized):
            view._check_permissions(obj)

    def test_redirect_to_other_client(self):
        oguid = 'client2:5'
        client2_url = 'http://otherhost/client2'
        target_url = '%s/@@resolve_oguid?oguid=%s' % (client2_url, oguid)

        info = self.mocker.mock()
        self.mock_utility(info, IContactInformation)
        self.expect(info.get_client_by_id('client2').public_url).result(
            client2_url)

        request = self.mocker.mock()
        self.expect(request.get('oguid')).result('client2:5')
        self.expect(request.RESPONSE.redirect(target_url)).result('REDIRECT')

        self.replay()

        view = ResolveOGUIDView(object(), request)
        self.assertEqual(view.render(), 'REDIRECT')

    def test_redirect_if_correct_client(self):
        absolute_url = 'http://anyhost/client1/somedossier'
        obj = self.mocker.mock()
        self.expect(obj.absolute_url()).result(absolute_url)

        context = object()

        request = self.mocker.mock()
        self.expect(request.get('oguid')).result('client1:444')
        self.expect(request.RESPONSE.redirect(absolute_url)).result(
            'redirected')

        intids = self.mocker.mock()
        self.expect(intids.getObject(444)).result(obj)
        self.mock_utility(intids, IIntIds)

        mtool = self.mocker.mock()
        self.expect(mtool.getAuthenticatedMember().checkPermission(
                'View', obj)).result(True)
        self.mock_tool(mtool, 'portal_membership')

        self.replay()

        view = ResolveOGUIDView(context, request)
        self.assertEqual(view.render(), 'redirected')
示例#32
0
def test_requiredThickness():
    m = Mocker()
    lnv = create_lnv()
    m.method(lnv.calculate_thickness)()
    with m:
        lnv.requiredThickness()
示例#33
0
class MiddlewareTests(SettingsMixin, TestCase):
    def setUp(self):
        self.mocker = Mocker()

    def test_valid_login(self):
        authenticator = self.mocker.mock()
        request = self.mocker.mock()
        expect(authenticator.authenticate(request)).result(True)
        with self.mocker:
            self.assertEqual(
                None,
                HttpDigestMiddleware(
                    authenticator=authenticator).process_request(request))

    def test_no_login_and_not_required(self):
        authenticator = self.mocker.mock()
        request = self.mocker.mock()
        expect(authenticator.authenticate(request)).result(False)
        expect(
            authenticator.contains_digest_credentials(request)).result(False)
        with self.mocker:
            self.assertEqual(
                None,
                HttpDigestMiddleware(
                    authenticator=authenticator).process_request(request))

    def test_no_login_and_required(self):
        authenticator = self.mocker.mock(count=False)
        request = self.mocker.mock()
        response = self.mocker.mock()
        expect(authenticator.authenticate(request)).result(False)
        expect(
            authenticator.contains_digest_credentials(request)).result(False)
        expect(authenticator.build_challenge_response()).result(response)
        with self.mocker:
            self.assertEqual(
                response,
                HttpDigestMiddleware(
                    authenticator=authenticator,
                    require_authentication=True).process_request(request))

    def test_process_response_401(self):
        authenticator = self.mocker.mock(count=False)
        request = self.mocker.mock()
        response = self.mocker.mock(count=False)
        challenge_response = self.mocker.mock()
        expect(response.status_code).result(401)
        expect(authenticator.build_challenge_response()).result(
            challenge_response)
        with self.mocker:
            self.assertEqual(
                challenge_response,
                HttpDigestMiddleware(
                    authenticator=authenticator).process_response(
                        request, response))

    def test_process_response_200(self):
        authenticator = self.mocker.mock(count=False)
        request = self.mocker.mock()
        response = self.mocker.mock(count=False)
        expect(response.status_code).result(200)
        with self.mocker:
            self.assertEqual(
                response,
                HttpDigestMiddleware(
                    authenticator=authenticator).process_response(
                        request, response))

    def test_process_response_404(self):
        authenticator = self.mocker.mock(count=False)
        request = self.mocker.mock()
        response = self.mocker.mock(count=False)
        expect(response.status_code).result(404)
        with self.mocker:
            self.assertEqual(
                response,
                HttpDigestMiddleware(
                    authenticator=authenticator).process_response(
                        request, response))
示例#34
0
文件: env.py 项目: yodermk/holland
 def __init__(self):
     self.mocker = Mocker()
     _setup_fileio(self.mocker)
     _setup_mysqlclient(self.mocker)
     _setup_subprocess(self.mocker)
示例#35
0
class TestCustodyPeriod(MockTestCase, TestCase):

    def setUp(self):
        super(TestCustodyPeriod, self).setUp()

        self.testcase_mocker = Mocker()
        grok('opengever.base.behaviors.lifecycle')

        # mock the registry, so that we have a static
        # configuration in our tests. we test functionality,
        # not configuration..
        proxy = self.testcase_mocker.mock()
        proxy.custody_periods
        self.testcase_mocker.result([u'0', u'10', u'20', u'30'])
        self.testcase_mocker.count(0, None)

        registry = self.testcase_mocker.mock()
        provideUtility(provides=IRegistry, component=registry)
        registry.forInterface(IBaseCustodyPeriods)
        self.testcase_mocker.result(proxy)
        self.testcase_mocker.count(0, None)

        # we need to register the vocabulary utility in the
        # vocabulary registry manually at this point:
        vocabulary_registry = getVocabularyRegistry()
        field = lifecycle.ILifeCycle['custody_period']
        try:
            vocabulary_registry.get(None, field.vocabularyName)
        except VocabularyRegistryError:
            factory = getUtility(IVocabularyFactory,
                                 name=u'lifecycle_custody_period_vocabulary')
            vocabulary_registry.register(field.vocabularyName, factory)

        # in this stage, only the grok-components (adapaters, utilities)
        # of the module are registered in the component registry.

        # we need to register any plone.directives.form magic components
        # from the module manually (they are not grokky):
        for factory, name in lifecycle.__form_value_adapters__:
            provideAdapter(factory, name=name)

        self.testcase_mocker.replay()

    def tearDown(self):
        self.testcase_mocker.verify()
        self.testcase_mocker.restore()
        super(TestCustodyPeriod, self).tearDown()

    def _get_term_titles_from_vocabulary(self, voc):
        return [term.title for term in voc._terms]

    def test_configured_field_vocabulary_factory_name(self):
        field = lifecycle.ILifeCycle['custody_period']
        self.assertEqual(field.vocabularyName,
                         u'lifecycle_custody_period_vocabulary')

    def test_vocabulary(self):
        vocfactory = getUtility(IVocabularyFactory,
                                name=u'lifecycle_custody_period_vocabulary')
        self.assertEqual(vocfactory.option_names, [0, 10, 20, 30])

    def test_vocabulary_in_context(self):
        vocfactory = getUtility(IVocabularyFactory,
                                name=u'lifecycle_custody_period_vocabulary')

        request = self.mocker.mock()
        self.expect(request.get('PATH_INFO', ANY)).result('somepath/++add++type')

        context = self.mocker.mock()
        self.expect(context.REQUEST).result(request)
        self.expect(context.custody_period).result(20)

        self.replay()

        vocabulary = vocfactory(context)
        self.assertEqual(sorted(self._get_term_titles_from_vocabulary(vocabulary)),
                         [u'20', u'30'])

    def test_validator(self):
        request = self.mocker.mock()
        self.expect(request.get('PATH_INFO', ANY)).result('somepath/++add++type')

        field = lifecycle.ILifeCycle['custody_period']

        context = None
        view = None
        widget = None

        self.replay()

        validator = getMultiAdapter((context, request, view, field, widget), IValidator)
        validator.validate(20)

        with TestCase.assertRaises(self, ConstraintNotSatisfied):
            validator.validate(15)

    def test_validator_in_context(self):
        request = self.mocker.mock()
        self.expect(request.get('PATH_INFO', ANY)).result(
            'somepath/++add++type').count(0, None)

        context = self.mocker.mock()
        self.expect(context.REQUEST).result(request).count(0, None)
        self.expect(context.custody_period).result(20).count(0, None)
        self.expect(context.aq_inner).result(context).count(0, None)
        self.expect(context.aq_parent).result(None).count(0, None)

        field = lifecycle.ILifeCycle['custody_period']

        view = None
        widget = None

        self.replay()

        validator = getMultiAdapter((context, request, view, field, widget), IValidator)
        validator.validate(20)
        validator.validate(30)

        with TestCase.assertRaises(self, ConstraintNotSatisfied):
            validator.validate(10)

    def test_default_value(self):
        field = lifecycle.ILifeCycle['custody_period']

        portal = self.create_dummy()
        directlyProvides(portal, ISiteRoot)

        default_value = getMultiAdapter(
            (portal,  # context
             None,  # request
             None,  # form
             field,  # field
             None,  # Widget
             ),
            IValue,
            name='default')
        self.assertEqual(default_value.get(), 30)

    def test_default_value_in_context(self):
        field = lifecycle.ILifeCycle['custody_period']

        context = self.create_dummy(custody_period=10)
        directlyProvides(context, lifecycle.ILifeCycle)

        default_value = getMultiAdapter(
            (context,  # context
             None,  # request
             None,  # form
             field,  # field
             None,  # Widget
             ),
            IValue,
            name='default')
        self.assertEqual(default_value.get(), 10)
示例#36
0
 def setUp(self):
     self.mocker = Mocker()
class StatsWorkerTestCase(TestCase):
    """Tests for StatsWorker class."""
    def setUp(self):
        super(StatsWorkerTestCase, self).setUp()
        self.mocker = Mocker()
        self.rpc = self.mocker.mock()
        self.worker = stats_worker.StatsWorker(10, '', self.rpc)

        # logging setup
        self.handler = MementoHandler()
        self.worker.logger.addHandler(self.handler)
        self.addCleanup(self.worker.logger.removeHandler, self.handler)
        self.worker.logger.setLevel(logging.DEBUG)
        self.handler.setLevel(logging.DEBUG)
        self.worker.logger.propagate = False
        self.handler.debug = True

    def test_collect_stats(self):
        """Test the collect_stats method."""
        called = []
        self.worker._collect_process = \
            lambda p, n: called.append(('proc', p, n)) or {}
        self.worker._collect_machine = lambda: called.append('machine') or {}
        processes = [dict(name="bar", group="foo", pid="42", state=RUNNING)]
        expect(self.rpc.supervisor.getAllProcessInfo()).result(processes)
        with self.mocker:
            self.worker.collect_stats()
        self.assertEqual(called, ['machine', ('proc', 42, 'bar')])
        self.assertTrue(self.handler.check_info("Collecting machine stats"))
        self.assertTrue(
            self.handler.check_info("Collecting stats for proc", "pid=42",
                                    "name=bar"))

    def test_collect_stats_not_running(self):
        """Test the collect_stats method if the proccess isn't running."""
        called = []
        self.worker._collect_process = \
            lambda p, n: called.append(('proc', p, n)) or {}
        self.worker._collect_machine = lambda: called.append('machine') or {}
        processes = [dict(name="bar", group="foo", pid="42", state=STARTING)]
        expect(self.rpc.supervisor.getAllProcessInfo()).result(processes)
        with self.mocker:
            self.worker.collect_stats()
        self.assertEqual(called, ['machine'])
        self.assertTrue(self.handler.check_info("Collecting machine stats"))
        self.assertTrue(
            self.handler.check_info("Ignoring process", "pid=42", "name=bar",
                                    "state=%s" % STARTING))

    def test_collect_stats_no_data(self):
        """Test the collect_stats method with no data of a process."""
        called = []
        self.worker._collect_process = \
            lambda p, n: called.append(('proc', p, n)) or {}
        self.worker._collect_machine = lambda: called.append('machine') or {}
        expect(self.rpc.supervisor.getAllProcessInfo()).result([])
        with self.mocker:
            self.worker.collect_stats()
        self.assertEqual(called, ['machine'])
        self.assertTrue(self.handler.check_info("Collecting machine stats"))

    def test_collect_process_info_new_report(self):
        """Check how the process info is collected first time."""
        mocker = Mocker()
        assert not self.worker.process_cache

        # patch Process to return our mock for test pid
        Process = mocker.mock()
        self.patch(stats_worker.psutil, 'Process', Process)
        proc = mocker.mock()
        pid = 1234
        expect(Process(pid)).result(proc)

        # patch ProcessReport to return or mock for given proc
        ProcessReport = mocker.mock()
        self.patch(stats_worker, 'ProcessReport', ProcessReport)
        proc_report = mocker.mock()
        expect(ProcessReport(proc)).result(proc_report)

        # expect to get called with some info, return some results
        name = 'test_proc'
        result = object()
        expect(proc_report.get_memory_and_cpu(prefix=name)).result(result)

        with mocker:
            real = self.worker._collect_process(pid, name)
        self.assertIdentical(real, result)

    def test_collect_process_info_old_report(self):
        """Check how the process info is collected when cached."""
        mocker = Mocker()

        # put it in the cache
        pid = 1234
        proc_report = mocker.mock()
        self.worker.process_cache[pid] = proc_report

        # expect to get called with some info, return some results
        name = 'test_proc'
        result = object()
        expect(proc_report.get_memory_and_cpu(prefix=name)).result(result)

        with mocker:
            real = self.worker._collect_process(pid, name)
        self.assertIdentical(real, result)

    def test_collect_system_info(self):
        """Check how the system info is collected."""
        mocker = Mocker()

        # change the constant to assure it's used as we want
        result1 = dict(a=3, b=5)
        result2 = dict(c=7)
        fake = (lambda: result1, lambda: result2)
        self.patch(stats_worker, 'SYSTEM_STATS', fake)

        with mocker:
            result = self.worker._collect_machine()

        should = {}
        should.update(result1)
        should.update(result2)
        self.assertEqual(result, should)

    def test_informed_metrics(self):
        """Check how stats are reported."""
        # prepare a lot of fake info that will be "collected"
        machine_info = dict(foo=3, bar=5)
        process_info = {
            1: dict(some=1234, other=4567),
            2: dict(some=9876, other=6543),
        }
        self.worker._collect_process = lambda pid, name: process_info[pid]
        self.worker._collect_machine = lambda: machine_info
        processes = [
            dict(name="proc1", group="", pid="1", state=RUNNING),
            dict(name="proc2", group="", pid="2", state=RUNNING),
        ]
        expect(self.rpc.supervisor.getAllProcessInfo()).result(processes)

        # patch the metric reporter to see what is sent
        reported = set()
        self.worker.metrics.gauge = lambda *a: reported.add(a)

        # what we should get is...
        should = set([
            ('foo', 3),
            ('bar', 5),
            ('some', 1234),
            ('other', 4567),
            ('some', 9876),
            ('other', 6543),
        ])
        with self.mocker:
            self.worker.collect_stats()
        self.assertEqual(reported, should)
示例#38
0
class assembler_spec:
    def setUp(self):
        self.mockery = Mocker()
        self.assembler = assembler()
        self.assembler.register(no_deps)
        self.assembler.register(one_dep, requires=[no_deps])
        self.assembler.register(two_deps,
                                requires=[no_deps, one_dep],
                                cacheable=False)

    def should_not_build_objects_for_unregistered_types(self):
        try:
            self.assembler.provide(str)
            assert False
        except ValueError:
            pass

    def should_build_objects_without_dependencies(self):
        instance = self.assembler.provide(no_deps)
        assert type(instance) == no_deps

    def should_build_objects_with_one_dependency(self):
        instance = self.assembler.provide(one_dep)
        assert type(instance) == one_dep
        assert type(instance.dependency) == no_deps

    def should_build_objects_with_a_few_dependencies(self):
        instance = self.assembler.provide(two_deps)
        assert type(instance) == two_deps
        assert type(instance.first_dep) == no_deps
        assert type(instance.second_dep) == one_dep

    def should_build_dependencies_correctly(self):
        instance = self.assembler.provide(two_deps)
        assert type(instance.second_dep) == one_dep
        assert type(instance.second_dep.dependency) == no_deps

    def should_build_objects_without_dependencies_from_factories(self):
        factory = self.mockery.mock()
        expect(factory()).result(12345)
        with self.mockery:
            self.assembler.register(int, requires=[], factory=factory)
            instance = self.assembler.provide(int)
        assert instance == 12345

    def should_build_objects_with_dependencies_from_factories(self):
        factory = self.mockery.mock()
        expect(factory(arg_of_type(no_deps))).result(12345)
        with self.mockery:
            self.assembler.register(int, requires=[no_deps], factory=factory)
            instance = self.assembler.provide(int)
        assert instance == 12345

    def should_add_the_new_instance_to_the_cache(self):
        instance = self.assembler.provide(no_deps)
        assert self.assembler.cache[no_deps] is instance

    def should_not_cache_instances_of_classes_registered_as_uncacheable(self):
        self.assembler.provide(two_deps)
        assert two_deps not in self.assembler.cache

    def should_reuse_cached_instances(self):
        first_instance = self.assembler.provide(no_deps)
        second_instance = self.assembler.provide(no_deps)
        assert second_instance is first_instance

    def should_spawn_child_assemblers(self):
        child_assembler = self.assembler.spawn_child()
        assert child_assembler.parent == self.assembler

    def should_refer_to_parent_assembler_for_building_rules(self):
        child_assembler = self.assembler.spawn_child()
        instance = child_assembler.provide(no_deps)
        assert type(instance) == no_deps

    def should_use_instances_cached_in_parent_assembler(self):
        child_assembler = self.assembler.spawn_child()
        first_instance = self.assembler.provide(no_deps)
        second_instance = child_assembler.provide(no_deps)
        assert second_instance is first_instance

    def should_be_able_to_provide_itself_to_created_objects(self):
        asm = assembler()
        asm.register(one_dep, requires=[assembler])
        instance = asm.provide(one_dep)