Esempio n. 1
0
 def test_match_eval_error(self):
     from stubo.match import match
     from stubo.utils.track import TrackTrace
     trace = TrackTrace(DummyModel(tracking_level='normal'), 'matcher')
     session = {
         "session":
         "first_2",
         "scenario":
         "localhost:first",
         'status':
         'playback',
         "system_date":
         "2013-09-05",
         'stubs': [{
             "matchers": ["{{"],
             "recorded": "2013-09-05",
             "response_id": 5,
             "module": {
                 "system_date": "2013-08-07",
                 "version": 1,
                 "name": "dummy"
             },
         }]
     }
     from stubo.exceptions import HTTPClientError
     from stubo.model.request import StuboRequest
     request = StuboRequest(DummyModel(body='xxx', headers={}))
     from stubo.ext.transformer import StuboDefaultHooks
     url_args = {}
     with self.assertRaises(HTTPClientError):
         match(request, session, trace, session.get('system_date'),
               url_args, StuboDefaultHooks(), None)
Esempio n. 2
0
 def test_raise_on_error_stubo_error(self):
     from stubo.exceptions import HTTPClientError
     fetcher = self._make()
     response = DummyModel(status_code=405, reason="Unknown")
     response.json = lambda : {'error' : 
         {u'message': 'something went wrong', 'code' : 405}}
     with self.assertRaises(HTTPClientError):
         fetcher.raise_on_error(response, "/some/url")     
Esempio n. 3
0
    def test_raise_on_error_stubo_error(self):
        from stubo.exceptions import HTTPClientError

        fetcher = self._make()
        response = DummyModel(status_code=405, reason="Unknown")
        response.json = lambda: {'error': {u'message': 'something went wrong', 'code': 405}}
        with self.assertRaises(HTTPClientError):
            fetcher.raise_on_error(response, "/some/url")
Esempio n. 4
0
    def post(self, url, data=None, json=None, **kwargs):
        if url == 'get/response/cantfindthis':
            return DummyModel(status_code=400, content='E017')

        self.posts.append((url, data or json))
        return DummyModel(status_code=200, raise_for_status=lambda: 1,
                          headers={"Content-Type": 'application/json; charset=UTF-8'},
                          json=lambda: "")
Esempio n. 5
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
                }
            })
Esempio n. 6
0
    def test_raise_on_error_file_not_found(self):
        from stubo.exceptions import HTTPClientError

        fetcher = self._make()
        response = DummyModel(status_code=404, reason="file not found")
        with self.assertRaises(HTTPClientError):
            fetcher.raise_on_error(response, "/some/url")
Esempio n. 7
0
    def test_raise_on_error_unexpected_error(self):
        from stubo.exceptions import HTTPServerError

        fetcher = self._make()
        response = DummyModel(status_code=501, reason="Unknown")
        with self.assertRaises(HTTPServerError):
            fetcher.raise_on_error(response, "/some/url")
Esempio n. 8
0
 def _get_best_match(self, request_text, session, trace=None,
                     system_date=None,
                     url_args=None, 
                     module_system_date=None): 
     from stubo.match import match
     from stubo.utils.track import TrackTrace
     trace = trace or TrackTrace(DummyModel(tracking_level='normal'), 
                                 'matcher')
     from stubo.model.request import StuboRequest
     request = StuboRequest(DummyModel(body=request_text, headers={'Stubo-Request-Method' : 'POST'}))
     url_args = url_args or {}
     from stubo.ext.transformer import StuboDefaultHooks
     return match(request, session, trace, system_date, 
                  url_args,
                  StuboDefaultHooks(),
                  module_system_date=module_system_date)   
Esempio n. 9
0
 def get(self, url):
     if 'stubo/api/put/delay_policy' in url:
         # special case as this is not implemented as a HTTP GET
         return self.post(url,"")
     import os.path
     url = os.path.basename(url)
     response = DummyModel(headers={})
     if url in globals().keys():  
         response.content = globals()[url]
         response.status_code = 200
         response.headers = {"Content-Type" : 'text/html; charset=UTF-8'}
         if url == 'content_not_json_1':
             response.encoding = 'utf8'
             response.text = response.content
         elif url in ('content_not_json_2', 'content_not_json_3'):
             response.encoding = ""       
         else:
             response.headers["Content-Type"] = 'application/json; charset=UTF-8'
             response.json = lambda: response.content                  
     else:      
         response.status_code = 404
     return response
Esempio n. 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)
Esempio n. 11
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>'])
Esempio n. 12
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>'])
Esempio n. 13
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)
Esempio n. 14
0
def manage_request_api(handler):
    cache = Cache(get_hostname(handler.request))
    action = handler.get_argument('action', None)
    all_hosts = asbool(handler.get_argument("all_hosts", False))
    message = error_message = ""
    module_info = {}
    if action is not None:
        # handle btn action
        try:
            name = handler.get_argument('name')
            # It would be nice to really track these actions
            handler.track = DummyModel()
            if action == 'delete':
                _type = handler.get_argument('type')
                if _type == 'module':
                    result = delete_module(handler.request, [name])
                elif _type == 'delay_policy':
                    result = delete_delay_policy(handler, [name])
                elif _type == 'stubs':
                    result = delete_stubs(handler,
                                          scenario_name=name,
                                          host=all_hosts)
                else:
                    result = 'error: unexpected action type={0}'.format(_type)
            elif action == 'end_session':
                result = end_session(handler, name)
            elif action == 'end_sessions':
                result = end_sessions(handler, name)
            else:
                result = 'error: unexpected action={0}'.format(action)

            if 'error' not in result:
                message = result
            else:
                error_message = result
        except MissingArgumentError, e:
            error_message = "Error: {0}".format(e)
        except StuboException, e:
            error_message = "Error: {0}".format(e.title)
Esempio n. 15
0
def command_handler_form_request(handler):
    cmds = handler.get_argument('cmds', None)
    cmd_file_url = handler.get_argument('cmdfile', None)
    if not (cmds or cmd_file_url):
        # TODO: use form validation instead
        raise exception_response(
            400, title="'cmds' or 'cmdFile' parameter not supplied.")

    log.debug(u'command_handler_form_request: cmd_file={0},cmds={1}'.format(
        cmd_file_url, cmds))
    if cmd_file_url:
        request = DummyModel(protocol=handler.request.protocol,
                             host=handler.request.host,
                             arguments=handler.request.arguments)
        response = run_command_file(cmd_file_url, request,
                                    handler.settings['static_path'])
    elif cmds:
        response = run_commands(handler, cmds)
    return handler.render_string(
        "commands.html",
        page_title='Commands',
        executed=response['data'].get('executed_commands'))
Esempio n. 16
0
    def post(self):
        stubo_response = dict(version=version)
        try:
            executor = self.settings['process_executor']
            cmd_file_url = self.get_argument('cmdfile', None)
            if not cmd_file_url:
                # LEGACY
                cmd_file_url = self.get_argument('cmdFile', None)
            if not cmd_file_url:
                raise exception_response(
                    400, title="'cmdfile' parameter not supplied.")

            request = DummyModel(protocol=self.request.protocol,
                                 host=self.request.host,
                                 arguments=self.request.arguments)
            stubo_response = yield executor.submit(
                command_handler_request, cmd_file_url, request,
                self.settings['static_path'])
        except StuboException, err:
            stubo_response['error'] = dict(code=err.code, message=err.title)
            if hasattr(err, 'traceback'):
                stubo_response['error']['traceback'] = err.traceback
            self.set_status(err.code)
Esempio n. 17
0
 def _make(self):
     from stubo.match import StubMatcher
     from stubo.utils.track import TrackTrace
     return StubMatcher(TrackTrace(DummyModel(tracking_level='full'), 
                                   'matcher'))
Esempio n. 18
0
 def get_stubo_request(self, body=None, **kwargs):
     from stubo.model.request import StuboRequest
     from stubo.testing import DummyModel
     request = DummyModel(body=body or '', headers=dict(**kwargs))
     return StuboRequest(request)
Esempio n. 19
0
    def export_playback(self, host, export_payload, files, session,
                        playback_session):
        playback_payload = export_payload['playback']
        scenario_name = playback_payload['scenario']
        scenario = u'{0}:{1}'.format(host, scenario_name)
        runnable_info = dict()
        tracker = Tracker()
        last_used = tracker.session_last_used(scenario, playback_session,
                                              'playback')
        if not last_used:
            raise exception_response(400,
                                     title="Unable to find playback session")
        runnable_info['last_used'] = dict(remote_ip=last_used['remote_ip'],
                                          start_time=str(
                                              last_used['start_time']))
        playback = tracker.get_last_playback(scenario_name, playback_session,
                                             last_used['start_time'])
        playback = list(playback)
        if not playback:
            raise exception_response(
                400,
                title=
                "Unable to find a playback for scenario='{0}', playback_session='{1}'"
                .format(scenario_name, playback_session))

        number_of_requests = len(playback)
        runnable_info['number_of_playback_requests'] = number_of_requests
        for nrequest in range(number_of_requests):
            track = playback[nrequest]
            request_text = track.get('request_text')
            if not request_text:
                raise exception_response(
                    400,
                    title=
                    'Unable to obtain playback details, was full tracking enabled?'
                )
            stubo_request = StuboRequest(
                DummyModel(headers=track.get('request_headers'),
                           body=request_text))
            vars = track.get('request_params')
            vars.pop('session', None)
            vars.pop('scenario', None)
            request_payload = dict(body=stubo_request.body,
                                   method=stubo_request.method,
                                   host=stubo_request.host,
                                   uri=stubo_request.uri,
                                   path=stubo_request.path,
                                   query=stubo_request.query,
                                   headers=stubo_request.headers)

            request_file_name = '{0}_{1}.request'.format(session, nrequest)
            files.append(
                (request_file_name, json.dumps(request_payload, indent=3)))
            # export a response for comparison
            stubo_response_text = track['stubo_response']
            if not isinstance(stubo_response_text, basestring):
                stubo_response_text = unicode(stubo_response_text)
            response_payload = dict(status=track.get('return_code'),
                                    body=stubo_response_text,
                                    headers=track.get('response_headers'))

            stubo_response_file_name = '{0}_{1}.stubo_response'.format(
                session, nrequest)
            playback_payload['requests'].append(
                dict(file=request_file_name,
                     vars=vars,
                     response=stubo_response_file_name))
            files.append((stubo_response_file_name,
                          json.dumps(response_payload, indent=3)))
        return runnable_info
Esempio n. 20
0
 def test_raise_on_error_ok(self):
     fetcher = self._make()
     response = DummyModel(status_code=200)
     fetcher.raise_on_error(response, "/some/url")
Esempio n. 21
0
    def _make(self, protocol='http', host='localhost:8001'):
        from stubo.model.importer import UriLocation

        return UriLocation(DummyModel(protocol=protocol, host=host))
Esempio n. 22
0
    def get(self, url, verify=False):
        if 'stubo/api/put/delay_policy' in url:
            # special case as this is not implemented as a HTTP GET
            return self.post(url, "")
        import os.path

        url = os.path.basename(url)
        response = DummyModel(headers={})
        if url in globals().keys():
            response.content = globals()[url]
            response.status_code = 200
            response.headers = {"Content-Type": 'text/html; charset=UTF-8'}
            if url == 'content_not_json_1':
                response.encoding = 'utf8'
                response.text = response.content
            elif url in ('content_not_json_2', 'content_not_json_3'):
                response.encoding = ""
            else:
                response.headers[
                    "Content-Type"] = 'application/json; charset=UTF-8'
                response.json = lambda: response.content
        else:
            response.status_code = 404
        return response