コード例 #1
0
ファイル: test_cache.py プロジェクト: roopeshpraj/stubo-app
    def test_new_session_with_state(self):
        scenario_name = 'foo'
        self._make_scenario('localhost:foo')
        from stubo.model.stub import create, Stub, response_hash
        stub = Stub(create('<test>match this</test>', '<test>OK</test>'),
                    'localhost:foo')
        doc = dict(scenario='localhost:foo', stub=stub)
        self.scenario.insert_stub(doc, stateful=True)

        stub2 = Stub(create('<test>match this</test>', '<test>BAD</test>'),
                     'localhost:foo')
        doc2 = dict(scenario='localhost:foo', stub=stub2)
        self.scenario.insert_stub(doc2, stateful=True)

        cache = self._get_cache()
        cache.create_session_cache('foo', 'bar')
        session = self.hash.get('localhost:foo', 'bar')
        self.assertEqual(session["status"], "playback")
        self.assertEqual(session['session'], 'bar')
        self.assertEqual(session["scenario"], "localhost:foo")

        self.assertTrue('stubs' in session)
        stubs = session['stubs']
        self.assertEqual(len(stubs), 1)
        from stubo.model.stub import StubCache
        stub = StubCache(stubs[0], session["scenario"], session['session'])
        responses = stub.response_ids()
        self.assertEqual(len(responses), 2)
        self.assertEqual(stub.contains_matchers(), ["<test>match this</test>"])
        self.assertEqual(responses, [
            response_hash('<test>OK</test>', stub),
            response_hash('<test>BAD</test>', stub2)
        ])
        self.assertEqual(self.hash.get_raw('localhost:sessions', 'bar'), 'foo')
コード例 #2
0
 def test_new_session_with_state(self):
     scenario_name = 'foo'
     self._make_scenario('localhost:foo')
     from stubo.model.stub import create, Stub, response_hash
     stub = Stub(create('<test>match this</test>', '<test>OK</test>'),
                 'localhost:foo')
     doc = dict(scenario='localhost:foo', stub=stub)
     self.scenario.insert_stub(doc, stateful=True)  
     
     stub2 = Stub(create('<test>match this</test>', '<test>BAD</test>'),
                 'localhost:foo')
     doc2 = dict(scenario='localhost:foo', stub=stub2)
     self.scenario.insert_stub(doc2, stateful=True)  
     
     cache = self._get_cache()
     cache.create_session_cache('foo', 'bar')  
     session = self.hash.get('localhost:foo', 'bar') 
     self.assertEqual(session["status"], "playback")
     self.assertEqual(session['session'], 'bar')
     self.assertEqual(session["scenario"], "localhost:foo")
     
     self.assertTrue('stubs' in session)
     stubs = session['stubs']
     self.assertEqual(len(stubs), 1)
     from stubo.model.stub import StubCache
     stub = StubCache(stubs[0], session["scenario"], session['session'])
     responses = stub.response_ids()
     self.assertEqual(len(responses), 2)
     self.assertEqual(stub.contains_matchers(), ["<test>match this</test>"])
     self.assertEqual(responses, [response_hash('<test>OK</test>', stub), 
                                  response_hash('<test>BAD</test>', stub2)])          
     self.assertEqual(self.hash.get_raw('localhost:sessions', 'bar'), 'foo')    
コード例 #3
0
    def test_response_namespace(self):
        from stubo.ext.xmlutils import XMLMangler

        mangler = XMLMangler(elements=dict(a=XPathValue('/path/to/a')))
        response_mangler = XMLMangler(elements=dict(a=XPathValue('//user:response', extractor=lambda x: x.upper())),
                                      copy_attrs_on_match=True,
                                      namespaces=dict(user="******"))

        request = DummyModel(body='<path><to><a>xyz</a></to></path>',
                             headers={})
        from stubo.model.stub import Stub, create

        stub = Stub(create('<path><to><a>xyz</a></to></path>',
                           '<x xmlns:user="******"><user:response>abc</user:response></x>'),
                    "foo")
        from stubo.ext.transformer import StuboTemplateProcessor

        context = dict(stub=stub, template_processor=StuboTemplateProcessor())
        putter = self._make(response_mangler=response_mangler,
                            mangler=mangler, request=StuboRequest(request),
                            context=context)
        putter.doMatcher()
        response = putter.doResponse()
        self.assertEqual(response.stub.payload,
                         {'request': {'bodyPatterns': {'contains': [u'<path><to><a>***</a></to></path>']},
                                      'method': 'POST'},
                          'response': {
                          'body': u'<x xmlns:user="******">'
                                  u'<user:response>ABC</user:response></x>',
                          'status': 200}})
コード例 #4
0
ファイル: test_cache.py プロジェクト: roopeshpraj/stubo-app
    def test_update_dormant_session_with_stubs(self):
        self.hash.set('somehost:foo', 'bar', {
            'status': 'dormant',
            'session': 'bar',
            'scenario': 'localhost:foo'
        })
        scenario_name = 'foo'
        self._make_scenario('localhost:foo')
        from stubo.model.stub import create, Stub, response_hash
        stub = Stub(create('<test>match this</test>', '<test>OK</test>'),
                    'localhost:foo')
        doc = dict(scenario='localhost:foo', stub=stub)
        self.scenario.insert_stub(doc, stateful=True)

        cache = self._get_cache()
        cache.create_session_cache('foo', 'bar')
        session = self.hash.get('localhost:foo', 'bar')
        self.assertEqual(session["status"], "playback")
        self.assertEqual(session['session'], 'bar')
        self.assertEqual(session["scenario"], "localhost:foo")

        self.assertTrue('stubs' in session)
        stubs = session['stubs']
        self.assertEqual(len(stubs), 1)
        from stubo.model.stub import StubCache
        stub = StubCache(stubs[0], session["scenario"], session['session'])
        self.assertEqual(stub.contains_matchers(), ["<test>match this</test>"])
        self.assertEqual(stub.response_ids(),
                         [response_hash('<test>OK</test>', stub)])
コード例 #5
0
ファイル: test_cache.py プロジェクト: rusenask/mirage
    def test_update_dormat_session_with_stubs_and_delay(self):
        self.hash.set('localhost:foo', 'bar', {'status': 'dormant',
                                               'session': 'bar',
                                               'scenario': 'localhost:foo'})
        delay_policy = {"delay_type": "fixed", "name": "slow",
                        "milliseconds": "500"}
        self.hash.set('localhost:delay_policy', 'slow', delay_policy)

        self._make_scenario('localhost:foo')
        from stubo.model.stub import create, Stub

        stub = Stub(create('<test>match this</test>', '<test>OK</test>'),
                    'localhost:foo')
        stub.set_delay_policy('slow')
        doc = dict(scenario='localhost:foo', stub=stub)
        self.scenario.insert_stub(doc, stateful=True)

        self._get_cache().create_session_cache('foo', 'bar')
        session = self.hash.get('localhost:foo', 'bar')
        self.assertTrue('stubs' in session)
        stubs = session['stubs']
        self.assertEqual(len(stubs), 1)
        from stubo.model.stub import StubCache

        stub = StubCache(stubs[0], session["scenario"], session['session'])
        self.assertEqual(stub.delay_policy(), delay_policy)
コード例 #6
0
    def test_update_dormat_session_with_stubs_and_module(self):
        self.hash.set('localhost:foo', 'bar', {
            'status': 'dormant',
            'session': 'bar',
            'scenario': 'localhost:foo'
        })
        module = {"system_date": "2013-09-24", "version": 1, "name": "funcky"}

        self._make_scenario('localhost:foo')
        from stubo.model.stub import create, Stub

        stub = Stub(create('<test>match this</test>', '<test>OK</test>'),
                    'localhost:foo')
        stub.set_module(module)
        doc = dict(scenario='localhost:foo', stub=stub)
        self.scenario.insert_stub(doc, stateful=True)
        self._get_cache().create_session_cache('foo', 'bar')
        session = self.hash.get('localhost:foo', 'bar')
        self.assertTrue('stubs' in session)
        stubs = session['stubs']
        self.assertEqual(len(stubs), 1)
        from stubo.model.stub import StubCache

        stub = StubCache(stubs[0], session["scenario"], session['session'])
        self.assertEqual(stub.module(), module)
コード例 #7
0
ファイル: test_cache.py プロジェクト: roopeshpraj/stubo-app
    def test_update_dormat_session_with_stubs_and_delay(self):
        self.hash.set('localhost:foo', 'bar', {
            'status': 'dormant',
            'session': 'bar',
            'scenario': 'localhost:foo'
        })
        delay_policy = {
            "delay_type": "fixed",
            "name": "slow",
            "milliseconds": "500"
        }
        self.hash.set('localhost:delay_policy', 'slow', delay_policy)

        self._make_scenario('localhost:foo')
        from stubo.model.stub import create, Stub
        stub = Stub(create('<test>match this</test>', '<test>OK</test>'),
                    'localhost:foo')
        stub.set_delay_policy('slow')
        doc = dict(scenario='localhost:foo', stub=stub)
        self.scenario.insert_stub(doc, stateful=True)

        self._get_cache().create_session_cache('foo', 'bar')
        session = self.hash.get('localhost:foo', 'bar')
        self.assertTrue('stubs' in session)
        stubs = session['stubs']
        self.assertEqual(len(stubs), 1)
        from stubo.model.stub import StubCache
        stub = StubCache(stubs[0], session["scenario"], session['session'])
        self.assertEqual(stub.delay_policy(), delay_policy)
コード例 #8
0
    def test_response(self):
        from stubo.ext.xmlutils import XMLMangler
        mangler = XMLMangler(elements=dict(a=XPathValue('/path/to/a')))
        response_mangler = XMLMangler(elements=dict(
            a=XPathValue('/response', extractor=lambda x: x.upper())),
                                      copy_attrs_on_match=True)

        request = DummyModel(body='<path><to><a>xyz</a></to></path>',
                             headers={})
        from stubo.model.stub import Stub, create
        stub = Stub(
            create('<path><to><a>xyz</a></to></path>',
                   '<response>abc</response>'), "foo")
        from stubo.ext.transformer import StuboTemplateProcessor
        context = dict(stub=stub, template_processor=StuboTemplateProcessor())
        putter = self._make(response_mangler=response_mangler,
                            mangler=mangler,
                            request=StuboRequest(request),
                            context=context)
        putter.doMatcher()
        response = putter.doResponse()
        self.assertEqual(
            response.stub.payload, {
                'request': {
                    'bodyPatterns': {
                        'contains': [u'<path><to><a>***</a></to></path>']
                    },
                    'method': 'POST'
                },
                'response': {
                    'body': u'<response>ABC</response>',
                    'status': 200
                }
            })
コード例 #9
0
 def test_update_dormant_session_with_stubs(self):
     self.hash.set('somehost:foo', 'bar', {'status' : 'dormant',
                                           'session' : 'bar',
                                           'scenario' : 'localhost:foo'})
     scenario_name = 'foo'
     self._make_scenario('localhost:foo')
     from stubo.model.stub import create, Stub, response_hash
     stub = Stub(create('<test>match this</test>', '<test>OK</test>'),
                 'localhost:foo')
     doc = dict(scenario='localhost:foo', stub=stub)
     self.scenario.insert_stub(doc, stateful=True)  
     
     cache = self._get_cache()
     cache.create_session_cache('foo', 'bar')  
     session = self.hash.get('localhost:foo', 'bar') 
     self.assertEqual(session["status"], "playback")
     self.assertEqual(session['session'], 'bar')
     self.assertEqual(session["scenario"], "localhost:foo")
     
     self.assertTrue('stubs' in session)
     stubs = session['stubs']
     self.assertEqual(len(stubs), 1)
     from stubo.model.stub import StubCache
     stub = StubCache(stubs[0], session["scenario"], session['session']) 
     self.assertEqual(stub.contains_matchers(), ["<test>match this</test>"])
     self.assertEqual(stub.response_ids(), [response_hash('<test>OK</test>',
                                                          stub)])        
コード例 #10
0
 def test_ctor(self):
     from stubo.ext.xmlutils import XMLMangler
     mangler = XMLMangler(elements=dict(a=XPathValue('/path/to/a')))
     request=DummyModel(body='<path><to><a>xyz</a></to></path>',
                        headers={})
     from stubo.model.stub import Stub, create
     stub = Stub(create('<path><to><a>xyz</a></to></path>',
                         '<response>abc</response>'), "foo")
     from stubo.ext.transformer import StuboTemplateProcessor
     context = dict(stub=stub, template_processor=StuboTemplateProcessor())
     getter = self._make(mangler=mangler, request=StuboRequest(request),
                         context=context)
     self.assertEqual(getter.mangler, mangler) 
コード例 #11
0
ファイル: test_cache.py プロジェクト: roopeshpraj/stubo-app
 def test_request_cache_limit2(self):
     scenario_name = 'foo'
     self._make_scenario('localhost:foo')
     from stubo.model.stub import create, Stub, response_hash
     stub = Stub(create('<test>match this</test>', '<test>OK</test>'),
                 'localhost:foo')
     doc = dict(scenario='localhost:foo', stub=stub)
     self.scenario.insert_stub(doc, stateful=True)
     cache = self._get_cache()
     session = cache.create_session_cache('foo', 'bar')
     self._func(session, stub, request_id='x', response_id=2)
     for i in range(15):
         self._func(session, stub, request_id='{0}'.format(i))
     self.assertEqual(len(self.hash.get_all('localhost:foo:request')), 11)
コード例 #12
0
 def test_request_cache_limit2(self): 
     scenario_name = 'foo'
     self._make_scenario('localhost:foo')
     from stubo.model.stub import create, Stub, response_hash
     stub = Stub(create('<test>match this</test>', '<test>OK</test>'),
                 'localhost:foo')
     doc = dict(scenario='localhost:foo', stub=stub)
     self.scenario.insert_stub(doc, stateful=True)  
     cache = self._get_cache()
     session = cache.create_session_cache('foo', 'bar') 
     self._func(session, stub, request_id='x', response_id=2)  
     for i in range(15):  
         self._func(session, stub, request_id='{0}'.format(i))  
     self.assertEqual(len(self.hash.get_all('localhost:foo:request')), 11)
コード例 #13
0
 def test_it(self):  
     scenario_name = 'foo'
     self._make_scenario('localhost:foo')
     from stubo.model.stub import create, Stub, response_hash
     stub = Stub(create('<test>match this</test>', '<test>OK</test>'),
                 'localhost:foo')
     doc = dict(scenario='localhost:foo', stub=stub)
     self.scenario.insert_stub(doc, stateful=True)  
     cache = self._get_cache()
     session = cache.create_session_cache('foo', 'bar') 
     self._func(session, stub)  
     self.assertEqual(self.hash.get('localhost:foo:request',
         'bar:1'),
        [[u'1'], u'', None, u'2013-09-05', {}, u'12b0a0eced1ec13b53d186be7bd4909fa94d1916cca4daa25bd24d48'])
コード例 #14
0
 def test_matcher_strip_ns(self):
     from stubo.ext.xmlutils import XMLMangler
     mangler = XMLMangler(elements=dict(a=XPathValue('/path/to/a')))
     request=DummyModel(body='<path><to><a>xyz</a></to></path>',
                        headers={})
     from stubo.model.stub import Stub, create
     stub = Stub(create('<path xmlns="http://great.com"><to><a>xyz</a></to></path>',
                         '<response>abc</response>'), "foo")
     from stubo.ext.transformer import StuboTemplateProcessor
     context = dict(stub=stub, template_processor=StuboTemplateProcessor())
     putter = self._make(mangler=mangler, request=StuboRequest(request),
                         context=context)
     result = putter.doMatcher()
     self.assertEqual(result.stub.contains_matchers(),
                      [u'<path><to><a>***</a></to></path>'])    
コード例 #15
0
ファイル: test_cache.py プロジェクト: roopeshpraj/stubo-app
 def test_it(self):
     scenario_name = 'foo'
     self._make_scenario('localhost:foo')
     from stubo.model.stub import create, Stub, response_hash
     stub = Stub(create('<test>match this</test>', '<test>OK</test>'),
                 'localhost:foo')
     doc = dict(scenario='localhost:foo', stub=stub)
     self.scenario.insert_stub(doc, stateful=True)
     cache = self._get_cache()
     session = cache.create_session_cache('foo', 'bar')
     self._func(session, stub)
     self.assertEqual(
         self.hash.get('localhost:foo:request', 'bar:1'),
         [[u'1'], u'', None, u'2013-09-05', {},
          u'12b0a0eced1ec13b53d186be7bd4909fa94d1916cca4daa25bd24d48'])
コード例 #16
0
 def test_ctor(self):
     from stubo.ext.xmlutils import XMLMangler
     mangler = XMLMangler(elements=dict(a=XPathValue('/path/to/a')))
     request = DummyModel(body='<path><to><a>xyz</a></to></path>',
                          headers={})
     from stubo.model.stub import Stub, create
     stub = Stub(
         create('<path><to><a>xyz</a></to></path>',
                '<response>abc</response>'), "foo")
     from stubo.ext.transformer import StuboTemplateProcessor
     context = dict(stub=stub, template_processor=StuboTemplateProcessor())
     getter = self._make(mangler=mangler,
                         request=StuboRequest(request),
                         context=context)
     self.assertEqual(getter.mangler, mangler)
コード例 #17
0
 def test_matcher2(self):
     from stubo.ext.xmlutils import XMLMangler
     mangler = XMLMangler(elements=dict(a=XPathValue('/path/to/a',
                                         extractor=lambda x: x[1:-1])))
     request=DummyModel(body='<path><to><a>xyz</a></to></path>',
                        headers={})
     from stubo.model.stub import Stub, create
     stub = Stub(create('<path><to><a>y</a></to></path>',
                         '<response>abc</response>'), "foo")
     from stubo.ext.transformer import StuboTemplateProcessor
     context = dict(stub=stub, template_processor=StuboTemplateProcessor())
     getter = self._make(mangler=mangler, request=StuboRequest(request),
                         context=context)
     response = getter.doMatcher()
     self.assertEqual(response.stub.contains_matchers(),
                      [u'<path><to><a>y</a></to></path>'])    
コード例 #18
0
 def test_matcher_strip_ns(self):
     from stubo.ext.xmlutils import XMLMangler
     mangler = XMLMangler(elements=dict(a=XPathValue('/path/to/a')))
     request = DummyModel(body='<path><to><a>xyz</a></to></path>',
                          headers={})
     from stubo.model.stub import Stub, create
     stub = Stub(
         create('<path xmlns="http://great.com"><to><a>xyz</a></to></path>',
                '<response>abc</response>'), "foo")
     from stubo.ext.transformer import StuboTemplateProcessor
     context = dict(stub=stub, template_processor=StuboTemplateProcessor())
     putter = self._make(mangler=mangler,
                         request=StuboRequest(request),
                         context=context)
     result = putter.doMatcher()
     self.assertEqual(result.stub.contains_matchers(),
                      [u'<path><to><a>***</a></to></path>'])
コード例 #19
0
 def test_ctor_fails_if_xpath_has_no_extractor(self):
     from stubo.ext.xmlutils import XMLMangler
     mangler = XMLMangler(elements=dict(a=XPathValue('/path/to/a')))
     response_mangler = XMLMangler(elements=dict(a=XPathValue('/response')), 
                                   copy_attrs_on_match=True)  
     
     request=DummyModel(body='<path><to><a>xyz</a></to></path>',
                        headers={})
     from stubo.model.stub import Stub, create
     stub = Stub(create('<path><to><a>xyz</a></to></path>',
                         '<response>abc</response>'), "foo")
     from stubo.ext.transformer import StuboTemplateProcessor
     context = dict(stub=stub, template_processor=StuboTemplateProcessor())
     with self.assertRaises(ValueError):
         self._make(response_mangler=response_mangler,
                         mangler=mangler, request=StuboRequest(request),
                         context=context)
コード例 #20
0
 def test_matcher2(self):
     from stubo.ext.xmlutils import XMLMangler
     mangler = XMLMangler(elements=dict(
         a=XPathValue('/path/to/a', extractor=lambda x: x[1:-1])))
     request = DummyModel(body='<path><to><a>xyz</a></to></path>',
                          headers={})
     from stubo.model.stub import Stub, create
     stub = Stub(
         create('<path><to><a>y</a></to></path>',
                '<response>abc</response>'), "foo")
     from stubo.ext.transformer import StuboTemplateProcessor
     context = dict(stub=stub, template_processor=StuboTemplateProcessor())
     getter = self._make(mangler=mangler,
                         request=StuboRequest(request),
                         context=context)
     response = getter.doMatcher()
     self.assertEqual(response.stub.contains_matchers(),
                      [u'<path><to><a>y</a></to></path>'])
コード例 #21
0
    def test_ctor_fails_if_xpath_has_no_extractor(self):
        from stubo.ext.xmlutils import XMLMangler
        mangler = XMLMangler(elements=dict(a=XPathValue('/path/to/a')))
        response_mangler = XMLMangler(elements=dict(a=XPathValue('/response')),
                                      copy_attrs_on_match=True)

        request = DummyModel(body='<path><to><a>xyz</a></to></path>',
                             headers={})
        from stubo.model.stub import Stub, create
        stub = Stub(
            create('<path><to><a>xyz</a></to></path>',
                   '<response>abc</response>'), "foo")
        from stubo.ext.transformer import StuboTemplateProcessor
        context = dict(stub=stub, template_processor=StuboTemplateProcessor())
        with self.assertRaises(ValueError):
            self._make(response_mangler=response_mangler,
                       mangler=mangler,
                       request=StuboRequest(request),
                       context=context)
コード例 #22
0
 def test_update_dormat_session_with_stubs_and_module(self):
     self.hash.set('localhost:foo', 'bar', {'status' : 'dormant',
                                           'session' : 'bar',
                                           'scenario' : 'localhost:foo'}) 
     module = {"system_date": "2013-09-24", "version": 1, "name": "funcky"}                                  
     
     self._make_scenario('localhost:foo')
     from stubo.model.stub import create, Stub
     stub = Stub(create('<test>match this</test>', '<test>OK</test>'),
                 'localhost:foo')
     stub.set_module(module)
     doc = dict(scenario='localhost:foo', stub=stub)
     self.scenario.insert_stub(doc, stateful=True)  
     self._get_cache().create_session_cache('foo', 'bar')  
     session = self.hash.get('localhost:foo', 'bar') 
     self.assertTrue('stubs' in session)
     stubs = session['stubs']
     self.assertEqual(len(stubs), 1)
     from stubo.model.stub import StubCache
     stub = StubCache(stubs[0], session["scenario"], session['session'])
     self.assertEqual(stub.module(), module)    
コード例 #23
0
    def run_command(self, url):
        data = ''
        log.debug('url.path={0}'.format(url.path))
        cmd_path = url.geturl()
        parent_path = self.location(os.path.dirname(
            self.cmd_file_url))[0] + '/'
        if url.path == 'import/bookmarks':
            loc = parse_qs(url.query).get('location')
            if loc:
                loc = loc[0]
            else:
                raise exception_response(
                    400,
                    title="missing 'location' param executing import/bookmarks"
                )
            target_url = self.location(urljoin(parent_path, loc))[0]
            log.debug('run_command: {0}'.format(target_url))
            import_cmd_url = self.location(
                'stubo/api/import/bookmarks?location={0}'.format(
                    target_url))[0]
            response, _ = UrlFetch().get(import_cmd_url)
            return

        elif url.path == 'put/stub':
            # Note: delay policy is an optional param, the text matchers &
            # response start after the first ","
            query, _, matchers_response = url.query.partition(',')
            query_params = parse_qs(query)
            delist_arguments(query_params)
            if 'session' not in query_params:
                raise exception_response(400,
                                         title="Missing 'session' param in"
                                         " query: {0}".format(url.query))
            matchers_response = u''.join(matchers_response.split()).strip()
            matchers_response = matchers_response.split(',')
            response_fname = matchers_response[-1].strip()
            matchers = matchers_response[:-1]
            request_matchers = []
            for matcher in matchers:
                if matcher[:4] == 'url=':
                    matcher_data_url = matcher[4:]
                    matcher_text, _ = UrlFetch().get(matcher_data_url)
                elif matcher[:5] == 'text=':
                    matcher_text = matcher[5:]
                else:
                    matcher_data_url = urljoin(parent_path, matcher)
                    matcher_text, _ = UrlFetch().get(matcher_data_url)
                request_matchers.append(matcher_text)

            if response_fname[:4] == 'url=':
                response_data_url = response_fname[4:]
                response_text, _ = UrlFetch().get(response_data_url)
            elif response_fname[:5] == 'text=':
                response_text = response_fname[5:]
            else:
                response_data_url = urljoin(parent_path, response_fname)
                response_text, _ = UrlFetch().get(response_data_url)

            if not response_text:
                raise exception_response(
                    400, title="put/stub response text can not be empty.")

            stub_payload = create(request_matchers, response_text)
            cmd_path = url.path + '?{0}'.format(urlencode(query_params))
            url = self.location(urljoin(api_base, cmd_path))[0]
            log.debug(u'run_command: {0}'.format(url))
            UrlFetch().post(url, data=None, json=stub_payload)
            return

        elif url.path == 'get/response':
            # get/response?session=foo_1, my.request
            query, _, request_fname = url.query.partition(',')
            query_params = parse_qs(query)
            if 'session' not in query_params:
                raise exception_response(400,
                                         title="Missing 'session' param in"
                                         " query: {0}".format(url.query))
            request_fname = request_fname.strip()

            if request_fname[:4] == 'url=':
                request_data_url = request_fname[4:]
                request_text, _ = UrlFetch().get(request_data_url)
            elif request_fname[:5] == 'text=':
                request_text = request_fname[5:]
            else:
                request_data_url = urljoin(parent_path, request_fname)
                request_text, _ = UrlFetch().get(request_data_url)
            data = request_text
            cmd_path = url.path + '?{0}'.format(query)

        elif url.path == 'put/delay_policy':
            url = self.location(urljoin(api_base, cmd_path))[0]
            log.debug('run_command: {0}, data={1}'.format(url, data))
            response, _ = UrlFetch().get(url)
            return

        url = self.location(urljoin(api_base, cmd_path))[0]
        log.debug(u'run_command: {0}'.format(url))
        encoded_data = data.encode('utf-8')
        UrlFetch().post(url, data=encoded_data)
コード例 #24
0
ファイル: cmds.py プロジェクト: ocoperations/stubo-app
    def run_command(self, url, priority):
        data = ''
        log.debug('url.path={0}'.format(url.path))
        cmd_path = url.geturl()
        parent_path = self.location(os.path.dirname(self.cmd_file_url))[0] + '/'
        if url.path == 'import/bookmarks':
            loc = parse_qs(url.query).get('location')
            if loc:
                loc = loc[0]
            else:
                raise exception_response(400,
                                         title="missing 'location' param executing import/bookmarks")
            target_url = self.location(urljoin(parent_path, loc))[0]
            log.debug('run_command: {0}'.format(target_url))
            import_cmd_url = self.location(
                'stubo/api/import/bookmarks?location={0}'.format(target_url))[0]
            response, _, status_code = UrlFetch().get(import_cmd_url)
            return status_code

        elif url.path == 'put/stub':
            # Note: delay policy is an optional param, the text matchers & 
            # response start after the first ","
            query, _, matchers_response = url.query.partition(',')
            query_params = parse_qs(query)
            delist_arguments(query_params)
            if 'session' not in query_params:
                raise exception_response(400, title="Missing 'session' param in"
                                                    " query: {0}".format(url.query))
            if 'priority' not in query_params:
                query_params['priority'] = priority
            matchers_response = u''.join(matchers_response.split()).strip()
            matchers_response = matchers_response.split(',')
            response_fname = matchers_response[-1].strip()
            matchers = matchers_response[:-1]
            request_matchers = []
            for matcher in matchers:
                if matcher[:4] == 'url=':
                    matcher_data_url = matcher[4:]
                    matcher_text, _, _ = UrlFetch().get(matcher_data_url)
                elif matcher[:5] == 'text=':
                    matcher_text = matcher[5:]
                else:
                    matcher_data_url = urljoin(parent_path, matcher)
                    matcher_text, _, _ = UrlFetch().get(matcher_data_url)
                request_matchers.append(matcher_text)

            if response_fname[:4] == 'url=':
                response_data_url = response_fname[4:]
                response_text, _, _ = UrlFetch().get(response_data_url)
            elif response_fname[:5] == 'text=':
                response_text = response_fname[5:]
            else:
                response_data_url = urljoin(parent_path, response_fname)
                response_text, hdrs, _ = UrlFetch().get(response_data_url)
                if 'application/json' in hdrs["Content-Type"]:
                    try:
                        response_text = json.dumps(response_text)
                    except Exception:
                        pass

            if not response_text:
                raise exception_response(400,
                                         title="put/stub response text can not be empty.")

            stub_payload = create(request_matchers, response_text)
            cmd_path = url.path + '?{0}'.format(urlencode(query_params))
            url = self.get_url(cmd_path)
            log.debug(u'run_command: {0}'.format(url))
            response = UrlFetch().post(url, data=None, json=stub_payload)
            return response.status_code

        elif url.path == 'get/response':
            # get/response?session=foo_1, my.request
            query, _, request_fname = url.query.partition(',')
            query_params = parse_qs(query)
            if 'session' not in query_params:
                raise exception_response(400, title="Missing 'session' param in"
                                                    " query: {0}".format(url.query))
            request_fname, _, header_args = request_fname.partition(',')
            request_fname = request_fname.strip()

            if request_fname[:4] == 'url=':
                request_data_url = request_fname[4:]
                request_text, _, _ = UrlFetch().get(request_data_url)
            elif request_fname[:5] == 'text=':
                request_text = request_fname[5:]
            else:
                request_data_url = urljoin(parent_path, request_fname)
                request_text, _, _ = UrlFetch().get(request_data_url)
            data = request_text
            cmd_path = url.path + '?{0}'.format(query)
            url = self.get_url(cmd_path)
            log.debug(u'run_command: {0}'.format(url))
            if isinstance(data, dict):
                # payload is json
                encoded_data = json.dumps(data)
            else:
                encoded_data = data.encode('utf-8')
            headers = {'Stubo-Request-Method': 'POST'}
            if header_args:
                headers.update(dict(x.split('=') for x in header_args.split(',')))
            response = UrlFetch().post(url, data=encoded_data, headers=headers)
            return response.status_code

        elif url.path == 'put/delay_policy':
            url = self.get_url(cmd_path)
            log.debug('run_command: {0}, data={1}'.format(url, data))
            _, _, status_code = UrlFetch().get(url)
            return status_code

        url = self.get_url(cmd_path)
        log.debug(u'run_command: {0}'.format(url))
        encoded_data = data.encode('utf-8')
        response = UrlFetch().post(url, data=encoded_data)
        return response.status_code
コード例 #25
0
ファイル: cmds.py プロジェクト: roopeshpraj/stubo-app
    def run_command(self, url, priority):
        data = ''
        log.debug('url.path={0}'.format(url.path))
        cmd_path = url.geturl()
        parent_path = self.location(os.path.dirname(
            self.cmd_file_url))[0] + '/'
        if url.path == 'import/bookmarks':
            loc = parse_qs(url.query).get('location')
            if loc:
                loc = loc[0]
            else:
                raise exception_response(
                    400,
                    title="missing 'location' param executing import/bookmarks"
                )
            target_url = self.location(urljoin(parent_path, loc))[0]
            log.debug('run_command: {0}'.format(target_url))
            import_cmd_url = self.location(
                'stubo/api/import/bookmarks?location={0}'.format(
                    target_url))[0]
            response, _, status_code = UrlFetch().get(import_cmd_url)
            return status_code

        elif url.path == 'put/stub':
            # Note: delay policy is an optional param, the text matchers &
            # response start after the first ","
            query, _, matchers_response = url.query.partition(',')
            query_params = parse_qs(query)
            delist_arguments(query_params)
            if 'session' not in query_params:
                raise exception_response(400,
                                         title="Missing 'session' param in"
                                         " query: {0}".format(url.query))
            if 'priority' not in query_params:
                query_params['priority'] = priority
            matchers_response = u''.join(matchers_response.split()).strip()
            matchers_response = matchers_response.split(',')
            response_fname = matchers_response[-1].strip()
            matchers = matchers_response[:-1]
            request_matchers = []
            for matcher in matchers:
                if matcher[:4] == 'url=':
                    matcher_data_url = matcher[4:]
                    matcher_text, _, _ = UrlFetch().get(matcher_data_url)
                elif matcher[:5] == 'text=':
                    matcher_text = matcher[5:]
                else:
                    matcher_data_url = urljoin(parent_path, matcher)
                    matcher_text, _, _ = UrlFetch().get(matcher_data_url)
                request_matchers.append(matcher_text)

            if response_fname[:4] == 'url=':
                response_data_url = response_fname[4:]
                response_text, _, _ = UrlFetch().get(response_data_url)
            elif response_fname[:5] == 'text=':
                response_text = response_fname[5:]
            else:
                response_data_url = urljoin(parent_path, response_fname)
                response_text, hdrs, _ = UrlFetch().get(response_data_url)
                if 'application/json' in hdrs["Content-Type"]:
                    try:
                        response_text = json.dumps(response_text)
                    except Exception:
                        pass

            if not response_text:
                raise exception_response(
                    400, title="put/stub response text can not be empty.")

            stub_payload = create(request_matchers, response_text)
            cmd_path = url.path + '?{0}'.format(urlencode(query_params))
            url = self.get_url(cmd_path)
            log.debug(u'run_command: {0}'.format(url))
            response = UrlFetch().post(url, data=None, json=stub_payload)
            return response.status_code

        elif url.path == 'get/response':
            # get/response?session=foo_1, my.request
            query, _, request_fname = url.query.partition(',')
            query_params = parse_qs(query)
            if 'session' not in query_params:
                raise exception_response(400,
                                         title="Missing 'session' param in"
                                         " query: {0}".format(url.query))
            request_fname, _, header_args = request_fname.partition(',')
            request_fname = request_fname.strip()

            if request_fname[:4] == 'url=':
                request_data_url = request_fname[4:]
                request_text, _, _ = UrlFetch().get(request_data_url)
            elif request_fname[:5] == 'text=':
                request_text = request_fname[5:]
            else:
                request_data_url = urljoin(parent_path, request_fname)
                request_text, _, _ = UrlFetch().get(request_data_url)
            data = request_text
            cmd_path = url.path + '?{0}'.format(query)
            url = self.get_url(cmd_path)
            log.debug(u'run_command: {0}'.format(url))
            if isinstance(data, dict):
                # payload is json
                encoded_data = json.dumps(data)
            else:
                encoded_data = data.encode('utf-8')
            headers = {'Stubo-Request-Method': 'POST'}
            if header_args:
                headers.update(
                    dict(x.split('=') for x in header_args.split(',')))
            response = UrlFetch().post(url, data=encoded_data, headers=headers)
            return response.status_code

        elif url.path == 'put/delay_policy':
            url = self.get_url(cmd_path)
            log.debug('run_command: {0}, data={1}'.format(url, data))
            _, _, status_code = UrlFetch().get(url)
            return status_code

        url = self.get_url(cmd_path)
        log.debug(u'run_command: {0}'.format(url))
        encoded_data = data.encode('utf-8')
        response = UrlFetch().post(url, data=encoded_data)
        return response.status_code