Exemple #1
0
class TestSession(unittest.TestCase):

    def setUp(self):
        self.app = make_wsgi('Testruns')
        self.client = Client(self.app, BaseResponse)

    def tearDown(self):
        self.client = None
        self.app = None

    def test_session_persist(self):
        r = self.client.get('/sessiontests/setfoo')

        self.assertEqual(r.status, '200 OK')
        self.assertEqual(r.data, b'foo set')

        r = self.client.get('/sessiontests/getfoo')

        self.assertEqual(r.status, '200 OK')
        self.assertEqual(r.data, b'bar')

    def test_session_regen_id(self):
        ta = TestApp(self.app)

        r = ta.get('/sessiontests/setfoo', status=200)
        assert r.session['foo'] == 'bar'
        sid = r.session.id
        assert sid in r.headers['Set-Cookie']

        r = ta.get('/sessiontests/regenid', status=200)
        assert r.session.id != sid
        assert r.session.id in r.headers['Set-Cookie']

        r = ta.get('/sessiontests/getfoo', status=200)
        assert r.body == b'bar'
Exemple #2
0
class SessionMiddlewareTestCase(GAETestBase):
  KIND_NAME_UNSWAPPED = False
  USE_PRODUCTION_STUBS = True
  CLEANUP_USED_KIND = True

  def setUp(self):
    s = LazySettings(settings_module='kay.tests.settings')
    app = get_application(settings=s)
    self.client = Client(app, BaseResponse)

  def tearDown(self):
    pass

  def test_countup(self):
    response = self.client.get('/countup')
    self.assertEqual(response.status_code, 200)
    self.assertEqual(response.data, '1')
    response = self.client.get('/countup')
    self.assertEqual(response.data, '2')
    response = self.client.get('/countup')
    self.assertEqual(response.data, '3')
    response = self.client.get('/countup')
    self.assertEqual(response.data, '4')
    response = self.client.get('/countup')
    self.assertEqual(response.data, '5')
Exemple #3
0
class TestUserFunctional(unittest.TestCase):
    def setUp(self):
        self.app = make_wsgi('Testruns')
        self.client = Client(self.app, BaseResponse)

    def tearDown(self):
        self.client = None
        self.app = None

    def test_attr(self):
        r = self.client.get('/usertests/setfoo')

        self.assertEqual(r.status, '200 OK')
        self.assertEqual(r.data, b'foo set')

        r = self.client.get('/usertests/getfoo')

        self.assertEqual(r.status, '200 OK')
        self.assertEqual(r.data, b'barbaz')

    def test_auth(self):
        r = self.client.get('/usertests/setauth')

        self.assertEqual(r.status, '200 OK')

        r = self.client.get('/usertests/getauth')

        self.assertEqual(r.status, '200 OK')
        self.assertEqual(r.data, b'True')

    def test_perm(self):
        r = self.client.get('/usertests/addperm')

        self.assertEqual(r.status, '200 OK')

        r = self.client.get('/usertests/getperms')

        self.assertEqual(r.status, '200 OK')
        self.assertEqual(r.data, b'TrueFalseTrue')

    def test_clear(self):
        r = self.client.get('/usertests/clear')

        self.assertEqual(r.status, '200 OK')
        self.assertEqual(r.data, b'FalseFalseNone')

    def test_message(self):
        r = self.client.get('/usertests/setmsg')

        self.assertEqual(r.status, '200 OK')

        r = self.client.get('/usertests/getmsg')

        self.assertEqual(r.status, '200 OK')
        self.assertEqual(r.data, b'test: my message')

        r = self.client.get('/usertests/nomsg')

        self.assertEqual(r.status, '200 OK')
        self.assertEqual(r.data, b'0')
Exemple #4
0
class TestWSLoader(unittest.TestCase):
    def setUp(self):
        app = wsloader.WSLoader(confdir = os.getcwd() + '/conf/')
        self.client = Client(app, BaseResponse)

    def test_service_check(self):
        response = self.client.get("/greeter/service_check")
        print response.data
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.data, "OK")

    def test_defaults(self):
        response = self.client.get("/greeter/say_hello")
        self.assertEqual(response.status_code, 200)
        body = json.loads(response.data)
        self.assertEqual(body['response'], "Hello World!")

    def test_aliased_class(self):
        response = self.client.get('/helloworld/say_hello?greeting="Hola"&to_whom="Amigos!"')
        try:
            body = json.loads(response.data)
        except Exception, e:
            print e
            print response.data
            return
        self.assertEqual(body['response'], "Hola Amigos!")
Exemple #5
0
class TestSession(unittest.TestCase):
    def setUp(self):
        self.app = make_wsgi('Testruns')
        self.client = Client(self.app, BaseResponse)

    def tearDown(self):
        self.client = None
        self.app = None

    def test_session_persist(self):
        r = self.client.get('/sessiontests/setfoo')

        self.assertEqual(r.status, '200 OK')
        self.assertEqual(r.data, b'foo set')

        r = self.client.get('/sessiontests/getfoo')

        self.assertEqual(r.status, '200 OK')
        self.assertEqual(r.data, b'bar')

    def test_session_regen_id(self):
        ta = TestApp(self.app)

        r = ta.get('/sessiontests/setfoo', status=200)
        assert r.session['foo'] == 'bar'
        sid = r.session.id
        assert sid in r.headers['Set-Cookie']

        r = ta.get('/sessiontests/regenid', status=200)
        assert r.session.id != sid
        assert r.session.id in r.headers['Set-Cookie']

        r = ta.get('/sessiontests/getfoo', status=200)
        assert r.body == b'bar'
class SessionMiddlewareTestCase(GAETestBase):
    KIND_NAME_UNSWAPPED = False
    USE_PRODUCTION_STUBS = True
    CLEANUP_USED_KIND = True

    def setUp(self):
        s = LazySettings(settings_module='kay.tests.settings')
        app = get_application(settings=s)
        self.client = Client(app, BaseResponse)

    def tearDown(self):
        pass

    def test_countup(self):
        response = self.client.get('/countup')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.data, '1')
        response = self.client.get('/countup')
        self.assertEqual(response.data, '2')
        response = self.client.get('/countup')
        self.assertEqual(response.data, '3')
        response = self.client.get('/countup')
        self.assertEqual(response.data, '4')
        response = self.client.get('/countup')
        self.assertEqual(response.data, '5')
Exemple #7
0
class TasksViewTest(unittest.TestCase):

    def setUp(self):
        self.c = Client(views.handler, BaseResponse)
        # clear state
        views.TASKS = {}
        views.clients = {}
        views.subscriptions = {}

    def test_POST(self):
        t = models.Task(name='Task1')
        r = self.c.post(path='/tasks/', headers={'Content-Type':tubes.JSON}, data=t.to_json_str())

        # check response
        self.assertEquals(r.status_code, 201)
        task = json.loads(r.data)
        self.assertEquals(task['name'], 'Task1')
        self.assertTrue('/tasks/0' in r.headers.get('Location'))

        # back-end
        task = views.TASKS['0']
        self.assertTrue(task != None)
        self.assertEquals(task.name, 'Task1')

    def test_PUT(self):
        views.TASKS['0'] = models.Task()
        r = self.c.put(path='/tasks/0',
                       headers={'Content-Type':tubes.JSON},
                       data=models.Task(name='Task_0').to_json_str())
        self.assertEquals(r.status_code, 200)

        # check response
        task = json.loads(r.data)
        self.assertEquals(task['name'], 'Task_0')

        # back-end
        task = views.TASKS['0']
        self.assertEquals(task.name, 'Task_0')

    def test_DELETE(self):
        views.TASKS['0'] = models.Task()
        r = self.c.delete(path='/tasks/0')
        self.assertEquals(r.status_code, 204)
        self.assertTrue(views.TASKS.get('0') == None)

    def test_GET_tasks(self):
        views.TASKS['0'] = models.Task(name='foo')
        r = self.c.get(path='/tasks/')
        self.assertTrue('foo' in r.data)

    def test_GET_task(self):
        views.TASKS['0'] = models.Task(name='foo')
        r = self.c.get(path='/tasks/0')
        self.assertTrue('foo' in r.data)
Exemple #8
0
class MaintenanceCheckTestCase(unittest.TestCase):
  
  def setUp(self):
    apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
    stub = datastore_file_stub.DatastoreFileStub('test','/dev/null',
                                                 '/dev/null')
    apiproxy_stub_map.apiproxy.RegisterStub('datastore_v3', stub)

    apiproxy_stub_map.apiproxy.RegisterStub(
      'user', user_service_stub.UserServiceStub())

    apiproxy_stub_map.apiproxy.RegisterStub(
      'memcache', memcache_stub.MemcacheServiceStub())

    apiproxy_stub_map.apiproxy.RegisterStub(
      'urlfetch', urlfetch_stub.URLFetchServiceStub())

    s = LazySettings(settings_module='kay.tests.settings')
    app = get_application(settings=s)
    self.client = Client(app, BaseResponse)
    if apiproxy_stub_map.apiproxy\
          ._APIProxyStubMap__stub_map.has_key('capability_service'):
      del(apiproxy_stub_map.apiproxy\
            ._APIProxyStubMap__stub_map['capability_service'])

  def tearDown(self):
    pass

  def test_success(self):
    """Test with normal CapabilityServiceStub"""
    apiproxy_stub_map.apiproxy.RegisterStub(
      'capability_service',
      capability_stub.CapabilityServiceStub())
    response = self.client.get('/')
    self.assertEqual(response.status_code, 200)

  def test_failure(self):
    """Test with DisabledCapabilityServiceStub
    """
    apiproxy_stub_map.apiproxy.RegisterStub(
      'capability_service',
      mocked_capability_stub.DisabledCapabilityServiceStub())
    response = self.client.get('/')
    self.assertEqual(response.status_code, 302)
    self.assertEqual(response.headers['Location'],
                     'http://localhost/maintenance_page')

    response = self.client.get('/index2')
    self.assertEqual(response.status_code, 302)
    self.assertEqual(response.headers['Location'],
                     'http://localhost/no_decorator')
    response = self.client.get('/no_decorator')
    self.assertEqual(response.status_code, 200)
Exemple #9
0
 def test_get_transaction_by_id(
     self,
     authorized_client: Client,
     allow_user_to_account,
     get_transaction_by_id_mock,
 ) -> None:
     rv: Response = authorized_client.get("/account/transactions/1", )
     assert rv.status_code == 200
     transaction = rv.get_json()
     assert get_transaction_by_id_mock["transaction_id"] == 1
     assert transaction == {
         "id": 1,
         "amount": 100,
         "currency": DiemCurrency.Coin1.value,
         "direction": TransactionDirection.SENT.value,
         "status": TransactionStatus.COMPLETED.value,
         "timestamp": "2020-06-23T19:49:26.989849",
         "source": {
             "full_addr":
             "tlb1p42424242424242424242424242rrhsrrm79jhucp0lc9r",
             "user_id": "863bc063df8b2bf3",
             "vasp_name": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
         },
         "destination": {
             "full_addr":
             "tlb1p4242424242424242424242424f6mztxd826s8fsfpwcy3",
             "user_id": "75b12ccd3ab503a6",
             "vasp_name": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
         },
         "blockchain_tx": None,
         "is_internal": True,
     }
Exemple #10
0
 def test_get_account_transactions(
     self,
     authorized_client: Client,
     allow_user_to_account,
     account_transactions_mock,
 ) -> None:
     rv: Response = authorized_client.get(
         "/account/transactions",
     )
     assert rv.status_code == 200
     transactions = rv.get_json()
     assert len(transactions) == 1
     assert transactions["transaction_list"] == [
         {
             "id": 1,
             "amount": 100,
             "currency": DiemCurrency.XUS.value,
             "direction": TransactionDirection.SENT.value,
             "status": TransactionStatus.COMPLETED.value,
             "timestamp": "2020-06-23T19:49:26.989849",
             "source": {
                 "full_addr": "tdm1p42424242424242424242424242rrhsrrm79jhuckttdwm",
                 "user_id": "863bc063df8b2bf3",
                 "vasp_name": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
             },
             "destination": {
                 "full_addr": "tdm1p4242424242424242424242424f6mztxd826s8fs796d0f",
                 "user_id": "75b12ccd3ab503a6",
                 "vasp_name": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
             },
             "blockchain_tx": None,
             "is_internal": True,
         }
     ]
Exemple #11
0
class AppStatsMiddlewareTestCase(GAETestBase):
  KIND_NAME_UNSWAPPED = False
  USE_PRODUCTION_STUBS = True
  CLEANUP_USED_KIND = True

  def setUp(self):
    from google.appengine.api import memcache
    memcache.flush_all()
    s = LazySettings(settings_module='kay.tests.appstats_settings')
    app = get_application(settings=s)
    self.client = Client(app, BaseResponse)

  def tearDown(self):
    pass

  def test_appstats_middleware(self):

    request = Request({})
    middleware = AppStatsMiddleware()

    r = middleware.process_request(request)
    self.assertTrue(r is None)

    r = middleware.process_response(request, BaseResponse("", 200))
    self.assertTrue(isinstance(r, BaseResponse))

    summary = recording.load_summary_protos()
    self.assert_(summary)

  def test_appstats_middleware_request(self):

    response = self.client.get('/no_decorator')
    summary = recording.load_summary_protos()
    self.assert_(summary)
Exemple #12
0
class CronOnlyTestCase(GAETestBase):

  def setUp(self):
    s = LazySettings(settings_module='kay.tests.settings')
    app = get_application(settings=s)
    self.client = Client(app, BaseResponse)

  def test_cron_only(self):
    response = self.client.get("/cron",
            headers=(('X-AppEngine-Cron', 'true'),))
    self.assertEqual(response.status_code, 200)
    self.assertTrue(response.data == "OK")

  def test_cron_only_failure(self):
    response = self.client.get("/cron")
    self.assertEqual(response.status_code, 403)
Exemple #13
0
class AppStatsMiddlewareTestCase(GAETestBase):
    KIND_NAME_UNSWAPPED = False
    USE_PRODUCTION_STUBS = True
    CLEANUP_USED_KIND = True

    def setUp(self):
        from google.appengine.api import memcache
        memcache.flush_all()
        s = LazySettings(settings_module='kay.tests.appstats_settings')
        app = get_application(settings=s)
        self.client = Client(app, BaseResponse)

    def tearDown(self):
        pass

    def test_appstats_middleware(self):

        request = Request({})
        middleware = AppStatsMiddleware()

        r = middleware.process_request(request)
        self.assertTrue(r is None)

        r = middleware.process_response(request, BaseResponse("", 200))
        self.assertTrue(isinstance(r, BaseResponse))

        summary = recording.load_summary_protos()
        self.assert_(summary)

    def test_appstats_middleware_request(self):

        response = self.client.get('/no_decorator')
        summary = recording.load_summary_protos()
        self.assert_(summary)
class DownloadicsTest(GAETestBase):

    def setUp(self):
        app = get_application()
        self.client = Client(app, BaseResponse)

        self.test_values = {
            'date': datetime.datetime(2016, 5, 20, 15, 0),
            'title': 'THIS IS TITLE',
            'description': 'THIS IS TITLE',
        }

        eve = Event(
            event_date=self.test_values['date'],
            title=self.test_values['title'],
            description=self.test_values['description'],
        )
        eve.put()
        events = Event.all().fetch(100)
        self.assertEquals(len(events), 1)
        self.assertEquals(events[0].title, 'THIS IS TITLE')
        self.event_key = str(events[0].key())

    def test_download_individual_icsfile(self):
        target_url = urlparse.urljoin('/ical/', self.event_key)
        res = self.client.get(target_url)
        self.assertEquals(res.status_code, 200)

        downloaded = res.get_data()
        reparsed = icalendar.Calendar.from_ical(downloaded)
        reparsed_eve = reparsed.walk('VEVENT')[0]
        stringfied = self.test_values['date'].strftime('%Y%m%dT%H%M%S')
        self.assertEquals(reparsed_eve['summary'].to_ical(), self.test_values['title'])
        self.assertEquals(reparsed_eve['dtstart'].to_ical(), stringfied)
        self.assertEquals(reparsed_eve['description'].to_ical(), self.test_values['description'])
Exemple #15
0
def test_responder():
    """Responder decorator"""
    def foo(environ, start_response):
        return BaseResponse('Test')
    client = Client(responder(foo), BaseResponse)
    response = client.get('/')
    assert response.status_code == 200
    assert response.data == 'Test'
Exemple #16
0
 def test_user_get_all(self, client: Client):
     register_user(client)
     login_resp = login_user(client)
     resp = client.get(
         url_for("user.get_users"),
         headers={"Authorization": f"Bearer {login_resp.json['token']}"},
     )
     assert resp.status_code == 401
Exemple #17
0
 def test_get_transaction_by_id_other_user(
     self,
     authorized_client: Client,
     allow_user_to_account,
     get_transaction_by_id_mock,
 ) -> None:
     rv: Response = authorized_client.get("/account/transactions/2", )
     assert get_transaction_by_id_mock["transaction_id"] == 2
     assert rv.status_code == 404
Exemple #18
0
 def test_get_account_info(self, authorized_client: Client,
                           allow_user_to_account, account_balance) -> None:
     rv: Response = authorized_client.get("/account", )
     assert rv.status_code == 200
     balances = rv.get_json()["balances"]
     assert account_balance["account_name"] == "fake_account"
     assert len(balances) == 1
     assert balances[0]["currency"] == DiemCurrency.Coin1.value
     assert balances[0]["balance"] == 100
Exemple #19
0
def test_responder():
    """Responder decorator"""
    def foo(environ, start_response):
        return BaseResponse('Test')

    client = Client(responder(foo), BaseResponse)
    response = client.get('/')
    assert response.status_code == 200
    assert response.data == 'Test'
Exemple #20
0
 def test_get_user_self(self, app, client: Client):
     register_resp = register_user(client)
     login_resp = login_user(client)
     resp = client.get(
         url_for("user.get_user_by_id", user_id=register_resp.json["id"]),
         headers={"Authorization": f"Bearer {login_resp.json['token']}"},
     )
     assert resp.status_code == 200
     UserResponseSchema().loads(resp.data)
Exemple #21
0
class MaintenanceCheckTestCase(unittest.TestCase):
    def setUp(self):
        apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
        stub = datastore_file_stub.DatastoreFileStub("test", "/dev/null", "/dev/null")
        apiproxy_stub_map.apiproxy.RegisterStub("datastore_v3", stub)

        apiproxy_stub_map.apiproxy.RegisterStub("user", user_service_stub.UserServiceStub())

        apiproxy_stub_map.apiproxy.RegisterStub("memcache", memcache_stub.MemcacheServiceStub())

        apiproxy_stub_map.apiproxy.RegisterStub("urlfetch", urlfetch_stub.URLFetchServiceStub())

        s = LazySettings(settings_module="kay.tests.settings")
        app = get_application(settings=s)
        self.client = Client(app, BaseResponse)
        if apiproxy_stub_map.apiproxy._APIProxyStubMap__stub_map.has_key("capability_service"):
            del (apiproxy_stub_map.apiproxy._APIProxyStubMap__stub_map["capability_service"])

    def tearDown(self):
        pass

    def test_success(self):
        """Test with normal CapabilityServiceStub"""
        apiproxy_stub_map.apiproxy.RegisterStub("capability_service", capability_stub.CapabilityServiceStub())
        response = self.client.get("/")
        self.assertEqual(response.status_code, 200)

    def test_failure(self):
        """Test with DisabledCapabilityServiceStub
    """
        apiproxy_stub_map.apiproxy.RegisterStub(
            "capability_service", mocked_capability_stub.DisabledCapabilityServiceStub()
        )
        response = self.client.get("/")
        self.assertEqual(response.status_code, 302)
        self.assertEqual(response.headers["Location"], "http://localhost/maintenance_page")

        response = self.client.get("/index2")
        self.assertEqual(response.status_code, 302)
        self.assertEqual(response.headers["Location"], "http://localhost/no_decorator")
        response = self.client.get("/no_decorator")
        self.assertEqual(response.status_code, 200)
Exemple #22
0
class TestApp2(unittest.TestCase):
    def setUp(self):
        self.app = make_wsgi2('Testruns')
        self.client = Client(self.app, BaseResponse)

    def tearDown(self):
        self.client = None
        self.app = None

    def test_app2(self):
        r = self.client.get('tests/rvbapp2')
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.data, b'Hello app2!')

    def test_underscore_templates(self):
        r = self.client.get('tests/underscoretemplates')

        self.assertEqual(r.status, '200 OK')
        self.assertEqual(r.data, b'Hello World!')
        self.assertEqual(r.headers['Content-Type'], 'text/html; charset=utf-8')
Exemple #23
0
class CronOnlyDebugTestCase(GAETestBase):

  def setUp(self):
    s = LazySettings(settings_module='kay.tests.settings')
    s.DEBUG = True
    app = get_application(settings=s)
    self.client = Client(app, BaseResponse)

  def test_cron_only_failure(self):
    from kay.utils import is_dev_server
    response = self.client.get("/cron")
    if is_dev_server():
      self.assertEqual(response.status_code, 200)
    else:
      self.assertEqual(response.status_code, 403)

  def test_cron_only(self):
    response = self.client.get("/cron",
            headers=(('X-AppEngine-Cron', 'true'),))
    self.assertEqual(response.status_code, 200)
    self.assertTrue(response.data == "OK")
class test_View_index(GAETestBase):
  CLEANUP_USED_KIND = True
  USE_PRODUCTION_STUBS = True

  def setUp(self):
    init_recording()
    app = get_application()
    self.client = Client(app, BaseResponse)

  def tearDown(self):
    disable_recording()

  def test_base(self):
    response = self.client.get('/')
    self.assertEquals(response.status_code, 404)

  def test_client_get(self):
    response = self.client.get('/client')
    self.assertEquals(response.status_code, 301)

  def test_client_head(self):
    self.fail('test_View_index.test_client_head not yet written')

  def test_client_post(self):
    self.fail('test_View_index.test_client_post not yet written')

  def test_client_put(self):
    self.fail('test_View_index.test_client_put not yet written')

  def test_client_delete(self):
    self.fail('test_View_index.test_client_delete not yet written')

  def test_client_options(self):
    self.fail('test_View_index.test_client_options not yet written')

  def test_client_trace(self):
    self.fail('test_View_index.test_client_trace not yet written')

  def test_client_connect(self):
    self.fail('test_View_index.test_client_connect not yet written')
Exemple #25
0
 def wrapper(self):
     client = Client(Application(), BaseResponse)
     response = client.get(url, headers={'Accept': accept})
     eq_(response.status_code, status_code)
     if template:
         assert response.template ==template
     f(self, response, response.context, PyQuery(response.data))
     # Validate after other tests so we know everything else works.
     # Hacky piggybacking on --verbose so tests go faster.
     if '--verbose' in sys.argv:
         validator = post_multipart('validator.w3.org', '/check',
                                    {'fragment': response.data})
         assert PyQuery(validator)('#congrats').size() == 1
Exemple #26
0
class MaintenanceCheckTestCase(unittest.TestCase):

  def setUp(self):
    s = LazySettings(settings_module='kay.tests.settings')
    app = get_application(settings=s)
    self.client = Client(app, BaseResponse)
    if apiproxy_stub_map.apiproxy\
          ._APIProxyStubMap__stub_map.has_key('capability_service'):
      del(apiproxy_stub_map.apiproxy\
            ._APIProxyStubMap__stub_map['capability_service'])

  def tearDown(self):
    pass

  def test_success(self):
    """Test with normal CapabilityServiceStub"""
    apiproxy_stub_map.apiproxy.RegisterStub(
      'capability_service',
      capability_stub.CapabilityServiceStub())
    response = self.client.get('/')
    self.assertEqual(response.status_code, 200)

  def test_failure(self):
    """Test with DisabledCapabilityServiceStub
    """
    apiproxy_stub_map.apiproxy.RegisterStub(
      'capability_service',
      mocked_capability_stub.DisabledCapabilityServiceStub())
    response = self.client.get('/')
    self.assertEqual(response.status_code, 302)
    self.assertEqual(response.headers['Location'],
                     'http://localhost/_kay/maintenance_page')

    response = self.client.get('/index2')
    self.assertEqual(response.status_code, 302)
    self.assertEqual(response.headers['Location'],
                     'http://localhost/no_decorator')
    response = self.client.get('/no_decorator')
    self.assertEqual(response.status_code, 200)
Exemple #27
0
 def test_get_account_transactions_by_currency(
     self,
     authorized_client: Client,
     allow_user_to_account,
     account_transactions_mock,
 ) -> None:
     requested_currency = DiemCurrency.Coin1.value
     rv: Response = authorized_client.get(
         f"/account/transactions?currency={requested_currency}")
     assert rv.status_code == 200
     transactions = rv.get_json()
     assert len(transactions) == 1
     assert account_transactions_mock["currency"] == requested_currency
Exemple #28
0
class MaintenanceCheckTestCase(unittest.TestCase):

  def setUp(self):
    s = LazySettings(settings_module='kay.tests.settings')
    app = get_application(settings=s)
    self.client = Client(app, BaseResponse)

  def tearDown(self):
    pass

  def test_redirect(self):
    """Test with normal CapabilityServiceStub"""
    response = self.client.get('/oldpage', follow_redirects=True)
    self.assertEqual(response.status_code, 200)
    self.assertEqual(response.data, "New")
 def test_get(self):
     # http://werkzeug.pocoo.org/docs/0.11/test/#werkzeug.test.Client
     sut = Client(app, Response)
     actual = sut.get('/')
     # http://werkzeug.pocoo.org/docs/0.11/wrappers/#werkzeug.wrappers.BaseResponse.status_code
     assert actual.status_code == 200
     # http://werkzeug.pocoo.org/docs/0.11/wrappers/#werkzeug.wrappers.BaseResponse.headers
     assert actual.headers.get('Content-Type') == 'text/html; charset=UTF-8'
     # デフォルトではバイト文字列になるので、as_text=Trueで文字列化する
     # http://werkzeug.pocoo.org/docs/0.11/wrappers/#werkzeug.wrappers.BaseResponse.get_data
     # ただし、バグがあるので、utf-8以外の文字コードは扱えない(現時点でもcloseしていない)
     # http://blog.amedama.jp/entry/2016/06/11/225137
     # https://github.com/pallets/werkzeug/issues/947
     body = actual.get_data(as_text=True)
     assert 'テスト掲示板' in body
Exemple #30
0
    def command(self):
        options = self.options
        c = Client(self.wsgiapp, BaseResponse)
        if self.args:
            url = self.args[0]
        else:
            url = '/'
        resp = c.get(url)

        if options.show_headers and not options.silent:
            print(resp.status)
            print(resp.headers)

        if options.show_body and not options.silent:
            for respstr in resp.response:
                if isinstance(respstr, six.binary_type):
                    respstr = respstr.decode()
                print(respstr)
Exemple #31
0
def geth(path):
    c = Client(application, BaseResponse)
    r = c.get(path)
    h = BeautifulSoup(r.data)
    return r.status_code, r.headers, h
Exemple #32
0
def test_ie_fixes():
    """Test IE fixes."""
    @fixers.InternetExplorerFix
    @Request.application
    def application(request):
        response = Response('binary data here', mimetype='application/vnd.ms-excel')
        response.headers['Vary'] = 'Cookie'
        response.headers['Content-Disposition'] = 'attachment; filename=foo.xls'
        return response

    c = Client(application, Response)
    response = c.get('/', headers=[
        ('User-Agent', 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)')
    ])

    # IE gets no vary
    assert response.data == 'binary data here'
    assert 'vary' not in response.headers
    assert response.headers['content-disposition'] == 'attachment; filename=foo.xls'
    assert response.headers['content-type'] == 'application/vnd.ms-excel'

    # other browsers do
    c = Client(application, Response)
    response = c.get('/')
    assert response.data == 'binary data here'
    assert 'vary' in response.headers

    cc = ResponseCacheControl()
    cc.no_cache = True

    @fixers.InternetExplorerFix
    @Request.application
    def application(request):
        response = Response('binary data here', mimetype='application/vnd.ms-excel')
        response.headers['Pragma'] = ', '.join(pragma)
        response.headers['Cache-Control'] = cc.to_header()
        response.headers['Content-Disposition'] = 'attachment; filename=foo.xls'
        return response


    # IE has no pragma or cache control
    pragma = ('no-cache',)
    c = Client(application, Response)
    response = c.get('/', headers=[
        ('User-Agent', 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)')
    ])
    assert response.data == 'binary data here'
    assert 'pragma' not in response.headers
    assert 'cache-control' not in response.headers
    assert response.headers['content-disposition'] == 'attachment; filename=foo.xls'

    # IE has simplified pragma
    pragma = ('no-cache', 'x-foo')
    cc.proxy_revalidate = True
    response = c.get('/', headers=[
        ('User-Agent', 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)')
    ])
    assert response.data == 'binary data here'
    assert response.headers['pragma'] == 'x-foo'
    assert response.headers['cache-control'] == 'proxy-revalidate'
    assert response.headers['content-disposition'] == 'attachment; filename=foo.xls'

    # regular browsers get everything
    response = c.get('/')
    assert response.data == 'binary data here'
    assert response.headers['pragma'] == 'no-cache, x-foo'
    cc = parse_cache_control_header(response.headers['cache-control'],
                                    cls=ResponseCacheControl)
    assert cc.no_cache
    assert cc.proxy_revalidate
    assert response.headers['content-disposition'] == 'attachment; filename=foo.xls'
Exemple #33
0
class WebTestCase(unittest.TestCase):
    def setUp(self):
        self.test_doc_path = mkdtemp()
        self.doc = open_document(path.join(self.test_doc_path, 'test_doc.db'))
        self.doc.create_note({'desc': 'note 1'})
        self.doc.create_note({'desc': 'note 2'})
        self.app = server.CorkApp(self.doc)
        self.client = Client(self.app, BaseResponse)

    def tearDown(self):
        rmtree(self.test_doc_path)

    def failUnlessJsonResponse(self, resp, json_data):
        self.failUnlessEqual(resp.status_code, 200)
        self.failUnlessEqual(resp.headers['Content-Type'], 'application/json')
        self.failUnlessEqual(json.loads(resp.data), json_data)

    def test_notes_listing(self):
        self.failUnlessJsonResponse(self.client.get('/notes'), [0, 1, 2])

    def test_get_note(self):
        self.failUnlessJsonResponse(self.client.get('/notes/0'), {
            'props': {'desc': 'ROOT'},
            'children': [1, 2],
        })

    def test_change_note(self):
        test_props = {'desc': 'new content here', 'a': 'b'}
        resp = self.client.post('/notes/1', data={'props': json.dumps(test_props)})
        self.doc.abort() # checking if transaction was committed
        self.failUnlessEqual(dict(self.doc.notes[1]), test_props)
        self.failUnlessJsonResponse(resp, {'props': test_props, 'children': []})

    def test_create_note(self):
        resp = self.client.post('/notes', data={
            'parent_id': 1, 'props': json.dumps({'f': 'g'})})
        self.failUnlessJsonResponse(resp, 3)
        self.doc.abort() # checking if transaction was committed
        self.failUnlessEqual(len(self.doc.notes), 4)
        self.failUnlessEqual(dict(self.doc.notes[3]), {'f': 'g'})
        self.failUnlessEqual(list(self.doc.notes[1].children_ids()), [3])
        self.failUnlessEqual(list(self.doc.notes[0].children_ids()), [1, 2])

    def test_set_parent(self):
        resp = self.client.post('/notes/2/parent', data={'parent_id': 1})
        self.failUnlessEqual(resp.status_code, 200)
        self.doc.abort() # checking if transaction was committed
        self.failUnlessEqual(list(self.doc.notes[1].children_ids()), [2])
        self.failUnlessEqual(list(self.doc.notes[0].children_ids()), [1])

    def test_remove_note(self):
        self.client.post('/notes/2/parent', data={'parent_id': 1})

        self.failUnless(1 in self.doc.notes)
        self.failUnless(1 in list(self.doc.notes[0].children_ids()))
        self.failUnless(2 in self.doc.notes)
        self.failUnless(2 in list(self.doc.notes[1].children_ids()))

        resp = self.client.delete('/notes/1')
        self.failUnlessJsonResponse(resp, 'ok')
        self.failIf(1 in self.doc.notes)
        self.failIf(1 in list(self.doc.notes[0].children_ids()))
        self.failIf(2 in self.doc.notes)

    def test_custom_html(self):
        gsm = component.getGlobalSiteManager()
        def customViewAdapter(note):
            if note.id == test_note_id:
                return CustomView(note)
        gsm.registerSubscriptionAdapter(customViewAdapter,
            required=[INote], provided=INoteView)

        test_note_id = self.doc.create_note({'a': 'b'}).id
        self.failUnlessJsonResponse(self.client.get('/notes/%d' % test_note_id), {
            'props': {'a': 'b'},
            'children': [],
            'html': '<em>hello custom!</em>',
        })

        gsm.unregisterSubscriptionAdapter(customViewAdapter,
            required=[INote], provided=INoteView)

    def test_ajax(self):
        gsm = component.getGlobalSiteManager()
        def customViewAdapter(note):
            if note.id == test_note_id:
                return CustomView(note)
        gsm.registerSubscriptionAdapter(customViewAdapter,
            required=[INote], provided=INoteView)

        test_note_id = self.doc.create_note({}).id
        resp = self.client.post('/notes/3/ajax', data={'args': json.dumps({'token': 'asdf'})})
        self.failUnlessJsonResponse(resp, '-asdf-')

        gsm.unregisterSubscriptionAdapter(customViewAdapter,
            required=[INote], provided=INoteView)
Exemple #34
0
class TestUserFunctional(unittest.TestCase):

    def setUp(self):
        self.app = make_wsgi('Testruns')
        self.client = Client(self.app, BaseResponse)

    def tearDown(self):
        self.client = None
        self.app = None

    def test_attr(self):
        r = self.client.get('/usertests/setfoo')

        self.assertEqual(r.status, '200 OK')
        self.assertEqual(r.data, b'foo set')

        r = self.client.get('/usertests/getfoo')

        self.assertEqual(r.status, '200 OK')
        self.assertEqual(r.data, b'barbaz')

    def test_auth(self):
        r = self.client.get('/usertests/setauth')

        self.assertEqual(r.status, '200 OK')

        r = self.client.get('/usertests/getauth')

        self.assertEqual(r.status, '200 OK')
        self.assertEqual(r.data, b'True')

    def test_perm(self):
        r = self.client.get('/usertests/addperm')

        self.assertEqual(r.status, '200 OK')

        r = self.client.get('/usertests/getperms')

        self.assertEqual(r.status, '200 OK')
        self.assertEqual(r.data, b'TrueFalseTrue')

    def test_clear(self):
        r = self.client.get('/usertests/clear')

        self.assertEqual(r.status, '200 OK')
        self.assertEqual(r.data, b'FalseFalseNone')

    def test_message(self):
        r = self.client.get('/usertests/setmsg')

        self.assertEqual(r.status, '200 OK')

        r = self.client.get('/usertests/getmsg')

        self.assertEqual(r.status, '200 OK')
        self.assertEqual(r.data, b'test: my message')

        r = self.client.get('/usertests/nomsg')

        self.assertEqual(r.status, '200 OK')
        self.assertEqual(r.data, b'0')
def test_ie_fixes():
    """Test IE fixes."""
    @fixers.InternetExplorerFix
    @Request.application
    def application(request):
        response = Response('binary data here',
                            mimetype='application/vnd.ms-excel')
        response.headers['Vary'] = 'Cookie'
        response.headers[
            'Content-Disposition'] = 'attachment; filename=foo.xls'
        return response

    c = Client(application, Response)
    response = c.get('/',
                     headers=[
                         ('User-Agent',
                          'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)')
                     ])

    # IE gets no vary
    assert response.data == 'binary data here'
    assert 'vary' not in response.headers
    assert response.headers[
        'content-disposition'] == 'attachment; filename=foo.xls'
    assert response.headers['content-type'] == 'application/vnd.ms-excel'

    # other browsers do
    c = Client(application, Response)
    response = c.get('/')
    assert response.data == 'binary data here'
    assert 'vary' in response.headers

    cc = ResponseCacheControl()
    cc.no_cache = True

    @fixers.InternetExplorerFix
    @Request.application
    def application(request):
        response = Response('binary data here',
                            mimetype='application/vnd.ms-excel')
        response.headers['Pragma'] = ', '.join(pragma)
        response.headers['Cache-Control'] = cc.to_header()
        response.headers[
            'Content-Disposition'] = 'attachment; filename=foo.xls'
        return response

    # IE has no pragma or cache control
    pragma = ('no-cache', )
    c = Client(application, Response)
    response = c.get('/',
                     headers=[
                         ('User-Agent',
                          'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)')
                     ])
    assert response.data == 'binary data here'
    assert 'pragma' not in response.headers
    assert 'cache-control' not in response.headers
    assert response.headers[
        'content-disposition'] == 'attachment; filename=foo.xls'

    # IE has simplified pragma
    pragma = ('no-cache', 'x-foo')
    cc.proxy_revalidate = True
    response = c.get('/',
                     headers=[
                         ('User-Agent',
                          'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)')
                     ])
    assert response.data == 'binary data here'
    assert response.headers['pragma'] == 'x-foo'
    assert response.headers['cache-control'] == 'proxy-revalidate'
    assert response.headers[
        'content-disposition'] == 'attachment; filename=foo.xls'

    # regular browsers get everything
    response = c.get('/')
    assert response.data == 'binary data here'
    assert response.headers['pragma'] == 'no-cache, x-foo'
    cc = parse_cache_control_header(response.headers['cache-control'],
                                    cls=ResponseCacheControl)
    assert cc.no_cache
    assert cc.proxy_revalidate
    assert response.headers[
        'content-disposition'] == 'attachment; filename=foo.xls'
Exemple #36
0
class TestViews(unittest.TestCase):
    def setUp(self):
        self.app = make_wsgi('Testruns')
        self.client = Client(self.app, BaseResponse)

    def tearDown(self):
        self.client = None
        self.app = None

    def test_responding_view_base(self):
        r = self.client.get('tests/rvb')

        self.assertEqual(r.status, '200 OK')
        self.assertEqual(r.data, b'Hello World!')

    def test_responding_view_base_with_snippet(self):
        r = self.client.get('tests/rvbwsnip')

        self.assertEqual(r.status, '200 OK')
        self.assertEqual(r.data, b'Hello World!')

    def test_get(self):
        r = self.client.get('tests/get')

        self.assertEqual(r.status, '200 OK')
        self.assertEqual(r.data, b'Hello World!')

    def test_post(self):
        r = self.client.post('tests/post')

        self.assertEqual(r.status, '200 OK')
        self.assertEqual(r.data, b'Hello World!')

    def test_404_noroute(self):
        r = self.client.get('nothere')

        self.assertEqual(r.status, '404 NOT FOUND')
        self.assertTrue(b'Not Found' in r.data)
        self.assertTrue(
            b'If you entered the URL manually please check your spelling '
            b'and try again.' in r.data)

    def test_nomodule(self):
        try:
            self.client.get('tests/badmod')
            self.fail(
                'should have got ProgrammingError since URL exists but module does not'
            )
        except HierarchyImportError as e:
            assert 'An object for View endpoint "fatfinger:NotExistant" was not found' == str(
                e), e

    def test_noview(self):
        try:
            self.client.get('tests/noview')
            self.fail(
                'should have got ProgrammingError since URL exists but view does not'
            )
        except HierarchyImportError as e:
            assert 'An object for View endpoint "tests:NotExistant" was not found' == str(
                e), e

    def test_prep(self):
        r = self.client.get('tests/prep')

        self.assertEqual(r.status, '200 OK')
        self.assertEqual(r.data, b'Hello World!')

    def test_hideexception(self):
        settings.exception_handling = ['handle']
        r = self.client.get('tests/raiseexc')
        self.assertEqual(r.status, '500 INTERNAL SERVER ERROR')

    def test_2gets(self):
        r = self.client.get('tests/get')

        self.assertEqual(r.status, '200 OK')
        self.assertEqual(r.data, b'Hello World!')

        r = self.client.get('tests/get')
        self.assertEqual(r.status, '200 OK')
        self.assertEqual(r.data, b'Hello World!')

    def test_forward(self):
        r = self.client.get('tests/doforward')

        self.assertEqual(r.status, '200 OK')
        self.assertEqual(r.data, b'forward to me')

    def test_text(self):
        r = self.client.get('tests/text')

        self.assertEqual(r.status, '200 OK')
        self.assertEqual(r.data, b'Hello World!')
        self.assertEqual(r.headers['Content-Type'],
                         'text/plain; charset=utf-8')

    def test_textwsnip(self):
        r = self.client.get('tests/textwsnip')

        self.assertEqual(r.status, '200 OK')
        self.assertEqual(r.data, b'Hello World!')
        self.assertEqual(r.headers['Content-Type'],
                         'text/plain; charset=utf-8')

    def test_textwsnip2(self):
        r = self.client.get('tests/textwsnip2')

        self.assertEqual(r.status, '200 OK')
        self.assertEqual(r.data, b'Hello World!')
        self.assertEqual(r.headers['Content-Type'],
                         'text/plain; charset=utf-8')

    def test_html(self):
        r = self.client.get('tests/html')

        self.assertEqual(r.status, '200 OK')
        self.assertEqual(r.data, b'Hello World!')
        self.assertEqual(r.headers['Content-Type'], 'text/html; charset=utf-8')

    def test_redirect(self):
        r = self.client.get('tests/redirect')

        self.assertEqual(r.status_code, 302)
        self.assertEqual(r.headers['Location'],
                         'http://localhost/some/other/page')

    def test_permredirect(self):
        r = self.client.get('tests/permredirect')

        self.assertEqual(r.status_code, 301)
        self.assertEqual(r.headers['Location'],
                         'http://localhost/some/other/page')

    def test_custredirect(self):
        r = self.client.get('tests/custredirect')

        self.assertEqual(r.status_code, 303)
        self.assertEqual(r.headers['Location'],
                         'http://localhost/some/other/page')

    def test_heraise(self):
        r = self.client.get('tests/heraise')

        self.assertEqual(r.status_code, 503)
        assert b'server is temporarily unable' in r.data

    def test_errordoc(self):
        settings.error_docs[503] = 'tests:Rvb'
        r = self.client.get('tests/heraise')

        self.assertEqual(r.status_code, 503)
        self.assertEqual(r.status, '503 SERVICE UNAVAILABLE')
        self.assertEqual(r.data, b'Hello World!')

    def test_errordocexc(self):
        settings.error_docs[503] = 'tests:RaiseExc'
        try:
            r = self.client.get('tests/heraise')
        except ValueError as e:
            self.assertTrue('exception for testing' in str(e))
        else:
            self.fail(
                'should have gotten an exception b/c our error handler raised one'
            )

        # now turn exception handling on and we should see a generic 500
        # response since the document handler raised an exception
        settings.exception_handling = ['handle']
        r = self.client.get('tests/heraise')

        self.assertEqual(r.status_code, 500)
        assert b'Internal Server Error' in r.data

    def test_forwardloop(self):
        try:
            self.client.get('tests/forwardloop')
        except ProgrammingError as e:
            self.assertTrue('forward loop detected:' in str(e))
        else:
            self.fail('excpected exception for a forward loop')

    def test_urlargs(self):
        r = self.client.get('tests/urlargs')

        self.assertEqual(r.status, '200 OK')
        self.assertEqual(r.data, b'Hello World!')

        r = self.client.get('tests/urlargs/fred')

        self.assertEqual(r.status, '200 OK')
        self.assertEqual(r.data, b'Hello fred!')

        r = self.client.get('tests/urlargs/10')

        self.assertEqual(r.status, '200 OK')
        self.assertEqual(r.data, b'Give me a name!')

    def test_getargs(self):

        r = self.client.get('tests/getargs')
        self.assertEqual(r.status, '200 OK')
        self.assertEqual(r.data, b'Hello World!')

        r = self.client.get('tests/getargs?towho=fred&greeting=Hi&extra=bar')
        self.assertEqual(r.status, '200 OK')
        self.assertEqual(r.data, b'Hello fred!')

    def test_getargs2(self):

        r = self.client.get('tests/getargs2')
        self.assertEqual(r.status, '200 OK')
        self.assertEqual(r.data, b'Hello World!')

        r = self.client.get('tests/getargs2?towho=fred')
        self.assertEqual(r.status, '200 OK')
        self.assertEqual(r.data, b'Hello fred!')

        r = self.client.get('tests/getargs2?num=10')
        self.assertEqual(r.status, '200 OK')
        self.assertEqual(r.data, b'Hello World, 10!')

        r = self.client.get('tests/getargs2?num=ten')
        self.assertEqual(r.status, '200 OK')
        self.assertEqual(r.data, b'Hello World!')

    def test_getargs3(self):
        r = self.client.get('tests/getargs3?num=ten&num2=ten')
        self.assertEqual(r.status_code, 400)
        # we are no longer going to manipulate the response object to include
        # user messages
        self.assertTrue(b'integer' not in r.data)

        # If you want user messages included in an error response
        # you need to use an error document that will include them, like so:
        settings.error_docs[400] = 'tests:UserMessages'
        r = self.client.get('tests/getargs3?num=ten&num2=ten')
        self.assertEqual(r.status_code, 400)
        assert b'(error) num2: num: must be an integer' in r.data, r.data
        assert b'(error) num: Please enter an integer value' in r.data, r.data

    def test_reqgetargs(self):
        settings.error_docs[400] = 'tests:UserMessages'
        r = self.client.get('/tests/reqgetargs?num=10&num2=10')
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.data, b'Hello World, 10 10 10!')

        r = self.client.get('/tests/reqgetargs?num2=ten')
        self.assertEqual(r.status_code, 400)
        self.assertTrue(b'(error) num: Please enter a value' in r.data, r.data)
        self.assertTrue(
            b'(error) num2: Please enter an integer value' in r.data)

        r = self.client.get('tests/reqgetargs?num1&num=2')
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.data, b'Hello World, 2 10 10!')

    def test_listgetargs(self):

        r = self.client.get('tests/listgetargs?nums=1&nums=2')
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.data, b'[1, 2]')

        r = self.client.get('tests/listgetargs?nums=ten&nums=2')
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.data, b'[2]')

    def test_customvalidator(self):

        r = self.client.get('tests/customvalidator?num=asek')
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.data, b'10')

        r = self.client.get('tests/customvalidator')
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.data, b'10')

        r = self.client.get('tests/customvalidator?num=5')
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.data, b'5')

    def test_badvalidator(self):
        try:
            self.client.get('tests/badvalidator')
        except TypeError as e:
            self.assertEqual(
                'processor must be a Formencode validator or a callable',
                str(e))
        else:
            self.fail('excpected exception for bad validator')

    def test_static(self):
        r = self.client.get('/static/app/helloworld.html')
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.get_data(), b'Hello World!')

        r = self.client.get('/static/app/helloworld2.html')
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.get_data().strip(), b'Hellow blazewebtestapp2!')

    def test_app2(self):
        # app2's test module won't have its settings imported
        # b/c app1's settings module is blocking it.  Therefore, the
        # route doesn't get added and we get a 404
        r = self.client.get('tests/rvbapp2')
        self.assertEqual(r.status_code, 404)

    def test_appfallback(self):
        r = self.client.get('tests/appfallback')
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.data, b'Hello app2!')

    def test_htmltemplatefilearg(self):
        r = self.client.get('tests/htmltemplatefilearg')
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.data, b'Hello File Arg!')

    def test_htmltemplateinheritance(self):
        """ test inheritance at the module level from a supporting app """
        r = self.client.get('tests/templateinheritance')
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.data, b'Hello Template Inheritance!')

    def test_parenttemplate(self):
        """ test extending a template from the parent application """
        r = self.client.get('tests/parenttemplate')
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.data, b'Hello Parent Template!')

    def test_parenttemplateinheritance(self):
        """ test extending a template from a supporting app"""
        r = self.client.get('tests/parenttemplateinheritance')
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.data, b'Hello App2 Parent Template!')

    def test_modlevelpriority(self):
        """ make sure that when inheriting that a module level template in a
            supporting app takes precidence over a template level app in the
            main module
        """
        r = self.client.get('tests/modlevelpriority')
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.data, b'Hello mod level priority!')

    def test_disabled_module(self):
        """ a disabled module should not be processed and therefore we should
        get a 404"""
        r = self.client.get('/disabled/notthere')

        self.assertEqual(r.status, '404 NOT FOUND')
        self.assertTrue(b'Not Found' in r.data)
        self.assertTrue(
            b'If you entered the URL manually please check your spelling and '
            b'try again.' in r.data)

    def test_render_endpoint(self):
        # app level endpoint
        r = self.client.get('/tests/tchooser/endpoint')
        assert b'app level' in r.data, r.data

        # render content
        r = self.client.get('/tests/tchooser/content')
        assert b'Hello World!' in r.data, r.data

    def test_render_template_directly(self):
        # app level endpoint
        r = self.client.get('/tests/text.txt/&fred')
        assert r.headers[
            'Content-Type'] == 'text/plain; charset=utf-8', r.headers
        assert b'Hello &amp;fred!' in r.data, r.data

    def test_jsonify_exception(self):
        # we have exception handling turned off during testing, so we should
        # get the exception passed all the way up
        try:
            r = self.client.get('/jsonify-exception')
            assert False
        except NameError as e:
            if 'foo' not in str(e):
                raise

        try:
            settings.exception_handling = ['handle']
            r = self.client.get('/jsonify-exception')
            assert r.status_code == 500, r.status_code
            data = jsonmod.loads(r.data.decode())
            assert data['error'] == 1, data
            assert data['data'] is None, data
        finally:
            settings.exception_handling = None
Exemple #37
0
class SolaceTestCase(unittest.TestCase):
    """Subclass of the standard test case that creates and drops the database."""
    def setUp(self):
        from solace import database, settings, templating
        from solace.application import application
        self.__old_settings = dict(settings.__dict__)
        settings.revert_to_default()
        settings.DATABASE_URI = 'sqlite:///' + TEST_DATABASE
        settings.TRACK_QUERIES = True
        settings.DATABASE_ECHO = False
        settings.MAIL_LOG_FILE = tempfile.NamedTemporaryFile()
        database.refresh_engine()
        database.init()
        self.client = Client(application, TestResponse)
        self.is_logged_in = False

    def get_session(self):
        from solace import settings
        for cookie in self.client.cookie_jar:
            if cookie.name == settings.COOKIE_NAME:
                value = unquote_header_value(cookie.value)
                return SecureCookie.unserialize(value, settings.SECRET_KEY)

    def get_exchange_token(self):
        return loads(self.client.get('/_request_exchange_token').data)['token']

    def get_mails(self):
        from solace import settings
        pos = settings.MAIL_LOG_FILE.tell()
        settings.MAIL_LOG_FILE.seek(0)
        mails = settings.MAIL_LOG_FILE.read().split('\n%s\n\n' % ('-' * 79))
        settings.MAIL_LOG_FILE.seek(pos)
        return [message_from_string(x) for x in mails if x]

    def normalize_local_path(self, path):
        if path in ('', '.'):
            path = path
        elif path.startswith(BASE_URL):
            path = path[len(BASE_URL) - 1:]
        return path

    def submit_form(self, path, data, follow_redirects=False):
        response = self.client.get(path)
        try:
            form = html_xpath(response.html, '//html:form')[0]
        except IndexError:
            raise RuntimeError('no form on page')
        csrf_token = html_xpath(form, '//html:input[@name="_csrf_token"]')[0]
        data['_csrf_token'] = csrf_token.attrib['value']
        action = self.normalize_local_path(form.attrib['action'])
        return self.client.post(action,
                                method=form.attrib['method'].upper(),
                                data=data,
                                follow_redirects=follow_redirects)

    def login(self, username, password):
        try:
            return self.submit_form('/login', {
                'username': username,
                'password': password
            })
        finally:
            self.is_logged_in = True

    def logout(self):
        self.is_logged_in = False
        return self.client.get('/logout?_xt=%s' % self.get_exchange_token())

    def tearDown(self):
        from solace import database, settings
        database.refresh_engine()
        try:
            os.remove(TEST_DATABASE)
        except OSError:
            pass
        settings.__dict__.clear()
        settings.__dict__.update(self.__old_settings)
        del self.is_logged_in
class FbTest(GAETestBase):

    def setUp(self):
        init_recording()
        app = get_application()
        self.client = Client(app, BaseResponse)

    def test_facebook_cookie_parsing(self):
        from fb.utils import get_facebook_uid_from_cookie
        cookies = {COOKIE_NAME: COOKIE_VALUE, 
                  '__qca': u'P0-1132520767-1274949618785'}
        fb_cookie = cookies[COOKIE_NAME] 
        self.assertEquals(get_facebook_uid_from_cookie(fb_cookie), '676578004')

    def test_facebook_profile_creation(self, fbuid = '123'):
        from werkzeug.utils import import_string
        dudes_profile = _user_creation(self)
        dudes_facebook = FacebookProfile(fb_uid = fbuid, userprofile = dudes_profile)
        dudes_facebook.put()
        auth_model_class = import_string(settings.AUTH_USER_MODEL)
        user = auth_model_class.get_user_by_fbuid(fbuid)
        self.assertEquals(dudes_facebook.userprofile.user.key(), user.key())

    def test_facebook_login_url(self):
        self.test_facebook_profile_creation(fbuid = FACEBOOK_UID)
        response = self.client.get('/facebook/login/')
        self.assertEquals(response.status_code, 404)
        resp = self.client.get('/facebook/set_test_session/')
        response = self.client.get('/facebook/login/')
        self.assertEquals(response.status_code, 302)

    def test_facebook_first_visit(self):
        profiles = UserProfile.all().fetch(100)
        self.assertEquals(len(profiles), 0)
        fb_profiles = FacebookProfile.all().fetch(100)
        self.assertEquals(len(fb_profiles), 0)
        users = DatastoreUser.all().fetch(100)
        self.assertEquals(len(users), 0)
        _facebook_login(self)

        fb_profiles = FacebookProfile.all().fetch(100)
        self.assertEquals(len(fb_profiles), 1)
        profiles = UserProfile.all().fetch(100)
        self.assertEquals(len(profiles), 1)
        users = DatastoreUser.all().fetch(100)
        self.assertEquals(len(users), 1)

    def test_facebook_return_visit(self):

        _create_fb_user(FACEBOOK_UID)

        profiles = UserProfile.all().fetch(100)
        self.assertEquals(len(profiles), 1)
        fb_profiles = FacebookProfile.all().fetch(100)
        self.assertEquals(len(fb_profiles), 1)
        users = DatastoreUser.all().fetch(100)
        self.assertEquals(len(users), 1)
        _facebook_login(self)

        fb_profiles = FacebookProfile.all().fetch(100)
        self.assertEquals(len(fb_profiles), 1)
        profiles = UserProfile.all().fetch(100)
        self.assertEquals(len(profiles), 1)
        users = DatastoreUser.all().fetch(100)
        self.assertEquals(len(users), 1)

    #def test_graph_authorization(self):
        #resp = self.client.get('/facebook/test_graph_api/')
        #self.assertEquals(resp.status_code, 302)

    def test_update_facebook_user(self):
        _create_fb_user(FACEBOOK_UID)
        facebook_data = dict(first_name = 'Mos', last_name = "Def")
        user = DatastoreUser.all().fetch(100)[0]
        self.assertTrue(user.user_name.find(FACEBOOK_UID) > -1)
        user = update_facebook_user(user = user, 
                             facebook_user_data = facebook_data)
        self.assertTrue(user.first_name == "Mos")

    def test_fb_login_decorator(self):
        _create_fb_user(FACEBOOK_UID)
        resp = self.client.get('/projects/new/')
        # fb user is not logged in and attempts to access this url. redirection expected, hence 302.
        self.assertEquals(resp.status_code, 302)
        # fb user is logged in and now should be able to access the url.
        _facebook_login(self)
        resp = self.client.get('/projects/new/')
        self.assertEquals(resp.status_code, 200)

    def test_fb_login_decorator_again(self):
        # fb user is not logged in and goes to /facebook/fb_login page.
        pass
Exemple #39
0
class SolaceTestCase(unittest.TestCase):
    """Subclass of the standard test case that creates and drops the database."""

    def setUp(self):
        from solace import database, settings, templating
        from solace.application import application
        self.__old_settings = dict(settings.__dict__)
        settings.revert_to_default()
        settings.DATABASE_URI = 'sqlite:///' + TEST_DATABASE
        settings.TRACK_QUERIES = True
        settings.DATABASE_ECHO = False
        settings.MAIL_LOG_FILE = tempfile.NamedTemporaryFile()
        database.refresh_engine()
        database.init()
        self.client = Client(application, TestResponse)
        self.is_logged_in = False

    def get_session(self):
        from solace import settings
        for cookie in self.client.cookie_jar:
            if cookie.name == settings.COOKIE_NAME:
                value = unquote_header_value(cookie.value)
                return SecureCookie.unserialize(value, settings.SECRET_KEY)

    def get_exchange_token(self):
        return loads(self.client.get('/_request_exchange_token').data)['token']

    def get_mails(self):
        from solace import settings
        pos = settings.MAIL_LOG_FILE.tell()
        settings.MAIL_LOG_FILE.seek(0)
        mails = settings.MAIL_LOG_FILE.read().split('\n%s\n\n' % ('-' * 79))
        settings.MAIL_LOG_FILE.seek(pos)
        return [message_from_string(x) for x in mails if x]

    def normalize_local_path(self, path):
        if path in ('', '.'):
            path = path
        elif path.startswith(BASE_URL):
            path = path[len(BASE_URL) - 1:]
        return path

    def submit_form(self, path, data, follow_redirects=False):
        response = self.client.get(path)
        try:
            tree = html.fromstring(response.data)
            form = tree.xpath('//form')[0]
            #was: form = response.html.xpath('//form')[0]
        except IndexError:
            raise RuntimeError('no form on page')
        csrf_token = form.xpath('//input[@name="_csrf_token"]')[0]
        data['_csrf_token'] = csrf_token.attrib['value']
        action = self.normalize_local_path(form.attrib['action'])
        return self.client.post(action, method=form.attrib['method'].upper(),
                                data=data, follow_redirects=follow_redirects)

    def login(self, username, password):
        try:
            return self.submit_form('/login', {
                'username':     username,
                'password':     password
            })
        finally:
            self.is_logged_in = True

    def logout(self):
        self.is_logged_in = False
        return self.client.get('/logout?_xt=%s' % self.get_exchange_token())

    def tearDown(self):
        from solace import database, settings
        database.refresh_engine()
        try:
            os.remove(TEST_DATABASE)
        except OSError:
            pass
        settings.__dict__.clear()
        settings.__dict__.update(self.__old_settings)
        del self.is_logged_in
Exemple #40
0
with open('./log.txt', 'w+') as fd:
    
    mem = process.memory_info().rss

    app = Flask(__name__)
    with time_it('create 60000 routes with flask', fd=fd):
        for i in range(60000):
            def route():
                return str(i)
            route.__name__ = copy.copy(str(i))

            app.route('/<name>/' + str(i))(route)

    c = Client(app.wsgi_app, Response)
    with time_it('call route from flask', fd=fd):
        res = c.get('/hakim/30000')
        print(res.data)
        # assert res.data == b'900 route'
    
    new_mem = process.memory_info().rss 
    print(new_mem - mem)
    mem = new_mem
    


    router = Router()
    with time_it('create 60000 routes wsgitools router', fd=fd):
        for i in range(60000):
            route_desc = copy.copy(str(i) + ' route')
            @router.get(rule='/<name>/' + str(i))
            def route(req, res):