Ejemplo n.º 1
0
class CountriesTests(unittest.TestCase):
	def setUp(self):
		middleware = []
		self.testApp = TestApp(app.wsgifunc(*middleware))
		
	def test_Countries(self):
		countries = Countries.find(lambda c: True)
		with_code = [country for country in countries if country['code']]
		self.assertTrue(len(with_code)/float(len(countries)) > 0.67)
		
	def test_GetWithNoParams(self):
		r = self.testApp.get('/countries/')
		self.assertEqual(r.status, 200)
		countries = json.loads(r.body)
		self.assertListEqual(countries, Countries.find(lambda c: True))
		
	def test_GetCountriesByContinent(self):
		r = self.testApp.get('/continents/')
		self.assertEqual(r.status, 200)
		continents = json.loads(r.body)
		for continent in continents:
			r = self.testApp.get('/countries/%s' % continent['code'])
			actualCountries = [c for c in Countries._countries if c['continent'] == continent['code']]
			self.assertEqual(r.status, 200)
			responseCountries = json.loads(r.body)
			self.assertListEqual(responseCountries, actualCountries)
Ejemplo n.º 2
0
 def test_userpass_success(self):
     """AUTHENTICATION (REST): Username and password (correct credentials)."""
     mw = []
     headers = {'X-Rucio-Account': 'root', 'X-Rucio-Username': '******', 'X-Rucio-Password': '******'}
     r = TestApp(app.wsgifunc(*mw)).get('/userpass', headers=headers, expect_errors=True)
     assert_equal(r.status, 200)
     assert_greater(len(r.header('X-Rucio-Auth-Token')), 32)
class TestAuthenticateFormDecorator(TestWSGIController):
    def setUp(self):
        TestWSGIController.setUp(self)
        app = ControllerWrap(ProtectedController)
        app = SetupCacheGlobal(app, self.environ, setup_session=True)
        app = SessionMiddleware(app, {}, data_dir=session_dir)
        app = RegistryManager(app)
        self.app = TestApp(app)

    def test_unauthenticated(self):
        self.environ["pylons.routes_dict"]["action"] = "protected"
        response = self.app.post("/protected", extra_environ=self.environ, expect_errors=True)
        assert response.status == 403
        assert csrf_detected_message in response

    def test_authenticated(self):
        self.environ["pylons.routes_dict"]["action"] = "form"
        response = self.app.get("/form", extra_environ=self.environ)
        token = response.body

        self.environ["pylons.routes_dict"]["action"] = "protected"
        response = self.app.post(
            "/protected", params={secure_form_tag.token_key: token}, extra_environ=self.environ, expect_errors=True
        )
        assert "Authenticated" in response
Ejemplo n.º 4
0
class TestFilteredWSGI(TestWSGIController):
    def __init__(self, *args, **kargs):
        TestWSGIController.__init__(self, *args, **kargs)
        self.baseenviron = {}
        app = ControllerWrap(FilteredWSGIController)
        app = self.sap = SetupCacheGlobal(app, self.baseenviron)
        app = RegistryManager(app)
        self.app = TestApp(app)
        
    def setUp(self):
        TestWSGIController.setUp(self)
        self.baseenviron.update(self.environ)
    
    def test_before(self):
        resp = self.get_response(action='index')
        assert 'hi' in resp
        assert 'before is 1' in resp

    def test_after_response(self):
        resp = self.get_response(action='after_response')
        assert 'hi from __after__' in resp

    def test_after_string_response(self):
        resp = self.get_response(action='after_string_response')
        assert 'hello from __after__' in resp

    def test_start_response(self):
        self.baseenviron['pylons.routes_dict']['action'] = 'start_response'
        self.app.get('/', status=404)
Ejemplo n.º 5
0
    def test_put_with_data(self, logging_info):
        # what the middleware app does is that it creates a class based on
        # another and sets an attribute called `cls`
        class MadeUp(middleware_app.ImplementationWrapper):
            cls = AuxImplementation4
            all_services = {}

        config = DotDict(
            logger=logging,
            web_server=DotDict(
                ip_address='127.0.0.1',
                port='88888'
            )
        )

        server = CherryPy(config, (
            ('/aux/(.*)', MadeUp),
        ))

        testapp = TestApp(server._wsgi_func)
        response = testapp.put('/aux/', params={'add': 1})
        eq_(response.status, 200)
        eq_(json.loads(response.body), {'age': 101})

        logging_info.assert_called_with('Running AuxImplementation4')
Ejemplo n.º 6
0
    def test_normal_post(self):
        middleware = []
        testApp = TestApp(app.wsgifunc(*middleware))

        r = testApp.post('/add_comment', params=self.correct_comment_params)
        assert_equal(r.status, 200)
        r.mustcontain("Thank you for your comment")
Ejemplo n.º 7
0
    def test_list_scope(self):
        """ SCOPE (REST): send a GET list all scopes for one account """
        mw = []

        headers1 = {'X-Rucio-Account': 'root', 'X-Rucio-Username': '******', 'X-Rucio-Password': '******'}
        r1 = TestApp(auth_app.wsgifunc(*mw)).get('/userpass', headers=headers1, expect_errors=True)
        assert_equal(r1.status, 200)

        token = str(r1.header('X-Rucio-Auth-Token'))

        tmp_val = account_name_generator()
        headers2 = {'Rucio-Type': 'user', 'X-Rucio-Account': 'root', 'X-Rucio-Auth-Token': str(token)}
        data = dumps({'type': 'USER'})
        r2 = TestApp(account_app.wsgifunc(*mw)).post('/%s' % tmp_val, headers=headers2, params=data, expect_errors=True)
        assert_equal(r2.status, 201)

        headers3 = {'X-Rucio-Auth-Token': str(token)}

        for scope in self.scopes:
            data = dumps({})
            r3 = TestApp(account_app.wsgifunc(*mw)).post('/%s/scopes/%s' % (tmp_val, scope), headers=headers3, params=data, expect_errors=True)
            assert_equal(r3.status, 201)

        r4 = TestApp(account_app.wsgifunc(*mw)).get('/%s/scopes/' % tmp_val, headers=headers3, expect_errors=True)

        assert_equal(r4.status, 200)

        svr_list = loads(r4.body)
        for scope in self.scopes:
            assert_in(scope, svr_list)
Ejemplo n.º 8
0
    def test_basic_get(self, logging_info):

        config_ = DotDict(
            logger=logging,
            web_server=DotDict(
                ip_address='127.0.0.1',
                port='88888'
            )
        )

        # what the middleware app does is that it creates a class based on
        # another and sets an attribute called `cls`
        class MadeUp(middleware_app.MeasuringImplementationWrapper):
            cls = AuxImplementation1
            all_services = {}
            config = config_

        server = CherryPy(config_, (
            ('/aux/(.*)', MadeUp),
        ))

        testapp = TestApp(server._wsgi_func)
        response = testapp.get('/aux/', params={'add': 1})
        eq_(response.status, 200)
        for call in logging_info.call_args_list:
            # mock calls are funny
            args = call[0]
            arg = args[0]
            if re.findall('measuringmiddleware:[\d\.]+\t/aux/\t\?add=1', arg):
                break
        else:
            raise AssertionError('call never found')
Ejemplo n.º 9
0
class TestFilteredWSGI(TestWSGIController):
    def __init__(self, *args, **kargs):
        TestWSGIController.__init__(self, *args, **kargs)
        self.baseenviron = {}
        app = ControllerWrap(FilteredWSGIController)
        app = self.sap = SetupCacheGlobal(app, self.baseenviron)
        app = RegistryManager(app)
        self.app = TestApp(app)

    def setUp(self):
        TestWSGIController.setUp(self)
        self.baseenviron.update(self.environ)

    def test_before(self):
        resp = self.get_response(action="index")
        assert "hi" in resp
        assert "before is 1" in resp

    def test_after_response(self):
        resp = self.get_response(action="after_response")
        assert "hi from __after__" in resp

    def test_after_string_response(self):
        resp = self.get_response(action="after_string_response")
        assert "hello from __after__" in resp

    def test_start_response(self):
        self.baseenviron["pylons.routes_dict"]["action"] = "start_response"
        self.app.get("/", status=404)
Ejemplo n.º 10
0
    def test_create_and_update_and_list_subscription(self):
        """ SUBSCRIPTION (REST): Test the creation of a new subscription, update it, list it """
        mw = []

        headers1 = {'X-Rucio-Account': 'root', 'X-Rucio-Username': '******', 'X-Rucio-Password': '******'}
        r1 = TestApp(auth_app.wsgifunc(*mw)).get('/userpass', headers=headers1, expect_errors=True)

        assert_equal(r1.status, 200)
        token = str(r1.header('X-Rucio-Auth-Token'))

        subscription_name = uuid()
        headers2 = {'X-Rucio-Auth-Token': str(token)}
        data = dumps({'name': subscription_name, 'filter': {'project': ['data12_900GeV', 'data12_8TeV', 'data13_900GeV', 'data13_8TeV'], 'datatype': ['AOD', ], 'excluded_pattern':
                     '(_tid|physics_(Muons|JetTauEtmiss|Egamma)\..*\.ESD|express_express(?!.*NTUP|.*\.ESD|.*RAW)|(physics|express)(?!.*NTUP).* \
                     \.x|physics_WarmStart|calibration(?!_PixelBeam.merge.(NTUP_IDVTXLUMI|AOD))|merge.HIST|NTUP_MUONCALIB|NTUP_TRIG)', 'account': 'tier0'},
                      'replication_rules': [(2, 'T1_DATATAPE', True, True), (1, 'T1_DATADISK', False, True)], 'lifetime': 100000, 'retroactive': 0, 'dry_run': 0, 'comments': 'blahblah'})
        r2 = TestApp(subs_app.wsgifunc(*mw)).post('/root/%s' % (subscription_name), headers=headers2, params=data, expect_errors=True)
        assert_equal(r2.status, 201)

        data = dumps({'filter': {'project': ['toto', ]}})
        r3 = TestApp(subs_app.wsgifunc(*mw)).put('/root/%s' % (subscription_name), headers=headers2, params=data, expect_errors=True)
        assert_equal(r3.status, 201)

        r4 = TestApp(subs_app.wsgifunc(*mw)).get('/root/%s' % (subscription_name), headers=headers2, expect_errors=True)
        print r4
        print type(loads(r4.body))
        assert_equal(r4.status, 200)
        assert_equal(loads(loads(r4.body)['filter'])['project'][0], 'toto')
Ejemplo n.º 11
0
    def test_errors_to_sentry(self, logging_info, raven_client_mocked):
        # what the middleware app does is that it creates a class based on
        # another and sets an attribute called `cls`
        class MadeUp(middleware_app.ImplementationWrapper):
            cls = AuxImplementationErroring
            all_services = {}

        FAKE_DSN = "https://[email protected]/XX"

        mock_logging = mock.MagicMock()

        config = DotDict(
            logger=mock_logging, web_server=DotDict(ip_address="127.0.0.1", port="88888"), sentry=DotDict(dsn=FAKE_DSN)
        )
        server = CherryPy(config, (("/aux/(.*)", MadeUp),))

        def fake_get_ident(exception):
            return "123456789"

        mocked_client = mock.MagicMock()
        mocked_client.get_ident.side_effect = fake_get_ident

        def fake_client(dsn):
            assert dsn == FAKE_DSN
            return mocked_client

        raven_client_mocked.side_effect = fake_client

        testapp = TestApp(server._wsgi_func)
        response = testapp.get("/aux/bla", expect_errors=True)
        eq_(response.status, 500)
        mock_logging.info.has_call([mock.call("Error captured in Sentry. Reference: 123456789")])
Ejemplo n.º 12
0
    def test_basic_get_with_parsed_query_string(self, logging_info):
        # what the middleware app does is that creates a class based on another
        # and sets an attribute called `cls`
        class MadeUp(middleware_app.ImplementationWrapper):
            cls = AuxImplementation5

        config = DotDict(
            logger=logging,
            web_server=DotDict(
                ip_address='127.0.0.1',
                port='88888'
            )
        )
        server = CherryPy(config, (
          ('/aux/(.*)', MadeUp),
        ))

        testapp = TestApp(server._wsgi_func)
        response = testapp.get('/aux/foo/bar/names/peter+anders')
        self.assertEqual(response.status, 200)
        self.assertEqual(json.loads(response.body),
                         {'foo': 'bar',
                          'names': ['peter', 'anders']})

        logging_info.assert_called_with('Running AuxImplementation5')
Ejemplo n.º 13
0
def test_if_mod_304():
    base_dir = os.path.dirname(__file__)
    test_dir = os.path.join(base_dir, 'test-data', '304')

    cache_app = CacheFixtureApp()
    index_page = CacheFixtureResponseInfo(open(os.path.join(test_dir,'index.html')).read())
    page1 = CacheFixtureResponseInfo(open(os.path.join(test_dir,'page1.html')).read())
    page2 = CacheFixtureResponseInfo(open(os.path.join(test_dir,'page2.html')).read())
    cache_app.map_url('/index.html',index_page)
    cache_app.map_url('/page1.html',page1)
    cache_app.map_url('/page2.html',page2)
    
    index_page.mod_time = 1000 
    page1.mod_time = 1000 
    page2.mod_time = 1000 

    
    transcluder = TranscluderMiddleware(cache_app)
    test_app = TestApp(transcluder)
    #load up the deptracker
    result = test_app.get('/index.html', extra_environ={'HTTP_IF_MODIFIED_SINCE' : make_http_time(2000)})

    #and test it
    result = test_app.get('/index.html', extra_environ={'HTTP_IF_MODIFIED_SINCE' : make_http_time(2000)})
    assert result.status == 304

    result = test_app.get('/index.html', extra_environ={'HTTP_IF_MODIFIED_SINCE' : make_http_time(500)})
    assert result.status == 200

    page1.mod_time = 3000
    result = test_app.get('/index.html', extra_environ={'HTTP_IF_MODIFIED_SINCE' : make_http_time(2000)})
    assert result.status == 200
Ejemplo n.º 14
0
    def test_add_attribute(self):
        """ ACCOUNT (REST): add/get/delete attribute."""
        mw = []

        headers1 = {'X-Rucio-Account': 'root', 'X-Rucio-Username': '******', 'X-Rucio-Password': '******'}
        r1 = TestApp(auth_app.wsgifunc(*mw)).get('/userpass', headers=headers1, expect_errors=True)

        assert_equal(r1.status, 200)
        token = str(r1.header('X-Rucio-Auth-Token'))

        acntusr = account_name_generator()
        headers2 = {'X-Rucio-Auth-Token': str(token)}
        data = dumps({'type': 'USER'})
        r2 = TestApp(account_app.wsgifunc(*mw)).post('/' + acntusr, headers=headers2, params=data, expect_errors=True)
        assert_equal(r2.status, 201)

        key = account_name_generator()
        value = "true"
        data = dumps({'key': key, 'value': value})
        r3 = TestApp(account_app.wsgifunc(*mw)).post('/{0}/attr/{1}'.format(acntusr, key), headers=headers2, params=data, expect_errors=True)
        assert_equal(r3.status, 201)

        r4 = TestApp(account_app.wsgifunc(*mw)).get('/' + acntusr + '/attr/', headers=headers2, expect_errors=True)
        assert_equal(r4.status, 200)

        r5 = TestApp(account_app.wsgifunc(*mw)).delete('/{0}/attr/{1}'.format(acntusr, key), headers=headers2, params=data, expect_errors=True)
        assert_equal(r5.status, 200)
Ejemplo n.º 15
0
def test_wsgirequest_charset_fileupload():
    def handle_fileupload(environ, start_response):
        start_response('200 OK', [('Content-type','text/plain')])
        request = WSGIRequest(environ)

        assert len(request.POST) == 1
        assert isinstance(request.POST.keys()[0], str)
        fs = request.POST['thefile']
        assert isinstance(fs, cgi.FieldStorage)
        assert isinstance(fs.filename, str)
        assert fs.filename == '寿司.txt'
        assert fs.value == 'Sushi'

        request.charset = 'UTF-8'
        assert len(request.POST) == 1
        assert isinstance(request.POST.keys()[0], str)
        fs = request.POST['thefile']
        assert isinstance(fs, cgi.FieldStorage)
        assert isinstance(fs.filename, unicode)
        assert fs.filename == u'寿司.txt'
        assert fs.value == 'Sushi'

        request.charset = None
        assert fs.value == 'Sushi'
        return []

    app = TestApp(handle_fileupload)
    res = app.post('/', upload_files=[('thefile', '寿司.txt', 'Sushi')])
Ejemplo n.º 16
0
 def test_login(self):
     middleware = []
     sendr = Sendr(app.wsgifunc(*middleware))
     r = sendr.get('/login')
     self.assertTrue(r.status == 200, "Expected 200 Response, " \
                         "instead got: %s" % r.status)
     r.mustcontain('Welcome!')
Ejemplo n.º 17
0
class ModelsApiUnhappyTest(unittest.TestCase):
  """
  Unhappy tests for Cloudwatch API
  """


  def setUp(self):
    self.app = TestApp(models_api.app.wsgifunc())
    self.headers = getDefaultHTTPHeaders(grok.app.config)


  @patch("grok.app.repository.engineFactory")
  def testNoAuthHeaders(self, engineFactoryMock): # pylint: disable=W0613
    """
    negative test for authentication guarded route.
    invoke get request without passing authentication headers
    response is validated for appropriate headers and body
    """
    response = self.app.get("", status="*")
    assertions.assertInvalidAuthenticationResponse(self, response)


  @patch("grok.app.repository.engineFactory")
  def testInvalidAuthHeaders(self, engineFactoryMock): # pylint: disable=W0613
    """
    negative test for authentication guarded route.
    invoke get request with invalid authentication headers
    response is validated for appropriate headers and body
    """
    invalidHeaders = getInvalidHTTPHeaders()
    response = self.app.get("", status="*", headers=invalidHeaders)
    assertions.assertInvalidAuthenticationResponse(self, response)
Ejemplo n.º 18
0
    def test_basic_get_args(self, logging_info):
        # what the middleware app does is that it creates a class based on
        # another and sets an attribute called `cls`
        class MadeUp(middleware_app.ImplementationWrapper):
            cls = AuxImplementation2
            all_services = {}

        config = DotDict(logger=logging, web_server=DotDict(ip_address="127.0.0.1", port="88888"))
        server = CherryPy(config, (("/aux/(age|gender|misconfigured)/(.*)", MadeUp),))

        testapp = TestApp(server._wsgi_func)
        response = testapp.get("/aux/age/")
        eq_(response.status, 200)
        eq_(json.loads(response.body), {"age": 100})
        eq_(response.header_dict["content-length"], str(len(response.body)))
        eq_(response.header_dict["content-type"], "application/json")

        logging_info.assert_called_with("Running AuxImplementation2")

        response = testapp.get("/aux/gender/", expect_errors=True)
        eq_(response.status, 200)
        eq_(json.loads(response.body), {"gender": 0})

        # if the URL allows a certain first argument but the implementation
        # isn't prepared for it, it barfs a 405 at you
        response = testapp.get("/aux/misconfigured/", expect_errors=True)
        eq_(response.status, 405)
Ejemplo n.º 19
0
    def test_basic_get(self, logging_info):
        # what the middleware app does is that creates a class based on another
        # and sets an attribute called `cls`
        class MadeUp(middleware_app.ImplementationWrapper):
            cls = AuxImplementation1

        config = DotDict(
            logger=logging,
            web_server=DotDict(
                ip_address='127.0.0.1',
                port='88888'
            )
        )
        server = CherryPy(config, (
          ('/aux/(.*)', MadeUp),
        ))

        testapp = TestApp(server._wsgi_func)
        response = testapp.get('/aux/')
        self.assertEqual(response.status, 200)
        self.assertEqual(json.loads(response.body), {'age': 100})

        logging_info.assert_called_with('Running AuxImplementation1')

        response = testapp.get('/xxxjunkxxx', expect_errors=True)
        self.assertEqual(response.status, 404)
Ejemplo n.º 20
0
class TestWsgi(unittest.TestCase):

    def setUp(self):
        import tempfile
        from paste.fixture import TestApp
        from collective.eggproxy.wsgi import EggProxyApp
        from collective.eggproxy.config import config

        self.tempdir = tempfile.mkdtemp()
        config["eggs_directory"] = self.tempdir
        self.app = TestApp(EggProxyApp(config))

    def tearDown(self):
        import shutil
        shutil.rmtree(self.tempdir)

    def test_root_index(self):
        response = self.app.get('/')
        assert 'collective.eggproxy' in response, response

    def test_package_index(self):
        response = self.app.get('/collective.eggproxy')
        assert '<title>Links for collective.eggproxy</title>' in response, \
                response

    def test_package(self):
        # without trailing '/', paste.fixture.TestResponse click results in:
        # >>> urlparse.urljoin('/collective.eggproxy',
        #                      'collective.eggproxy-0.2.0.tar.gz')
        # '/collective.eggproxy-0.2.0.tar.gz'
        # actual url is: /collective.eggproxy/collective.eggproxy-0.2.0.tar.gz
        response = self.app.get('/collective.eggproxy/')
        response = response.click(index=0, verbose=True)
        assert ('Content-Encoding', 'gzip') in response.headers, \
                response.headers
Ejemplo n.º 21
0
    def test_errors(self, logging_info):
        # what the middleware app does is that it creates a class based on
        # another and sets an attribute called `cls`
        class WithNotFound(middleware_app.ImplementationWrapper):
            cls = AuxImplementationWithNotFoundError
            all_services = {}

        class WithUnavailable(middleware_app.ImplementationWrapper):
            cls = AuxImplementationWithUnavailableError
            all_services = {}

        class WithMissingArgument(middleware_app.ImplementationWrapper):
            cls = AuxImplementationWithMissingArgumentError
            all_services = {}

        class WithBadArgument(middleware_app.ImplementationWrapper):
            cls = AuxImplementationWithBadArgumentError
            all_services = {}

        config = DotDict(logger=logging, web_server=DotDict(ip_address="127.0.0.1", port="88888"))

        server = CherryPy(
            config,
            (
                ("/aux/notfound", WithNotFound),
                ("/aux/unavailable", WithUnavailable),
                ("/aux/missing", WithMissingArgument),
                ("/aux/bad", WithBadArgument),
            ),
        )

        testapp = TestApp(server._wsgi_func)

        # Test a Not Found error
        response = testapp.get("/aux/notfound", expect_errors=True)
        eq_(response.status, 404)
        eq_(response.header("content-type"), "application/json; charset=UTF-8")
        body = json.loads(response.body)
        eq_(body["error"]["message"], "not here")

        # Test a Timeout error
        response = testapp.get("/aux/unavailable", expect_errors=True)
        eq_(response.status, 408)
        eq_(response.header("content-type"), "application/json; charset=UTF-8")
        body = json.loads(response.body)
        eq_(body["error"]["message"], "unavailable")

        # Test BadRequest errors
        response = testapp.get("/aux/missing", expect_errors=True)
        eq_(response.status, 400)
        eq_(response.header("content-type"), "application/json; charset=UTF-8")
        body = json.loads(response.body)
        eq_(body["error"]["message"], "Mandatory parameter(s) 'missing arg' is missing or empty.")

        response = testapp.get("/aux/bad", expect_errors=True)
        eq_(response.status, 400)
        eq_(response.header("content-type"), "application/json; charset=UTF-8")
        body = json.loads(response.body)
        eq_(body["error"]["message"], "Bad value for parameter(s) 'bad arg'")
Ejemplo n.º 22
0
class TestWSGICombo(ComboTestBase):

    def setUp(self):
        super(TestWSGICombo, self).setUp()
        self.root = self.makeDir()
        self.app = TestApp(combo_app(self.root))

    def test_combo_app_sets_content_type_for_js(self):
        """The WSGI App should set a proper Content-Type for Javascript."""
        files = [
            self.makeSampleFile(
                self.root,
                os.path.join("yui", "yui-min.js"),
                "** yui-min **"),
            self.makeSampleFile(
                self.root,
                os.path.join("oop", "oop-min.js"),
                "** oop-min **"),
            self.makeSampleFile(
                self.root,
                os.path.join("event-custom", "event-custom-min.js"),
                "** event-custom-min **"),
            ]

        expected = "\n".join(("// yui/yui-min.js",
                              "** yui-min **",
                              "// oop/oop-min.js",
                              "** oop-min **",
                              "// event-custom/event-custom-min.js",
                              "** event-custom-min **"))

        res = self.app.get("/?" + "&".join(
            ["yui/yui-min.js",
             "oop/oop-min.js",
             "event-custom/event-custom-min.js"]), status=200)
        self.assertEquals(res.headers, [("Content-Type", "text/javascript")])
        self.assertEquals(res.body.strip(), expected)

    def test_combo_app_sets_content_type_for_css(self):
        """The WSGI App should set a proper Content-Type for CSS."""
        files = [
            self.makeSampleFile(
                self.root,
                os.path.join("widget", "skin", "sam", "widget.css"),
                "/* widget-skin-sam */"),
            ]

        expected = "/* widget/skin/sam/widget.css */"

        res = self.app.get("/?" + "&".join(
            ["widget/skin/sam/widget.css"]), status=200)
        self.assertEquals(res.headers, [("Content-Type", "text/css")])
        self.assertEquals(res.body.strip(), expected)

    def test_no_filename_gives_404(self):
        """If no filename is included, a 404 should be returned."""
        res = self.app.get("/", status=404)
        self.assertEquals(res.headers, [("Content-Type", "text/plain")])
        self.assertEquals(res.body, "Not Found")
Ejemplo n.º 23
0
def test_increment():
    app = TestApp(SessionMiddleware(simple_app))
    res = app.get('/')
    assert 'current value is: 1' in res
    res = app.get('/')
    assert 'current value is: 2' in res
    res = app.get('/')
    assert 'current value is: 3' in res
Ejemplo n.º 24
0
def test_app2():
    app = TestApp(wsgi_app)
    info[:] = ['fluff']
    res = app.get('/put2')
    res = app.get('/get1')
    assert res.body == b'fluff'
    res = app.get('/get2')
    assert res.body == b'fluff'
Ejemplo n.º 25
0
 def test_paste_with_remote_user(self):
     app = proxy.make_proxy({},
                            'http://localhost:9876',
                            remote_user_header="HTTP_X_REMOTE_USER")
     app = TestApp(app)
     self.server.accept(1)
     res = app.get('/', extra_environ={'REMOTE_USER': '******'})
     self.assertTrue('User FooBar' in res)
Ejemplo n.º 26
0
 def test_proxy_no_header(self):
     app = proxy.make_proxy({},
                            'http://localhost:9876',
                            remote_user_header="HTTP_X_REMOTE_USER")
     app = TestApp(app)
     self.server.accept(1)
     res = app.get('/')
     self.assertTrue('Just Foo' in res)
Ejemplo n.º 27
0
def test_handlers_index():
    mw = []
    testApp = TestApp(app.wsgifunc(*mw))
    req = testApp.get("/")

    assert_equal(req.status, 200)

    req.mustcontain("Hello Kitty")
Ejemplo n.º 28
0
def test_paste_website():
    # Not the most robust test...
    # need to test things like POSTing to pages, and getting from pages
    # that don't set content-length.
    app = proxy.Proxy('http://pythonpaste.org')
    app = TestApp(app)
    res = app.get('/')
    assert 'Documentation' in res
Ejemplo n.º 29
0
 def test_logout(self):
     middleware = []
     sendr = Sendr(app.wsgifunc(*middleware))
     r = sendr.get('/logout')
     self.assertTrue(r.status == 303, "Expected 303 Response, " \
                         "(redir from /logout to /) " \
                         "instead got: %s" % r.status)
     self.assertTrue(r.normal_body == "", "No content expected at /, " \
                         "instead got: %s" % r.normal_body)
Ejemplo n.º 30
0
 def put(self, server, url, data=None, expect_errors=False):
     a = TestApp(server._wsgi_func)
     data = data or ''
     if isinstance(data, dict):
         q = urllib.urlencode(data, True)
     else:
         q = data
     response = a.put(url, q, expect_errors=expect_errors)
     return self._respond(response, expect_errors)
Ejemplo n.º 31
0
class DefaultHandlerTest(unittest.TestCase):
    def setUp(self):
        self.headers = getDefaultHTTPHeaders(grok.app.config)
        self.app = TestApp(webapp.app.wsgifunc())

    def testDefaultHandlerGET(self):
        response = self.app.get("", headers=self.headers)
        self.assertEqual(response.status, 303)
        self.assertEqual(response.full_status, "303 See Other")
        headers = dict(response.headers)
        self.assertEqual(headers["Content-Type"], "text/html")
        self.assertEqual(headers["Location"],
                         "http://localhost/static/index.html")

    def testDefaultHandlerGETWithSlash(self):
        response = self.app.get("/", headers=self.headers)
        self.assertEqual(response.status, 303)
        self.assertEqual(response.full_status, "303 See Other")
        headers = dict(response.headers)
        self.assertEqual(headers["Content-Type"], "text/html")
        self.assertEqual(headers["Location"],
                         "http://localhost/static/index.html")
Ejemplo n.º 32
0
    def test_errors(self, logging_info):
        # what the middleware app does is that it creates a class based on
        # another and sets an attribute called `cls`
        class WithNotFound(middleware_app.ImplementationWrapper):
            cls = AuxImplementationWithNotFoundError
            all_services = {}

        class WithUnavailable(middleware_app.ImplementationWrapper):
            cls = AuxImplementationWithUnavailableError
            all_services = {}

        class WithMissingArgument(middleware_app.ImplementationWrapper):
            cls = AuxImplementationWithMissingArgumentError
            all_services = {}

        class WithBadArgument(middleware_app.ImplementationWrapper):
            cls = AuxImplementationWithBadArgumentError
            all_services = {}

        config = DotDict(logger=logging,
                         web_server=DotDict(ip_address='127.0.0.1',
                                            port='88888'))

        server = CherryPy(config, (
            ('/aux/notfound', WithNotFound),
            ('/aux/unavailable', WithUnavailable),
            ('/aux/missing', WithMissingArgument),
            ('/aux/bad', WithBadArgument),
        ))

        testapp = TestApp(server._wsgi_func)

        # Test a Not Found error
        response = testapp.get('/aux/notfound', expect_errors=True)
        eq_(response.status, 404)
        eq_(response.header('content-type'), 'application/json; charset=UTF-8')
        body = json.loads(response.body)
        eq_(body['error']['message'], 'not here')

        # Test a Timeout error
        response = testapp.get('/aux/unavailable', expect_errors=True)
        eq_(response.status, 408)
        eq_(response.header('content-type'), 'application/json; charset=UTF-8')
        body = json.loads(response.body)
        eq_(body['error']['message'], 'unavailable')

        # Test BadRequest errors
        response = testapp.get('/aux/missing', expect_errors=True)
        eq_(response.status, 400)
        eq_(response.header('content-type'), 'application/json; charset=UTF-8')
        body = json.loads(response.body)
        eq_(body['error']['message'],
            "Mandatory parameter(s) 'missing arg' is missing or empty.")

        response = testapp.get('/aux/bad', expect_errors=True)
        eq_(response.status, 400)
        eq_(response.header('content-type'), 'application/json; charset=UTF-8')
        body = json.loads(response.body)
        eq_(body['error']['message'], "Bad value for parameter(s) 'bad arg'")
Ejemplo n.º 33
0
    def test_basic_post(self, logging_info):
        # what the middleware app does is that it creates a class based on
        # another and sets an attribute called `cls`
        class MadeUp(middleware_app.ImplementationWrapper):
            cls = AuxImplementation3
            all_services = {}

        config = DotDict(logger=logging,
                         web_server=DotDict(ip_address='127.0.0.1',
                                            port='88888'))

        server = CherryPy(config, (('/aux/(.*)', MadeUp), ))

        testapp = TestApp(server._wsgi_func)
        response = testapp.post('/aux/')
        eq_(response.status, 200)
        eq_(json.loads(response.body), {'age': 100})

        logging_info.assert_called_with('Running AuxImplementation3')

        response = testapp.get('/aux/', expect_errors=True)
        eq_(response.status, 405)
Ejemplo n.º 34
0
 def test_userpass_fail(self):
     """AUTHENTICATION (REST): Username and password (wrong credentials)."""
     options = []
     headers = {
         'X-Rucio-Account': 'wrong',
         'X-Rucio-Username': '******',
         'X-Rucio-Password': '******'
     }
     headers.update(self.vo_header)
     result = TestApp(APP.wsgifunc(*options)).get('/userpass',
                                                  headers=headers,
                                                  expect_errors=True)
     assert_equal(result.status, 401)
Ejemplo n.º 35
0
    def test_userpass(self):
        """ ACCOUNT (REST): send a POST to add an identity to an account."""
        if config_get_bool('common', 'multi_vo', raise_exception=False, default=False):
            vo_header = {'X-Rucio-VO': config_get('client', 'vo', raise_exception=False, default='tst')}
        else:
            vo_header = {}

        mw = []
        account = 'root'
        headers1 = {'X-Rucio-Account': account, 'X-Rucio-Username': '******', 'X-Rucio-Password': '******'}
        headers1.update(vo_header)
        res1 = TestApp(auth_app.wsgifunc(*mw)).get('/userpass', headers=headers1, expect_errors=True)
        assert_equal(res1.status, 200)
        token = str(res1.header('X-Rucio-Auth-Token'))
        username = uuid()
        password = '******'

        # normal addition
        headers2 = {'X-Rucio-Auth-Token': str(token), 'X-Rucio-Username': username, 'X-Rucio-Password': password,
                    'X-Rucio-Email': 'email'}
        res2 = TestApp(identity_app.wsgifunc(*mw)).put('/' + account + '/userpass', headers=headers2, expect_errors=True)
        assert_equal(res2.status, 201)
Ejemplo n.º 36
0
    def setUp(self):
        self.headers = getDefaultHTTPHeaders(app_config)
        self.invalidHeaders = getInvalidHTTPHeaders()
        self.app = TestApp(annotations_api.app.wsgifunc())
        self.annotation = {
            "uid": "f4aa70b361f04036b0b39530900f38fa",
            "timestamp": "2014-01-25 05:00:00",
            "created": "2014-01-25 07:14:06",
            "device": "device1",
            "user": "******",
            "server": "us-west-2/AWS/EC2/i-f52075fe",
            "message": "My annotation",
            "data": None
        }
        self.instanceId = "%s/AWS/EC2/%s" % (VALID_EC2_INSTANCES["region"],
                                             VALID_EC2_INSTANCES["instanceId"])

        # Prepare request as annotation without "uid" or "created" fields
        self.request = self.annotation.copy()
        self.request["server"] = self.instanceId
        del self.request["uid"]
        del self.request["created"]
Ejemplo n.º 37
0
    def test_create_and_list_subscription_by_id(self):
        """ SUBSCRIPTION (REST): Test the creation of a new subscription and get by subscription id """
        mw = []

        headers1 = {'X-Rucio-Account': 'root', 'X-Rucio-Username': '******', 'X-Rucio-Password': '******'}
        res1 = TestApp(auth_app.wsgifunc(*mw)).get('/userpass', headers=headers1, expect_errors=True)

        assert_equal(res1.status, 200)
        token = str(res1.header('X-Rucio-Auth-Token'))

        subscription_name = uuid()
        headers2 = {'X-Rucio-Auth-Token': str(token)}
        data = dumps({'options': {'filter': {'project': self.projects, 'datatype': ['AOD', ], 'excluded_pattern': self.pattern1, 'account': ['tier0', ]},
                                  'replication_rules': [{'lifetime': 86400, 'rse_expression': 'MOCK|MOCK2', 'copies': 2, 'activity': 'Data Brokering'}],
                                  'lifetime': 100000, 'retroactive': 0, 'dry_run': 0, 'comments': 'blahblah'}})
        res2 = TestApp(subs_app.wsgifunc(*mw)).post('/root/%s' % (subscription_name), headers=headers2, params=data, expect_errors=True)
        assert_equal(res2.status, 201)

        subscription_id = res2.body
        res3 = TestApp(subs_app.wsgifunc(*mw)).get('/Id/%s' % (subscription_id), headers=headers2, expect_errors=True)
        assert_equal(res3.status, 200)
        assert_equal(loads(loads(res3.body)['filter'])['project'][0], 'data12_900GeV')
Ejemplo n.º 38
0
    def test_whoami_account(self):
        """ ACCOUNT (REST): Test the whoami method."""
        mw = []

        headers1 = {
            'X-Rucio-Account': 'root',
            'X-Rucio-Username': '******',
            'X-Rucio-Password': '******'
        }
        headers1.update(self.vo_header)
        res1 = TestApp(auth_app.wsgifunc(*mw)).get('/userpass',
                                                   headers=headers1,
                                                   expect_errors=True)

        assert res1.status == 200
        token = str(res1.header('X-Rucio-Auth-Token'))

        headers2 = {'X-Rucio-Auth-Token': str(token)}
        res2 = TestApp(account_app.wsgifunc(*mw)).get('/whoami',
                                                      headers=headers2,
                                                      expect_errors=True)
        assert res2.status == 303
Ejemplo n.º 39
0
class TestHttpsDecorator(TestWSGIController):
    def setUp(self):
        TestWSGIController.setUp(self)
        from routes import Mapper
        map = Mapper()
        map.connect('/:action/:id')
        map.connect('/:controller/:action/:id')
        app = ControllerWrap(HttpsController)
        app = SetupCacheGlobal(app, self.environ, setup_cache=False)
        app = RoutesMiddleware(app, map)
        app = RegistryManager(app)
        self.app = TestApp(app)

    def test_https_explicit_path(self):
        self.environ['pylons.routes_dict']['action'] = 'index'

        response = self.app.get('/index', status=302)
        assert response.header_dict.get('location') == \
            'https://localhost/pylons'

        self.environ['wsgi.url_scheme'] = 'https'
        response = self.app.get('/index', status=200)
        assert 'location' not in response.header_dict
        assert 'index page' in response

    def test_https_disallows_post(self):
        self.environ['pylons.routes_dict']['action'] = 'index'

        response = self.app.post('/index', status=405)

    def test_https_url_for_kwargs(self):
        self.environ['pylons.routes_dict']['action'] = 'login'

        response = self.app.get('/login', status=302)
        assert response.header_dict.get('location') == \
            'https://localhost/auth/login'

        self.environ['wsgi.url_scheme'] = 'https'
        response = self.app.get('/login', status=200)
        assert 'location' not in response.header_dict
        assert 'login page' in response

    def test_https_redirect_to_self(self):
        self.environ['pylons.routes_dict']['action'] = 'get'

        response = self.app.get('/get', status=302)
        assert response.header_dict.get('location') == \
            'https://localhost/get'

        self.environ['wsgi.url_scheme'] = 'https'
        response = self.app.get('/get', status=200)
        assert 'location' not in response.header_dict
        assert 'get page' in response
Ejemplo n.º 40
0
    def _make_app(self):
        r"""Create a demo app with the WSGI-like stack applied on top"""
        self.plugin = self._makeOne(realm='OAuthRealm')

        app = DemoApp()

        # Apply repoze on top
        app = setup_auth(app, group_adapters=None, permission_adapters=None,
            identifiers=[('oauth', self.plugin)],
            authenticators=[('oauth', self.plugin)],
            challengers=[('oauth', self.plugin)])

        self.app = TestApp(app)
        return self.app
Ejemplo n.º 41
0
    def test_scope_failure(self):
        """ SCOPE (REST): send a POST to create a new scope for a not existing account to test the error"""
        mw = []

        headers1 = {
            'X-Rucio-Account': 'root',
            'X-Rucio-Username': '******',
            'X-Rucio-Password': '******'
        }
        res1 = TestApp(auth_app.wsgifunc(*mw)).get('/userpass',
                                                   headers=headers1,
                                                   expect_errors=True)
        assert_equal(res1.status, 200)

        token = str(res1.header('X-Rucio-Auth-Token'))
        headers2 = {'X-Rucio-Auth-Token': str(token)}
        scopeusr = scope_name_generator()
        account_name_generator()
        res2 = TestApp(account_app.wsgifunc(*mw)).post('/%s/scopes/%s' %
                                                       (scopeusr, scopeusr),
                                                       headers=headers2,
                                                       expect_errors=True)
        assert_equal(res2.status, 404)
Ejemplo n.º 42
0
    def setUp(self):
        """Set up the file system and GPG"""
        # Create directories for the file store and the GPG keyring
        for d in (config.TEST_DIR, config.STORE_DIR, config.GPG_KEY_DIR):
            try:
                # some of these dirs already exist because we import source and
                # journalist, which import crypto, which calls gpg.GPG at module
                # level, which auto-generates the GPG homedir if it does not exist
                os.mkdir(d)
            except OSError:
                pass

        # Initialize the GPG keyring
        self.gpg = gnupg.GPG(gnupghome=config.GPG_KEY_DIR)

        # Import the journalist key for testing (faster to import a pre-generated
        # key than to gen a new one every time)
        for keyfile in ("test_journalist_key.pub", "test_journalist_key.sec"):
            self.gpg.import_keys(open(keyfile).read())

        middleware = []
        self.source_app = TestApp(source_app.wsgifunc(*middleware))
        self.journalist_app = TestApp(journalist_app.wsgifunc(*middleware))
Ejemplo n.º 43
0
 def setUp(self):
   self.headers = getDefaultHTTPHeaders(grok.app.config)
   self.app = TestApp(wufoo_api.app.wsgifunc())
   self.instanceData = {"version" : "2010-08-31",
                        "instanceId" : "i-d9e211f6",
                        "billingProducts" : None,
                        "accountId" : "987654321",
                        "kernelId" : "aki-88aa75e1",
                        "ramdiskId" : None,
                        "architecture" : "x86_64",
                        "imageId" : "ami-b56a7fdc",
                        "pendingTime" : "2014-03-20T14:06:46Z",
                        "instanceType" : "m1.medium",
                        "region" : "us-east-1",
                        "devpayProductCodes" : None,
                        "privateIp" : "10.122.242.151",
                        "availabilityZone" : "us-east-1d"}
   self.postData = data = {"name": "User Schmoozer",
                           "company": "Numenta, inc.",
                           "edition": "Standard",
                           "version": grok.__version__.__version__,
                           "build": "0",
                           "email": "*****@*****.**"}
Ejemplo n.º 44
0
    def test_update_vo_success(self):
        """ MULTI VO (REST): Test updating VO through REST layer succeeds """
        mw = []

        headers1 = {'X-Rucio-Account': 'super_root', 'X-Rucio-Username': '******', 'X-Rucio-Password': '******'}
        headers1.update(self.def_header)
        res1 = TestApp(auth_app.wsgifunc(*mw)).get('/userpass', headers=headers1, expect_errors=True)

        assert_equal(res1.status, 200)
        token = str(res1.header('X-Rucio-Auth-Token'))

        params = {'email': generate_uuid(), 'description': generate_uuid()}
        headers2 = {'X-Rucio-Auth-Token': str(token)}
        res2 = TestApp(vo_app.wsgifunc(*mw)).put('/' + self.vo['vo'], headers=headers2, expect_errors=True, params=dumps(params))
        assert_equal(res2.status, 200)

        vo_update_success = False
        for v in vo_api.list_vos('super_root', 'def'):
            if v['vo'] == self.vo['vo']:
                assert_equal(params['email'], v['email'])
                assert_equal(params['description'], v['description'])
                vo_update_success = True
        assert_true(vo_update_success)
Ejemplo n.º 45
0
    def test_auth_x509(self):
        """ MULTI VO (REST): Test X509 authentication to multiple VOs """
        mw = []

        # TestApp doesn't support `cert` argument, so get tokens from API instead
        token_tst = get_auth_token_x509('root', '/CN=Rucio User', 'unknown', None, **self.vo).token
        token_new = get_auth_token_x509('root', '/CN=Rucio User', 'unknown', None, **self.new_vo).token

        headers_tst = {'X-Rucio-Auth-Token': str(token_tst)}
        res_tst = TestApp(account_app.wsgifunc(*mw)).get('/', headers=headers_tst, expect_errors=True)
        assert_equal(res_tst.status, 200)
        accounts_tst = [parse_response(a)['account'] for a in res_tst.body.decode().split('\n')[:-1]]
        assert_not_equal(len(accounts_tst), 0)
        assert_in(self.account_tst, accounts_tst)
        assert_not_in(self.account_new, accounts_tst)

        headers_new = {'X-Rucio-Auth-Token': str(token_new)}
        res_new = TestApp(account_app.wsgifunc(*mw)).get('/', headers=headers_new, expect_errors=True)
        assert_equal(res_new.status, 200)
        accounts_new = [parse_response(a)['account'] for a in res_new.body.decode().split('\n')[:-1]]
        assert_not_equal(len(accounts_new), 0)
        assert_in(self.account_new, accounts_new)
        assert_not_in(self.account_tst, accounts_new)
Ejemplo n.º 46
0
    def test_auth_gss(self):
        """ MULTI VO (REST): Test gss authentication to multiple VOs """
        mw = []

        # Can't rely on `requests_kerberos` module being present, so get tokens from API instead
        token_tst = get_auth_token_gss('root', '*****@*****.**', 'unknown', None, **self.vo).token
        token_new = get_auth_token_gss('root', '*****@*****.**', 'unknown', None, **self.new_vo).token

        headers_tst = {'X-Rucio-Auth-Token': str(token_tst)}
        res_tst = TestApp(account_app.wsgifunc(*mw)).get('/', headers=headers_tst, expect_errors=True)
        assert_equal(res_tst.status, 200)
        accounts_tst = [parse_response(a)['account'] for a in res_tst.body.decode().split('\n')[:-1]]
        assert_not_equal(len(accounts_tst), 0)
        assert_in(self.account_tst, accounts_tst)
        assert_not_in(self.account_new, accounts_tst)

        headers_new = {'X-Rucio-Auth-Token': str(token_new)}
        res_new = TestApp(account_app.wsgifunc(*mw)).get('/', headers=headers_new, expect_errors=True)
        assert_equal(res_new.status, 200)
        accounts_new = [parse_response(a)['account'] for a in res_new.body.decode().split('\n')[:-1]]
        assert_not_equal(len(accounts_new), 0)
        assert_in(self.account_new, accounts_new)
        assert_not_in(self.account_tst, accounts_new)
Ejemplo n.º 47
0
def test_request_config_multi():
    try:
        config = {test_key: 'test value'}
        app = ConfigMiddleware(app_with_config, config)
        config = {test_key: 'nesting value'}
        app = ConfigMiddleware(NestingAppWithConfig(app), config)
        res = TestApp(app).get('/')
        assert 'Variable is: test value' in res
        assert 'Variable is (in environ): test value' in res
        assert 'Nesting variable is: nesting value' in res
        print(res)
        assert 'Nesting variable is (in environ): nesting value' in res
    finally:
        reset_config()
class Tests(TestCase):

    def test_DateTimeJSONEncoder(self):
        dt = datetime.datetime(1978, 6, 15)
        self.assertEqual(json.dumps([dt, 1], cls=handlers.DateTimeJSONEncoder),
                '["1978-06-15T00:00:00", 1]')

    @mock.patch('time.time')
    def test_InMemCacheMixin(self, time):
        loaded_urls = templeton.handlers.load_urls([
            '/test/', 'CachedHandler',
        ])
        webapp = web.application(loaded_urls, globals())
        self.app = TestApp(webapp.wsgifunc())

        CachedHandler.updates = []
        time.return_value = 10

        for i in xrange(30):
            self.app.get('/api/test/')
            time.return_value += 1

        self.assertEqual(CachedHandler.updates, [10, 20, 30])
Ejemplo n.º 49
0
    def test_basic_get_args(self, logging_info):
        # what the middleware app does is that it creates a class based on
        # another and sets an attribute called `cls`
        class MadeUp(middleware_app.ImplementationWrapper):
            cls = AuxImplementation2
            all_services = {}

        config = DotDict(
            logger=logging,
            web_server=DotDict(
                ip_address='127.0.0.1',
                port='88888'
            )
        )
        server = CherryPy(config, (
            ('/aux/(age|gender|misconfigured)/(.*)', MadeUp),
        ))

        testapp = TestApp(server._wsgi_func)
        response = testapp.get('/aux/age/')
        eq_(response.status, 200)
        eq_(json.loads(response.body), {'age': 100})
        eq_(response.header_dict['content-length'],
                         str(len(response.body)))
        eq_(response.header_dict['content-type'],
                         'application/json')

        logging_info.assert_called_with('Running AuxImplementation2')

        response = testapp.get('/aux/gender/', expect_errors=True)
        eq_(response.status, 200)
        eq_(json.loads(response.body), {'gender': 0})

        # if the URL allows a certain first argument but the implementation
        # isn't prepared for it, it barfs a 405 at you
        response = testapp.get('/aux/misconfigured/', expect_errors=True)
        eq_(response.status, 405)
Ejemplo n.º 50
0
    def test_export_import(self):
        """ IMPORT/EXPORT (REST): Test the export and import of data together to check same syntax."""
        # Setup new RSE, distance, attribute, limits
        new_rse = rse_name_generator()
        add_rse(new_rse, **self.vo)

        # Get token
        mw = []
        headers1 = {
            'X-Rucio-Account': 'root',
            'X-Rucio-Username': '******',
            'X-Rucio-Password': '******'
        }
        headers1.update(self.vo_header)
        r1 = TestApp(auth_app.wsgifunc(*mw)).get('/userpass',
                                                 headers=headers1,
                                                 expect_errors=True)
        token = str(r1.header('X-Rucio-Auth-Token'))
        headers2 = {
            'X-Rucio-Type': 'user',
            'X-Rucio-Account': 'root',
            'X-Rucio-Auth-Token': str(token)
        }

        # Export data
        r2 = TestApp(export_app.wsgifunc(*mw)).get('/',
                                                   headers=headers2,
                                                   expect_errors=True)
        exported_data = parse_response(r2.body)

        # Import data
        r3 = TestApp(import_app.wsgifunc(*mw)).post(
            '/',
            headers=headers2,
            expect_errors=True,
            params=render_json(**exported_data))
        assert_equal(r3.status, 201)
Ejemplo n.º 51
0
    def test_export_rest(self):
        """ EXPORT (REST): Test the export of data."""
        mw = []
        headers1 = {
            'X-Rucio-Account': 'root',
            'X-Rucio-Username': '******',
            'X-Rucio-Password': '******'
        }
        headers1.update(self.vo_header)
        r1 = TestApp(auth_app.wsgifunc(*mw)).get('/userpass',
                                                 headers=headers1,
                                                 expect_errors=True)
        token = str(r1.header('X-Rucio-Auth-Token'))
        headers2 = {
            'X-Rucio-Type': 'user',
            'X-Rucio-Account': 'root',
            'X-Rucio-Auth-Token': str(token)
        }

        r2 = TestApp(export_app.wsgifunc(*mw)).get('/',
                                                   headers=headers2,
                                                   expect_errors=True)
        rses = export_rses()
        sanitised = {}
        for rse_id in rses:
            sanitised[get_rse_name(rse_id=rse_id)] = rses[rse_id]
        rses = sanitised

        assert_equal(r2.status, 200)
        assert_equal(
            json.loads(r2.body),
            json.loads(
                render_json(**{
                    'rses': rses,
                    'distances': export_distances()
                })))
Ejemplo n.º 52
0
class GrokHandlerTest(unittest.TestCase):


  def setUp(self):
    self.headers = getDefaultHTTPHeaders(grok.app.config)
    self.app = TestApp(webapp.app.wsgifunc())


  @patch.object(web.template, "render")
  def testgrokHandlerGET(self, render, _instanceDataMock):
    response = self.app.get("/grok", headers=self.headers)
    self.assertTrue(render.called)
    assertions.assertResponseStatusCode(self, response, code=200)
    headers = dict(response.headers)
    self.assertEqual(headers["Content-Type"], "text/html; charset=UTF-8")
Ejemplo n.º 53
0
    def setUp(self):
        # HACK: We kept getting db.printing inexplicably set to True, so patch
        # it to be False here.
        _real_db_execute = web.db.DB._db_execute

        def _db_execute(self, cur, sql_query):
            self.printing = False
            return _real_db_execute(self, cur, sql_query)

        web.db.DB._db_execute = _db_execute

        # Set the dev flag in Config to False.
        Config.load()
        Config.data['dev'] = False

        # Set the debug flag to true, despite what is in the config file
        web.config.debug = False
        web.config.session_parameters['cookie_name'] = 'gam'

        # TODO: Clean up this initialization
        web.ctx.method = ''
        web.ctx.path = ''
        import StringIO
        web.ctx.env = {'wsgi.input': StringIO.StringIO(), 'REQUEST_METHOD': ''}

        # Set up the routes
        app = web.application(main.ROUTES, globals())

        # Grab a database connection
        self.db = main.sessionDB()

        # Initialize the session holder (I don't know what that is yet)
        #main.SessionHolder.set(web.session.Session(app, web.session.DBStore(db, 'web_session')))

        # Finally, create a test app
        self.app = TestApp(app.wsgifunc())
Ejemplo n.º 54
0
    def test_put_with_data(self, logging_info):
        # what the middleware app does is that creates a class based on another
        # and sets an attribute called `cls`
        class MadeUp(middleware_app.ImplementationWrapper):
            cls = AuxImplementation4

        config = DotDict(
            logger=logging,
            web_server=DotDict(
                ip_address='127.0.0.1',
                port='88888'
            )
        )

        server = CherryPy(config, (
          ('/aux/(.*)', MadeUp),
        ))

        testapp = TestApp(server._wsgi_func)
        response = testapp.put('/aux/', params={'add': 1})
        self.assertEqual(response.status, 200)
        self.assertEqual(json.loads(response.body), {'age': 101})

        logging_info.assert_called_with('Running AuxImplementation4')
Ejemplo n.º 55
0
    def test_create_user_success(self):
        """ ACCOUNT (REST): send a POST to create a new user """
        mw = []

        headers1 = {
            'X-Rucio-Account': 'root',
            'X-Rucio-Username': '******',
            'X-Rucio-Password': '******'
        }
        res1 = TestApp(auth_app.wsgifunc(*mw)).get('/userpass',
                                                   headers=headers1,
                                                   expect_errors=True)

        assert_equal(res1.status, 200)
        token = str(res1.header('X-Rucio-Auth-Token'))

        acntusr = account_name_generator()
        headers2 = {'X-Rucio-Auth-Token': str(token)}
        data = dumps({'type': 'USER', 'email': '*****@*****.**'})
        res2 = TestApp(account_app.wsgifunc(*mw)).post('/' + acntusr,
                                                       headers=headers2,
                                                       params=data,
                                                       expect_errors=True)
        assert_equal(res2.status, 201)
Ejemplo n.º 56
0
def test_fixture():
    app = TestApp(SimpleApplication())
    res = app.get('/', params={'a': ['1', '2']})
    assert (res.request.environ['QUERY_STRING'] == 'a=1&a=2')
    res = app.put('/')
    assert (res.request.environ['REQUEST_METHOD'] == 'PUT')
    res = app.delete('/')
    assert (res.request.environ['REQUEST_METHOD'] == 'DELETE')

    class FakeDict(object):
        def items(self):
            return [('a', '10'), ('a', '20')]

    res = app.post('/params', params=FakeDict())

    # test multiple cookies in one request
    app.cookies['one'] = 'first'
    app.cookies['two'] = 'second'
    app.cookies['three'] = ''
    res = app.get('/')
    hc = res.request.environ['HTTP_COOKIE'].split('; ')
    assert ('one=first' in hc)
    assert ('two=second' in hc)
    assert ('three=' in hc)
Ejemplo n.º 57
0
class SettingsApiUnhappyTest(unittest.TestCase):
    """
  Unhappy tests for cloudwatch API
  """
    def setUp(self):
        self.app = TestApp(settings_api.app.wsgifunc())
        self.headers = getDefaultHTTPHeaders(htm.it.app.config)

    def testNoAuthHeaders(self):
        """
    negative test for authentication guarded route.
    invoke get request without passing authentication headers
    resoponse is validated for appropriate headers and body
    """
        response = self.app.get("", status="*")
        assertions.assertInvalidAuthenticationResponse(self, response)

    def testInvalidAuthHeaders(self):
        """
    negative test for authentication guarded route.
    invoke get request with invalid authentication headers
    resoponse is validated for appropriate headers and body
    """
        invalidHeaders = getInvalidHTTPHeaders()
        response = self.app.get("", status="*", headers=invalidHeaders)
        assertions.assertInvalidAuthenticationResponse(self, response)

    def testInvalidMethod(self):
        """
    Invoke non supported method
    resoponse is validated for appropriate headers and body
    """
        response = self.app.put("", status="*", headers=self.headers)
        assertions.assertMethodNotAllowed(self, response)
        headers = dict(response.headers)
        self.assertEqual(headers["Allow"], "GET, POST")
class TestAuthenticateFormDecorator(TestWSGIController):
    def setUp(self):
        from pylons.testutil import ControllerWrap, SetupCacheGlobal
        ProtectedController = make_protected()
        TestWSGIController.setUp(self)
        app = ControllerWrap(ProtectedController)
        app = SetupCacheGlobal(app, self.environ, setup_session=True)
        app = SessionMiddleware(app, {}, data_dir=session_dir)
        app = RegistryManager(app)
        self.app = TestApp(app)

    def test_unauthenticated(self):
        from pylons.decorators.secure import csrf_detected_message

        self.environ['pylons.routes_dict']['action'] = 'protected'
        response = self.app.post('/protected',
                                 extra_environ=self.environ,
                                 expect_errors=True)
        assert response.status == 403
        assert csrf_detected_message in response

    def test_authenticated(self):
        from webhelpers.pylonslib import secure_form

        self.environ['pylons.routes_dict']['action'] = 'form'
        response = self.app.get('/form', extra_environ=self.environ)
        token = response.body

        self.environ['pylons.routes_dict']['action'] = 'protected'
        response = self.app.post('/protected',
                                 params={secure_form.token_key: token},
                                 extra_environ=self.environ,
                                 expect_errors=True)
        assert 'Authenticated' in response

        self.environ['pylons.routes_dict']['action'] = 'protected'
        response = self.app.put('/protected',
                                params={secure_form.token_key: token},
                                extra_environ=self.environ,
                                expect_errors=True)
        assert 'Authenticated' in response

        # GET with token_key in query string
        response = self.app.get('/protected',
                                params={secure_form.token_key: token},
                                extra_environ=self.environ,
                                expect_errors=True)
        assert 'Authenticated' in response

        # POST with token_key in query string
        response = self.app.post('/protected?' + secure_form.token_key + '=' +
                                 token,
                                 extra_environ=self.environ,
                                 expect_errors=True)
        assert 'Authenticated' in response
Ejemplo n.º 59
0
    def test_ssh_fail(self):
        """AUTHENTICATION (REST): SSH RSA public key exchange (wrong credentials)."""

        root = InternalAccount('root')
        try:
            add_account_identity(PUBLIC_KEY, IdentityType.SSH, root, email='*****@*****.**')
        except Duplicate:
            pass  # might already exist, can skip

        signature = ssh_sign(PRIVATE_KEY, 'sign_something_else')

        options = []
        headers = {'X-Rucio-Account': 'root', 'X-Rucio-SSH-Signature': signature}
        result = TestApp(APP.wsgifunc(*options)).get('/ssh', headers=headers, expect_errors=True)
        assert_equal(result.status, 401)

        del_account_identity(PUBLIC_KEY, IdentityType.SSH, root)
Ejemplo n.º 60
0
    def setUp(
        self
    ):  # This test duplicates a lot of setUp code, it should be refactored or dropped
        from ictv.app import get_app
        from ictv.database import setup_database, create_database, load_plugins
        from ictv.plugin_manager.plugin_manager import PluginManager
        from paste.fixture import TestApp

        create_fake_plugin(self.fake_plugin_root)

        setup_database()
        create_database()
        load_plugins()
        Plugin.selectBy(name='fake_plugin').getOne().activated = 'notfound'
        Plugin.update_plugins(PluginManager.list_plugins())
        self.ictv_app = get_app("/tmp/config.yaml")
        self.testApp = TestApp(self.ictv_app.wsgifunc())