Beispiel #1
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)
    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)
class TestGET():
    def setUp(self):
        self.url_1 = ''.join([controller, 'c221'])
        self.url_2 = ''.join([controller, 'c222'])
        
        middleware = []
        self.client = TestApp(app.wsgifunc(*middleware))
        self.client.post(self.url_1, 'test')
        self.client.post(self.url_2, 'test')

    def test_get_with_no_key_should_return_all_keys(self):
        r = self.client.get(controller)
        assert_equal(r.status, 200)
        r.mustcontain('c222')
        r.mustcontain('c221')

    def test_get_with_valid_key(self):
        r = self.client.get(self.url_2)
        assert_equal(r.status, 200)
        r.mustcontain('test')
    
    def test_get_with_invalid_key(self):
        """No Assertion required
        """
        self.url_3 = ''.join([controller, 'c223'])
        self.client.get(self.url_3, status=404)
    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)
class TestGET():
    def setUp(self):
        middleware = []
        self.client = TestApp(app.wsgifunc(*middleware))

        self.lazy_url_2 = ''.join([lazy_controller, 'l222'])
        self.lazy_url_3 = ''.join([lazy_controller, 'l223'])     
        canonical_url_1 = ''.join([canonical_controller, 'l221'])
        canonical_url_2 = ''.join([canonical_controller, 'l222'])
        
        self.client.post(canonical_url_1, 'test')   #Propagated to all nodes
        self.client.post(canonical_url_2, 'test')   #Propagated to all nodes

    def test_get_with_no_key_should_return_all_keys_present_in_any_node(self):
        r = self.client.get(lazy_controller)
        assert_equal(r.status, 200)
        r.mustcontain('l222')
        r.mustcontain('l221')

    def test_get_with_valid_key_present_in_all_nodes(self):
        r = self.client.get(self.lazy_url_2)
        assert_equal(r.status, 200)
        r.mustcontain('test')
    
    def test_get_with_invalid_key(self):
        """No Assertion required
        """
        self.client.get(self.lazy_url_3, status=404)
class TestPOST():
    def setUp(self):
        middleware = []
        self.client = TestApp(app.wsgifunc(*middleware))

    def test_set_a_key_value(self):
        url_225 = ''.join([controller, 'c225'])
        r = self.client.post(url_225, "testing post method:newly set key")
        assert_equal(r.status, 201)
        r.mustcontain("c225")
        r2 = self.client.get(url_225)
        r2.mustcontain("testing post method:newly set key")

    def test_set_a_key_value_where_key_exists(self):
        url_335 = ''.join([controller, 'c335'])
        self.client.post(url_335, "value exists. should have been overwritten.")
        r2 = self.client.get(url_335)
        r2.mustcontain("value exists. should have been overwritten.")
        
        r3 = self.client.post(url_335, "overwritten the existing value")
        assert_equal(r3.status, 201)
        r4 = self.client.get(url_335)
        r4.mustcontain("overwritten the existing value")
    
    def test_long_key_results_error(self):
        """No Assertion required
        """
        key = "".join(map(str, range(40)))
        url_too_long_key = ''.join([controller, key])
        self.client.post(url_too_long_key, "very very long. longer key than in database. should not get inserted", status=400)
        self.client.get(url_too_long_key, status=404)
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
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)
class TestDELETE():
    def setUp(self):
        middleware = []
        self.client = TestApp(app.wsgifunc(*middleware))

    def test_delete_a_key_value(self):
        lazy_url = ''.join([lazy_controller, 'l777'])
        canonical_url = ''.join([canonical_controller, 'l777'])
        self.client.post(canonical_url, "should have a deleted flag")
        
        self.client.delete(lazy_url, status=202)
        self.client.get(canonical_url, status=404)
        
    def test_cannot_delete_a_non_existing_key_value(self):
        url_xyz = ''.join([lazy_controller, 'lxyz'])
        self.client.delete(url_xyz, status=404)
                
    def test_delete_existing_and_immediately_insert_a_key_value(self):
        lazy_url = ''.join([lazy_controller, 'l737'])
        canonical_url = ''.join([canonical_controller, 'l737'])        
        self.client.post(canonical_url, "will be deleted and over written on canonical. Can be visible in others.")
        
        self.client.delete(lazy_url, status=202)
        self.client.post(lazy_url, "deleted existing. and written a new value")
        r2 = self.client.get(canonical_url)
        r2.mustcontain("deleted existing. and written a new value")
Beispiel #10
0
def test_wsgirequest_charset():
    # Jose, 'José'
    app = TestApp(AssertApp(assertfunc=valid_name(u'José',
                                                  encoding='iso-8859-1')))
    res = app.get('/?name=Jos%E9')

    # Tanaka, '田中'
    app = TestApp(AssertApp(assertfunc=valid_name(u'田中', encoding='UTF-8')))
    res = app.get('/?name=%E7%94%B0%E4%B8%AD')
    
    # Nippon (Japan), '日本'
    app = TestApp(AssertApp(assertfunc=valid_name(u'日本', encoding='UTF-8',
                                                  post=True)))
    res = app.post('/', params=dict(name='日本'))

    # WSGIRequest will determine the charset from the Content-Type header when
    # unicode is expected.
    # No encoding specified: not expecting unicode
    app = TestApp(AssertApp(assertfunc=valid_name('日本', post=True)))
    content_type = 'application/x-www-form-urlencoded; charset=%s'
    res = app.post('/', params=dict(name='日本'),
                   headers={'content-type': content_type % 'UTF-8'})

    # Encoding specified: expect unicode. Shiftjis is the default encoding, but
    # params become UTF-8 because the browser specified so
    app = TestApp(AssertApp(assertfunc=valid_name(u'日本', post=True,
                                                  encoding='shiftjis')))
    res = app.post('/', params=dict(name='日本'),
                   headers={'content-type': content_type % 'UTF-8'})

    # Browser did not specify: parse params as the fallback shiftjis
    app = TestApp(AssertApp(assertfunc=valid_name(u'日本', post=True,
                                                  encoding='shiftjis')))
    res = app.post('/', params=dict(name=u'日本'.encode('shiftjis')))
Beispiel #11
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)
Beispiel #12
0
class TestPOST():
    def setUp(self):
        middleware = []
        self.client = TestApp(app.wsgifunc(*middleware))

    def test_set_a_key_value(self):
        lazy_post_url = ''.join([lazy_controller, 'l555'])
        canonical_get_url = ''.join([canonical_controller, 'l555'])
        
        r = self.client.post(lazy_post_url, "testing post method: newly created value")
        assert_equal(r.status, 201)
        r2 = self.client.get(canonical_get_url)
        r2.mustcontain("testing post method: newly created value")

    def test_set_a_key_value_where_key_exists(self):        
        lazy_post_url = ''.join([lazy_controller, 'l655'])
        canonical_url = ''.join([canonical_controller, 'l655'])
        self.client.post(canonical_url, "value exists. over written on canonical. Can be visible in others")
        r2 = self.client.get(canonical_url)
        
        r3 = self.client.post(lazy_post_url, "overwritten the existing value")
        assert_equal(r3.status, 201)
        r4 = self.client.get(canonical_url)
        r4.mustcontain("overwritten the existing value")
    
    def test_long_key_results_error(self):
        """No Assertion required
        """
        key = "".join(map(str, range(40)))
        url_too_long_key = ''.join([lazy_controller, key])
        self.client.post(url_too_long_key, "very very long. longer key than in database. should not get inserted", status=400)
        self.client.get(url_too_long_key, status=404)
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)
Beispiel #14
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)
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
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")
    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'")
Beispiel #18
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'
Beispiel #19
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
Beispiel #20
0
def run_dir(dir):
    static_app = StaticURLParser(dir)
    trans_app = TranscluderMiddleware(static_app)
    app = TestApp(trans_app)
    expected_app = TestApp(static_app)
    
    result = app.get('/index.html')
    expected = expected_app.get('/expected.html')
    html_string_compare(result.body, expected.body)
class TestTemplatingApp(object):
    def setUp(self):
        self.app = TestApp(make_app({'cache_dir': os.path.join(os.path.dirname(__file__), 'cache')}, include_cache_middleware=True))
    
    def test_testvars(self):
        resp = self.app.get('/hello/intro_template')
        assert 'Hi there 6' in resp
    
    def test_template_cache(self):
        resp = self.app.get('/hello/time_template')
        resp2 = self.app.get('/hello/time_template')
        assert resp.body == resp2.body
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
Beispiel #23
0
def test_app1():
    app = TestApp(wsgi_app)
    res = app.get('/get1')
    assert res.body == b'no-info'
    res = app.get('/get2')
    assert res.body ==b'no-info'
    info[:] = ['test']
    res = app.get('/put1')
    res = app.get('/get1')
    assert res.body == b'test'
    res = app.get('/get2')
    assert res.body == b'test'
Beispiel #24
0
def test_different_sessions():
    app = TestApp(SessionMiddleware(simple_app))
    app2 = TestApp(SessionMiddleware(simple_app))
    res = app.get('/')
    assert 'current value is: 1' in res
    res = app2.get('/')
    assert 'current value is: 1' in res
    res = app2.get('/')
    res = app2.get('/')
    res = app2.get('/')
    res2 = app.get('/')
    assert 'current value is: 2' in res2
    assert 'current value is: 4' in res
class TestCWRegionsHandler(unittest.TestCase):
    """
  Unit tests CWRegionsHandler
  """

    @classmethod
    def setUpClass(cls):
        adapter = datasource_adapter_factory.createCloudwatchDatasourceAdapter()
        cls.resources = adapter.describeSupportedMetrics()
        cls.regions = adapter.describeRegions()

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

    @patch("grok.app.webservices.cloudwatch_api.datasource_adapter_factory." "createCloudwatchDatasourceAdapter")
    def testGetListRegionsEmptyResponse(self, adapterMock):
        """
    Test for Get '/_metrics/cloudwatch/regions'
    response is validated for appropriate headers, body and status
    """
        adapterMock.return_value.describeRegions.return_value = []
        response = self.app.get("/regions", headers=self.headers)
        assertions.assertSuccess(self, response)
        result = app_utils.jsonDecode(response.body)
        self.assertEqual(result, {})

    @patch("grok.app.webservices.cloudwatch_api.datasource_adapter_factory." "createCloudwatchDatasourceAdapter")
    def testGetListRegionsNonEmptyResponse(self, adapterMock):
        """
    Test for Get '/_metrics/cloudwatch/regions'
    response is validated for appropriate headers, body and status
    and pre-defined values
    """
        adapterMock.return_value.describeRegions.return_value = self.regions
        response = self.app.get("/regions", headers=self.headers)
        assertions.assertSuccess(self, response)
        result = app_utils.jsonDecode(response.body)
        self.assertEqual(result, dict(self.regions))

    @patch("grok.app.webservices.cloudwatch_api.datasource_adapter_factory." "createCloudwatchDatasourceAdapter")
    def testGetListRegionMetricsEmptyResponse(self, adapterMock):
        """
    Test for Get '/_metrics/cloudwatch/regions/<invalid-region-name>'
    response is validated for appropriate headers, body and status
    response is validated against expected error message
    """
        adapterMock.return_value.describeRegions.return_value = self.regions
        response = self.app.get("/regions/fake-region", status="*", headers=self.headers)
        assertions.assertNotFound(self, response)
        self.assertIn("Region 'fake-region' was not found", response.body)
class MetricsApiUnhappyTest(unittest.TestCase):
  """
  Unhappy tests for Metrics  API
  """


  def setUp(self):
    self.app = TestApp(metrics_api.app.wsgifunc())
    self.headers = getDefaultHTTPHeaders(grok.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("/datasources", 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("/datasources", status="*", headers=invalidHeaders)
    assertions.assertInvalidAuthenticationResponse(self, response)


  def testInvalidRoute(self):
    """
    Invoke non supported route
    resoponse is validated for appropriate headers and body
    """
    response = self.app.get("/foo", status="*", headers=self.headers)
    assertions.assertRouteNotFound(self, response)


  def testInvalidMethod(self):
    """
    Invoe non supported methods
    resoponse is validated for appropriate headers and body
    """
    response = self.app.post("/datasources", status="*", headers=self.headers)
    assertions.assertMethodNotAllowed(self, response)
    headers = dict(response.headers)
    self.assertEqual(headers["Allow"], "GET")
Beispiel #27
0
def test_nosave():
    app = TestApp(SessionMiddleware(simple_app))
    res = app.get('/nosave')
    assert 'current value is: 1' in res
    assert [] == res.all_headers('Set-Cookie')
    res = app.get('/nosave')
    assert 'current value is: 1' in res
    
    res = app.get('/')
    assert 'current value is: 1' in res
    assert len(res.all_headers('Set-Cookie')) > 0
    res = app.get('/')
    assert [] == res.all_headers('Set-Cookie')
    assert 'current value is: 2' in res
Beispiel #28
0
class AjaxTest(unittest.TestCase):


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


  def testSettingsAPIGET(self):
    response = self.app.get("/_settings", headers=self.headers)
    assertions.assertSuccess(self, response)


  @patch.object(repository, "engineFactory", autospec=True)
  @patch.object(repository, "getInstanceStatusHistory", autospec=True)
  @patch.object(repository, 'getAllModels', autospec=True)
  def testModelsAPIGET(self,
                       getAllMetricsMock,
                       getInstanceStatusHistoryMock,
                       engineFactoryMock, *args):
    #import pdb; pdb.set_trace()
    getAllMetricsMock.return_value = []
    getInstanceStatusHistoryMock.return_value = []
    response = self.app.get("/_models", headers=self.headers)
    assertions.assertSuccess(self, response)
    result = app_utils.jsonDecode(response.body)
    self.assertEqual(result, [])
    self.assertTrue(getAllMetricsMock.called)


  @patch.object(metrics_api.MetricsHandler, "getDatasources")
  def testMetricsAPIGETDataSources(self, getDatasources):
    getDatasources.return_value = []
    response = self.app.get("/_metrics/datasources", headers=self.headers)
    assertions.assertSuccess(self, response)
    result = app_utils.jsonDecode(response.body)
    self.assertEqual(result, [])
    self.assertTrue(getDatasources.called)


  @patch("grok.app.webservices.cloudwatch_api.datasource_adapter_factory."
         "createCloudwatchDatasourceAdapter")
  def testMetricsAPIGETCouldWatch(self, adapterMock):
    adapterMock.return_value.describeRegions.return_value = []
    adapterMock.return_value.describeSupportedMetrics.return_value = {}
    response = self.app.get("/_metrics/cloudwatch", headers=self.headers)
    assertions.assertSuccess(self, response)
    result = app_utils.jsonDecode(response.body)
    self.assertEqual(result, {'regions': {}, 'namespaces': {}})
Beispiel #29
0
class TestCode:
    def setup(self):
        middleware = []
        self.testApp = TestApp(app)

    def test_invalid_page_request(self):
        r = self.testApp.get("/", expect_errors=True)
        r.mustcontain("Invalid")
        assert_equal(400, r.status)

    def test_receive_push_sms(self):
        url = ""
        data = {"sender": "0827824665", "text": "53543298", "timestamp": "2013"}

        response = self.testApp.get("/", data, headers={"Content-Type": "text/plain"}, status=200)
Beispiel #30
0
def test_cookie():
    base_dir = os.path.dirname(__file__)
    test_dir = os.path.join(base_dir, 'test-data', 'cookie')
    static_app = StaticURLParser(test_dir)
    cookie_app = CookieMiddleware(static_app)
    transcluder = AnyDomainTranscluderMiddleware(cookie_app)
    test_app = TestApp(transcluder)
    test_static_app = TestApp(static_app)

    result = test_app.get('/index.html')
    expected = test_static_app.get('/expected1.html')
    html_string_compare(result.body, expected.body)
    result = test_app.get('/index.html')
    expected = test_static_app.get('/expected2.html')
    html_string_compare(result.body, expected.body)
Beispiel #31
0
class CWApiUnhappyTest(unittest.TestCase):
    """
  Unhappy tests for Cloudwatch API
  """
    def setUp(self):
        self.app = TestApp(cloudwatch_api.app.wsgifunc())
        self.headers = getDefaultHTTPHeaders(grok.app.config)

    def testNoAuthHeaders(self):
        """
    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)

    def testInvalidAuthHeaders(self):
        """
    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)

    def testInvalidRoute(self):
        """
    Invoke non supported route
    resoponse is validated for appropriate headers and body
    """
        response = self.app.get("/foo", status="*", headers=self.headers)
        assertions.assertRouteNotFound(self, response)

    def testInvalidMethod(self):
        """
    Invoe non supported methods
    resoponse is validated for appropriate headers and body
    """
        response = self.app.post("", status="*", headers=self.headers)
        assertions.assertMethodNotAllowed(self, response)
        headers = dict(response.headers)
        self.assertEqual(headers["Allow"], "GET")
Beispiel #32
0
class TestBasicWSGI(TestWSGIController):
    def __init__(self, *args, **kargs):
        TestWSGIController.__init__(self, *args, **kargs)
        self.baseenviron = {}
        app = ControllerWrap(BasicWSGIController)
        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_wsgi_call(self):
        resp = self.get_response()
        assert 'hello world' in resp

    def test_yield_wrapper(self):
        resp = self.get_response(action='yield_fun')
        assert 'hi' * 100 in resp

    def test_404(self):
        self.environ['paste.config']['global_conf']['debug'] = False
        self.environ['pylons.routes_dict']['action'] = 'notthere'
        resp = self.app.get('/', status=404)
        assert resp.status == 404

    def test_private_func(self):
        self.baseenviron['pylons.routes_dict']['action'] = '_private'
        resp = self.app.get('/', status=404)
        assert resp.status == 404

    def test_strme_func(self):
        self.baseenviron['pylons.routes_dict']['action'] = 'strme'
        resp = self.app.get('/')
        assert "hi there" in resp

    def test_header_check(self):
        self.baseenviron['pylons.routes_dict']['action'] = 'header_check'
        resp = self.app.get('/')
        assert "Hello all!" in resp
        assert resp.response.headers['Content-Type'] == 'text/plain'
        assert resp.response.headers['Cache-Control'] == 'private'
        assert resp.header('Content-Type') == 'text/plain'

    def test_redirect(self):
        self.baseenviron['pylons.routes_dict']['action'] = 'use_redirect'
        resp = self.app.get('/', status=301)

    def test_nothing(self):
        self.baseenviron['pylons.routes_dict']['action'] = 'nothing'
        resp = self.app.get('/')
        assert '' == resp.body
        assert resp.response.headers['Cache-Control'] == 'private'

    def test_unicode_action(self):
        self.baseenviron['pylons.routes_dict'][
            'action'] = u'ОбсуждениеКомпаний'
        resp = self.app.get('/', status=404)
Beispiel #33
0
def test_product_pager():
    """
    Test paginating products is working
    Using ? in modern REST API's... comon
    """
    restApp = TestApp(webservice.app.wsgifunc(*[]))
    req = restApp.get('/products/?page=2')
    product_list = json.loads(req.body)

    assert len(product_list) == 10
Beispiel #34
0
def test_products():
    """
    Test first item in the list has to be cheaper
    than the last item in the list
    """
    restApp = TestApp(webservice.app.wsgifunc(*[]))
    req = restApp.get('/products/')
    products = json.loads(req.body)

    assert products[0]['price'] < products[9]['price']
 def _deleteOneMetric(self):
   """
   Delete one metric from test EC2 instance
   """
   app = TestApp(models_api.app.wsgifunc())
   response = app.get("/", headers=self.headers)
   assertions.assertSuccess(self, response)
   result = app_utils.jsonDecode(response.body)
   self.assertIsInstance(result, list)
   app.delete("/" + result[0]['uid'], headers=self.headers)
    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)
Beispiel #37
0
 def test_add(self):
     middleware = []
     testApp = TestApp(app.wsgifunc(*middleware))
     key = 'test2'
     message = 'jhfsdf'
     obj_data = {'key': key, 'message': message}
     r1 = testApp.post('/storage/' + key, params=json.dumps(obj_data))
     r = testApp.get('/storage/' + key)
     self.assertEqual(r1.status, 200)
     self.assertEqual(r.status, 200)
     self.assertEqual(json.loads(r.body.decode('utf-8'))['message'], message)
Beispiel #38
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

        class WithUnavailable(middleware_app.ImplementationWrapper):
            cls = AuxImplementationWithUnavailableError

        class WithMissingArgument(middleware_app.ImplementationWrapper):
            cls = AuxImplementationWithMissingArgumentError

        class WithBadArgument(middleware_app.ImplementationWrapper):
            cls = AuxImplementationWithBadArgumentError

        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)
        self.assertEqual(response.status, 404)

        # Test a Timeout error
        response = testapp.get('/aux/unavailable', expect_errors=True)
        self.assertEqual(response.status, 408)

        # Test BadRequest errors
        response = testapp.get('/aux/missing', expect_errors=True)
        self.assertEqual(response.status, 400)
        response = testapp.get('/aux/bad', expect_errors=True)
        self.assertEqual(response.status, 400)
Beispiel #39
0
class TestWsgiApp(object):
    def setUp(self):
        from paste.fixture import TestApp
        from routes.util import URLGenerator
        
        app = make_app({})
        self.app = TestApp(app)
        self.url = URLGenerator(app.config['routes.map'], {})
    
    def test_testvars(self):
        resp = self.app.get('/_test_vars', extra_environ={'paste.testing_variables': True})
        assert re.match(r'^\d+$', resp.body)
    
    def test_exception_resp_attach(self):
        resp = self.app.get('/test_func', expect_errors=True)
        assert resp.status == 404
    
    @raises(Exception)
    def test_no_content(self):
        resp = self.app.get('/test_empty', expect_errors=True)
        assert 'wontgethre'
    
    def test_middleware_cache_obj_instance(self):
        from paste.fixture import TestApp
        app = TestApp(make_app({}, include_cache_middleware=True))
        resp = app.get('/hello/index')
        assert resp.cache
    
    def test_attribsafe_tmpl_context(self):
        from paste.fixture import TestApp
        app = TestApp(make_app({}, attribsafe=True))
        resp = app.get('/hello/index')
        assert 'Hello World' in resp
    
    def test_cache_obj_appglobals(self):
        resp = self.app.get('/hello/index', extra_environ={'paste.testing_variables': True})
        assert resp.cache == 'Nothing here but a string'
    
    def test_controller_name_override(self):
        resp = self.app.get('/goodbye/index')
        assert 'Hello World' in resp
Beispiel #40
0
class Test():
    def setUp(self):
        middleware = []
        self.testApp = TestApp(app.wsgifunc(*middleware))

    def test_homepage_route(self):
        r = self.testApp.get('/')
        assert_equal(r.status, 200)
        r.mustcontain('A REST way to manage your Cron')
        r.mustcontain('curl -XGET http://localhost:8080/cron')
        r.mustcontain('curl -XGET http://localhost:8080/cron/1')
        r.mustcontain('curl -XDELETE http://localhost:8080/cron/2')

    def test_cron_list_route(self):
        r = self.testApp.get('/cron')
        assert_equal(r.status, 200)
        r.mustcontain('"id": 1')
        r.mustcontain('"minute": "0"')
        r.mustcontain('"hour": "3"')
        r.mustcontain('"day_of_month": "*"')
        r.mustcontain('"day_of_week": "*"')
        r.mustcontain('"month": "*"')
        r.mustcontain('curl -I http://eher.com.br/')
        r.mustcontain('"id": 2')
        r.mustcontain('"minute": "1"')
        r.mustcontain('"hour": "*"')
        r.mustcontain('"day_of_month": "*"')
        r.mustcontain('"day_of_week": "*"')
        r.mustcontain('"month": "*"')
        r.mustcontain('curl -I http://chegamos.com/')

    def test_cron_route(self):
        r = self.testApp.get('/cron/1')
        assert_equal(r.status, 200)
        r.mustcontain('"id": 1')
        r.mustcontain('"minute": "0"')
        r.mustcontain('"hour": "3"')
        r.mustcontain('"day_of_month": "*"')
        r.mustcontain('"day_of_week": "*"')
        r.mustcontain('"month": "*"')
        r.mustcontain('curl -I http://eher.com.br/')
Beispiel #41
0
class AjaxTest(unittest.TestCase):
    def setUp(self):
        self.headers = getDefaultHTTPHeaders(grok.app.config)
        self.app = TestApp(webapp.app.wsgifunc())

    def testSettingsAPIGET(self):
        response = self.app.get("/_settings", headers=self.headers)
        assertions.assertSuccess(self, response)

    @patch.object(repository, "engineFactory", autospec=True)
    @patch.object(repository, "getInstanceStatusHistory", autospec=True)
    @patch.object(repository, 'getAllModels', autospec=True)
    def testModelsAPIGET(self, getAllMetricsMock, getInstanceStatusHistoryMock,
                         engineFactoryMock, *args):
        #import pdb; pdb.set_trace()
        getAllMetricsMock.return_value = []
        getInstanceStatusHistoryMock.return_value = []
        response = self.app.get("/_models", headers=self.headers)
        assertions.assertSuccess(self, response)
        result = app_utils.jsonDecode(response.body)
        self.assertEqual(result, [])
        self.assertTrue(getAllMetricsMock.called)

    @patch.object(metrics_api.MetricsHandler, "getDatasources")
    def testMetricsAPIGETDataSources(self, getDatasources):
        getDatasources.return_value = []
        response = self.app.get("/_metrics/datasources", headers=self.headers)
        assertions.assertSuccess(self, response)
        result = app_utils.jsonDecode(response.body)
        self.assertEqual(result, [])
        self.assertTrue(getDatasources.called)

    @patch("grok.app.webservices.cloudwatch_api.datasource_adapter_factory."
           "createCloudwatchDatasourceAdapter")
    def testMetricsAPIGETCouldWatch(self, adapterMock):
        adapterMock.return_value.describeRegions.return_value = []
        adapterMock.return_value.describeSupportedMetrics.return_value = {}
        response = self.app.get("/_metrics/cloudwatch", headers=self.headers)
        assertions.assertSuccess(self, response)
        result = app_utils.jsonDecode(response.body)
        self.assertEqual(result, {'regions': {}, 'namespaces': {}})
Beispiel #42
0
def test_home_page_redirects_to_cas():
    '''A plain request for the homepage redirects us to the CAS login page:

      >>> t, r1 = test_home_page_redirects_to_cas()
      >>> dict(r1.headers)['Location']
      'https://example/cas/login?service=http%3A%2F%2Fheron-service%2F'

    '''
    from paste.fixture import TestApp
    t = TestApp(Mock.make([HeronAdminConfig])[0].make_wsgi_app())
    r1 = t.get('/', status=303)
    return t, r1
Beispiel #43
0
def test_product_id():
    """
    Test that we get product data by product id
    when it's passed as a URL parameter
    """
    product = Product.get()

    restApp = TestApp(webservice.app.wsgifunc(*[]))
    req = restApp.get("/product/{0}/".format(product.product_id))
    product_data = json.loads(req.body)

    assert product.name == product_data['name']
Beispiel #44
0
    def test_GET(self):
        middleware = []
        testApp = TestApp(app.wsgifunc(*middleware))

        # Return all thermostats with 200 OK
        r = testApp.get('/thermostats', {'content-type': 'application/json'})
        json_data = json.loads(r.body)
        assert_equal(r.status, 200)
        assert_equal(json_data, thermostats)

        # Return thermostat with id 100 with 200 OK
        r = testApp.get('/thermostats/100',
                        {'content-type': 'application/json'})
        json_data = json.loads(r.body)
        assert_equal(r.status, 200)
        assert_equal(json_data, thermostats[0])

        # Return 404 error for thermostat that doesn't exists
        r = testApp.get('/thermostats/102', status="*")
        assert_equal(r.status, 404)
        r.mustcontain('not found')
Beispiel #45
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")
Beispiel #46
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")
Beispiel #47
0
def test_wsgirequest_charset():
    # Jose, 'José'
    app = TestApp(
        AssertApp(assertfunc=valid_name(u'José', encoding='iso-8859-1')))
    res = app.get('/?name=Jos%E9')

    # Tanaka, '田中'
    app = TestApp(AssertApp(assertfunc=valid_name(u'田中', encoding='UTF-8')))
    res = app.get('/?name=%E7%94%B0%E4%B8%AD')

    # Nippon (Japan), '日本'
    app = TestApp(
        AssertApp(assertfunc=valid_name(u'日本', encoding='UTF-8', post=True)))
    res = app.post('/', params=dict(name='日本'))

    # WSGIRequest will determine the charset from the Content-Type header when
    # unicode is expected.
    # No encoding specified: not expecting unicode
    app = TestApp(AssertApp(assertfunc=valid_name('日本', post=True)))
    content_type = 'application/x-www-form-urlencoded; charset=%s'
    res = app.post('/',
                   params=dict(name='日本'),
                   headers={'content-type': content_type % 'UTF-8'})

    # Encoding specified: expect unicode. Shiftjis is the default encoding, but
    # params become UTF-8 because the browser specified so
    app = TestApp(
        AssertApp(
            assertfunc=valid_name(u'日本', post=True, encoding='shiftjis')))
    res = app.post('/',
                   params=dict(name='日本'),
                   headers={'content-type': content_type % 'UTF-8'})

    # Browser did not specify: parse params as the fallback shiftjis
    app = TestApp(
        AssertApp(
            assertfunc=valid_name(u'日本', post=True, encoding='shiftjis')))
    res = app.post('/', params=dict(name=u'日本'.encode('shiftjis')))
Beispiel #48
0
def init_mediadrop(config_filename, here_dir=None, disable_logging=False):
    if not os.path.exists(config_filename):
        raise IOError('Config file %r does not exist.' % config_filename)
    if here_dir is None:
        here_dir = os.getcwd()
    if not disable_logging:
        logging_config.fileConfig(config_filename)

    config_name = 'config:%s' % config_filename
    # XXX: Note, initializing CONFIG here is Legacy support. pylons.config
    # will automatically be initialized and restored via the registry
    # restorer along with the other StackedObjectProxys
    # Load app config into paste.deploy to simulate request config
    # Setup the Paste CONFIG object, adding app_conf/global_conf for legacy
    # code
    conf = appconfig(config_name, relative_to=here_dir)
    conf.update(dict(app_conf=conf.local_conf, global_conf=conf.global_conf))
    paste.deploy.config.CONFIG.push_thread_config(conf)

    # Load locals and populate with objects for use in shell
    sys.path.insert(0, here_dir)

    # WebOb 1.2+ does not support unicode_errors/decode_param_names anymore for
    # the Request() class so we need to override Pylons' defaults to prevent
    # DeprecationWarnings (only shown in Python 2.6 by default).
    webob_request_options = {
        'charset': 'utf-8',
        'errors': None,
        'decode_param_names': None,
        'language': 'en-us',
    }
    global_conf = {'pylons.request_options': webob_request_options}
    # Load the wsgi app first so that everything is initialized right
    wsgiapp = loadapp(config_name,
                      relative_to=here_dir,
                      global_conf=global_conf)
    test_app = TestApp(wsgiapp)

    # Query the test app to setup the environment
    tresponse = test_app.get('/_test_vars')
    request_id = int(tresponse.body)

    # Disable restoration during test_app requests
    test_app.pre_request_hook = lambda self: paste.registry.restorer.restoration_end(
    )
    test_app.post_request_hook = lambda self: paste.registry.restorer.restoration_begin(
        request_id)

    # Restore the state of the Pylons special objects (StackedObjectProxies)
    paste.registry.restorer.restoration_begin(request_id)
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])
    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)
Beispiel #51
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)
class TestCode(object):
    '''
        go to individual module view, press edit mounting, check if
        edit mounting is loaded correctly.
    '''
    URL_INDIVIDUAL_MOUNTING = '/individualModuleInfo?code=BT5110&aysem=AY+17%2F18+Sem+1'
    URL_EDIT_MOUNTING = '/editMounting?code=BT5110&aysem=AY+17%2F18+Sem+1'
    EDIT_MOUNTING_BUTTON_FORM_ID = 'edit-mounting-button'
    EDIT_MOUNTING_FORM_ID = 'edit-mounting-form'

    def __init__(self):
        self.middleware = None
        self.test_app = None

    def setUp(self):
        '''
            Sets up the 'app.py' fixture
        '''
        self.middleware = []
        self.test_app = TestApp(APP.wsgifunc(*self.middleware))
        session.set_up(self.test_app)

    def tearDown(self):
        '''
            Tears down 'app.py' fixture and logs out
        '''
        session.tear_down(self.test_app)

    def test_mounting_edit_submit_button(self):
        '''
            tests whether the user accessed mounting edit page has a submit
            button and works as intended
        '''
        root = self.test_app.get(self.URL_EDIT_MOUNTING)
        assert_equal(root.status, 200)
        #tests if the correct page is loaded
        root.mustcontain('BT5110')
        root.mustcontain('Module Info')

        submit_edit_mounting_form = root.forms__get()[
            self.EDIT_MOUNTING_FORM_ID]
        root = submit_edit_mounting_form.submit()
        assert_equal(root.status, 200)

        #redirect back to individual module info page
        root.mustcontain("edited successfully")
Beispiel #53
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
class CWDefaultHandlerTest(unittest.TestCase):
    """
  Integration test CWDefaultHandler
  """
    def setUp(self):
        self.app = TestApp(cloudwatch_api.app.wsgifunc())
        self.headers = getDefaultHTTPHeaders(grok.app.config)

    def _testGETCloudWatchImpl(self, url):
        response = self.app.get(url, headers=self.headers)
        assertions.assertSuccess(self, response)
        result = app_utils.jsonDecode(response.body)
        self.assertIsInstance(result, dict)

        supportedMetrics = createCloudwatchDatasourceAdapter(
        ).describeSupportedMetrics()

        for metrics in supportedMetrics.values():
            for metric, keys in metrics.items():
                self.assertIn(
                    keys["namespace"], result["namespaces"],
                    "Expected namespace (%s) not found in response." %
                    (keys["namespace"]))
                self.assertIn(
                    metric, result["namespaces"][keys["namespace"]]["metrics"],
                    "Expected metric (%s, %s) not found in response." %
                    (keys["namespace"], metric))

    @ManagedTempRepository("CWDefaultHandlerTest")
    def testGETCloudWatch(self):
        """
    Test for Get '/_metrics/cloudwatch'
    response is validated for appropriate headers, body and status
    response is validated against known namespaces and available metrics
    """
        self._testGETCloudWatchImpl("")

    @ManagedTempRepository("CWDefaultHandlerTest")
    def testGETCloudWatchWithSlash(self):
        """
    Test for Get '/_metrics/cloudwatch'
    response is validated for appropriate headers, body and status
    response is validated against known namespaces and available metrics
    """
        self._testGETCloudWatchImpl("/")
Beispiel #55
0
class TestJsonifyDecorator(object):
    def setUp(self):
        from paste.fixture import TestApp
        from routes.util import URLGenerator
        app = make_app({})
        self.config = app.config
        self.app = TestApp(app)
        self.url = URLGenerator(app.config['routes.map'], {})
    
    def test_basic_response(self):
        response = self.app.get('/hello/index')
        assert 'Hello World' in response
    
    def test_config(self):
        import pylons
        import pylons.configuration as configuration
        assert pylons.config == configuration.config

    @raises(AssertionError)
    def test_eval(self):
        from paste.fixture import TestApp
        app = TestApp(make_app(dict(debug='True')))
        app.get('/hello/oops', status=500, extra_environ={'paste.throw_errors': False})

    def test_set_lang(self):
        self._test_set_lang('set_lang')

    def test_set_lang_pylonscontext(self):
        self._test_set_lang('set_lang_pylonscontext')

    def _test_set_lang(self, action):
        response = self.app.get(self.url(controller='i18nc', action=action, lang='ja'))
        assert u'\u8a00\u8a9e\u8a2d\u5b9a\u3092\u300cja\u300d\u306b\u5909\u66f4\u3057\u307e\u3057\u305f'.encode('utf-8') in response
        response = self.app.get(self.url(controller='i18nc', action=action, lang='ch'))
        assert 'Could not set language to "ch"' in response

    def test_detect_lang(self):
        response = self.app.get(self.url(controller='i18nc', action='i18n_index'), headers={
                'Accept-Language':'fr;q=0.6, en;q=0.1, ja;q=0.3'})
        # expect japanese fallback for nonexistent french.
        assert u'\u6839\u672c\u30a4\u30f3\u30c7\u30af\u30b9\u30da\u30fc\u30b8'.encode('utf-8') in response

    def test_no_lang(self):
        response = self.app.get(self.url(controller='i18nc', action='no_lang'))
        assert 'No language' in response
        assert 'No languages' in response
    
    def test_langs(self):
        response = self.app.get(self.url(controller='i18nc', action='langs'), headers={
                'Accept-Language':'fr;q=0.6, en;q=0.1, ja;q=0.3'})
        assert "['fr', 'ja', 'en-us']" in response
Beispiel #56
0
class CWDefaultHandlerTest(unittest.TestCase):
  """
  Unit tests CWDefaultHandler
  """

  def setUp(self):
    self.headers = getDefaultHTTPHeaders(htm.it.app.config)
    self.app = TestApp(cloudwatch_api.app.wsgifunc())
    adapter = datasource_adapter_factory.createCloudwatchDatasourceAdapter()
    self.resources = adapter.describeSupportedMetrics()
    self.regions = adapter.describeRegions()


  def _getCloudWatchCommon(self, url, expectedResult):
    response = self.app.get(url, headers=self.headers)
    assertions.assertSuccess(self, response)
    result = app_utils.jsonDecode(response.body)
    self.assertIsInstance(result, dict)
    self.assertEqual(result, expectedResult)


  @patch("htm.it.app.webservices.cloudwatch_api.datasource_adapter_factory."
         "createCloudwatchDatasourceAdapter")
  def testCWDefaultHandlerDefault(self, adapterMock):
    """
    Test for Get '/_metrics/cloudwatch'
    response is validated for appropriate headers, body and status
    """
    adapterMock.return_value.describeRegions.return_value = []
    adapterMock.return_value.describeSupportedMetrics.return_value = {}
    self._getCloudWatchCommon("", {"regions": {}, "namespaces": {}})


  @patch("htm.it.app.webservices.cloudwatch_api.datasource_adapter_factory."
         "createCloudwatchDatasourceAdapter")
  def testCWDefaultHandlerDefaultWithSlash(self, adapterMock):
    """
    Test for Get '/_metrics/cloudwatch/'
    response is validated for appropriate headers, body and status
    """
    adapterMock.return_value.describeRegions.return_value = []
    adapterMock.return_value.describeSupportedMetrics.return_value = {}
    self._getCloudWatchCommon("/", {"regions": {}, "namespaces": {}})
    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'
        )])
Beispiel #58
0
class MetricsHandlerTest(unittest.TestCase):
    """
  Integration tests for  metrics API
  """
    def setUp(self):
        self.headers = getDefaultHTTPHeaders(grok.app.config)
        self.app = TestApp(metrics_api.app.wsgifunc())

    @ManagedTempRepository("MettricsHandlerTest")
    def testGETDatasources(self):
        """
    Test for GET for '/_metrics/datasources'
    response is validated for appropriate headers and body
    """
        response = self.app.get('/datasources', headers=self.headers)
        assertions.assertSuccess(self, response)
        self.assertIsInstance(utils.jsonDecode(response.body), list)
        self.assertSetEqual(set(utils.jsonDecode(response.body)),
                            set(["autostack", "custom", "cloudwatch"]))
    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')
Beispiel #60
0
class TestHelpers(TestWSGIController):
    def __init__(self, *args, **kargs):
        from pylons.testutil import ControllerWrap, SetupCacheGlobal
        HelpersController = make_helperscontroller()
        TestWSGIController.__init__(self, *args, **kargs)
        self.baseenviron = {}
        app = ControllerWrap(HelpersController)
        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)
        warnings.simplefilter('error', DeprecationWarning)

    def tearDown(self):
        warnings.simplefilter('always', DeprecationWarning)

    def test_return_etag_cache(self):
        self.baseenviron['pylons.routes_dict']['action'] = 'test_etag_cache'
        response = self.app.get('/')
        assert '"test"' == response.header('Etag')
        assert 'from etag_cache' in response