Beispiel #1
0
def test_environ_builder_headers_content_type():
    b = EnvironBuilder(headers={"Content-Type": "text/plain"})
    env = b.get_environ()
    assert env["CONTENT_TYPE"] == "text/plain"
    b = EnvironBuilder(content_type="text/html", headers={"Content-Type": "text/plain"})
    env = b.get_environ()
    assert env["CONTENT_TYPE"] == "text/html"
def test_apihandler_ws_error(conn):
    values = {'format': 'json'}
    builder = EnvironBuilder(method='POST', data=values)
    handler = WebServiceErrorHandler(connect=provider(conn))
    resp = handler.handle(Request(builder.get_environ()))
    assert_equals('application/json; charset=UTF-8', resp.content_type)
    expected = {
        "status": "error",
        "error": {
            "message": "invalid API key",
            "code": 4,
        }
    }
    assert_json_equals(expected, resp.data)
    assert_equals('400 BAD REQUEST', resp.status)
    handler = InternalErrorHandler(connect=provider(conn))
    resp = handler.handle(Request(builder.get_environ()))
    assert_equals('application/json; charset=UTF-8', resp.content_type)
    expected = {
        "status": "error",
        "error": {
            "message": "internal error",
            "code": 5,
        }
    }
    assert_json_equals(expected, resp.data)
    assert_equals('500 INTERNAL SERVER ERROR', resp.status)
Beispiel #3
0
 def test_environ_builder_headers_content_type(self):
     b = EnvironBuilder(headers={'Content-Type': 'text/plain'})
     env = b.get_environ()
     self.assert_equal(env['CONTENT_TYPE'], 'text/plain')
     b = EnvironBuilder(content_type='text/html',
                        headers={'Content-Type': 'text/plain'})
     env = b.get_environ()
     self.assert_equal(env['CONTENT_TYPE'], 'text/html')
Beispiel #4
0
def test_environ_builder_headers_content_type():
    b = EnvironBuilder(headers={'Content-Type': 'text/plain'})
    env = b.get_environ()
    assert env['CONTENT_TYPE'] == 'text/plain'
    b = EnvironBuilder(content_type='text/html',
                       headers={'Content-Type': 'text/plain'})
    env = b.get_environ()
    assert env['CONTENT_TYPE'] == 'text/html'
Beispiel #5
0
def test_environ_builder_headers():
    b = EnvironBuilder(environ_base={"HTTP_USER_AGENT": "Foo/0.1"}, environ_overrides={"wsgi.version": (1, 1)})
    b.headers["X-Beat-My-Horse"] = "very well sir"
    env = b.get_environ()
    strict_eq(env["HTTP_USER_AGENT"], "Foo/0.1")
    strict_eq(env["HTTP_X_BEAT_MY_HORSE"], "very well sir")
    strict_eq(env["wsgi.version"], (1, 1))

    b.headers["User-Agent"] = "Bar/1.0"
    env = b.get_environ()
    strict_eq(env["HTTP_USER_AGENT"], "Bar/1.0")
Beispiel #6
0
    def test_environ_builder_headers(self):
        b = EnvironBuilder(environ_base={'HTTP_USER_AGENT': 'Foo/0.1'},
                           environ_overrides={'wsgi.version': (1, 1)})
        b.headers['X-Beat-My-Horse'] = 'very well sir'
        env = b.get_environ()
        self.assert_strict_equal(env['HTTP_USER_AGENT'], 'Foo/0.1')
        self.assert_strict_equal(env['HTTP_X_BEAT_MY_HORSE'], 'very well sir')
        self.assert_strict_equal(env['wsgi.version'], (1, 1))

        b.headers['User-Agent'] = 'Bar/1.0'
        env = b.get_environ()
        self.assert_strict_equal(env['HTTP_USER_AGENT'], 'Bar/1.0')
Beispiel #7
0
    def test_environ_builder_headers(self):
        b = EnvironBuilder(environ_base={'HTTP_USER_AGENT': 'Foo/0.1'},
                           environ_overrides={'wsgi.version': (1, 1)})
        b.headers['X-Suck-My-Dick'] = 'very well sir'
        env = b.get_environ()
        assert env['HTTP_USER_AGENT'] == 'Foo/0.1'
        assert env['HTTP_X_SUCK_MY_DICK'] == 'very well sir'
        assert env['wsgi.version'] == (1, 1)

        b.headers['User-Agent'] = 'Bar/1.0'
        env = b.get_environ()
        assert env['HTTP_USER_AGENT'] == 'Bar/1.0'
Beispiel #8
0
    def test_same_submission(self, mock_validate_email):
        """
        Tests that the same form is not sent twice.
        """
        builder = EnvironBuilder(method='POST',
                                 data={'name': 'Valid Guy',
                                       'email': '*****@*****.**',
                                       'last_name': '',
                                       'token': conf.TOKEN,
                                       'redirect': 'http://www.example.com'})

        env = builder.get_environ()

        # Mock sendmail function so it doesn't send an actual email
        smtplib.SMTP.sendmail = Mock('smtplib.SMTP.sendmail')
        mock_validate_email.return_value = True

        # Create apps
        app = handler.create_app()

        # Will cause a duplicate with the last call because
        # first app.name = 'Valid Guy' = last app.name
        req = Request(env)
        app.on_form_page(req)
        self.assertEquals(app.error, None)

        # Update name so not a duplicate
        builder.form['name'] = 'Another Guy'
        env = builder.get_environ()
        req = Request(env)
        app.on_form_page(req)
        self.assertEquals(app.error, None)

        # Update name so not a duplicate
        builder.form['name'] = 'A Third Guy'
        env = builder.get_environ()
        req = Request(env)
        app.on_form_page(req)
        self.assertEquals(app.error, None)

        # Duplicate with first app because
        # first app.name = 'Valid Guy' = this app.name
        builder.form['name'] = 'Valid Guy'
        env = builder.get_environ()
        req = Request(env)
        app.on_form_page(req)

        self.assertEquals(app.error, 'Duplicate Request')
    def test_loading_file(self):
        """Test that it loads image from disk."""
        test_string = 'hello'
        self.hass.wsgi = mock.MagicMock()

        with mock.patch('os.path.isfile', mock.Mock(return_value=True)), \
                mock.patch('os.access', mock.Mock(return_value=True)):
            assert setup_component(self.hass, 'camera', {
                'camera': {
                    'name': 'config_test',
                    'platform': 'local_file',
                    'file_path': 'mock.file',
                }})

        image_view = self.hass.wsgi.mock_calls[0][1][0]

        m_open = mock.mock_open(read_data=test_string)
        with mock.patch(
                'homeassistant.components.camera.local_file.open',
                m_open, create=True
        ):
            builder = EnvironBuilder(method='GET')
            Request = request_class()  # pylint: disable=invalid-name
            request = Request(builder.get_environ())
            request.authenticated = True
            resp = image_view.get(request, 'camera.config_test')

        assert resp.status_code == 200, resp.response
        assert resp.response[0].decode('utf-8') == test_string
Beispiel #10
0
    def test_send_email_default(self, mock_validate_email):
        """
        Tests that the form is sent to the correct default address when
        the 'send_to' field is set to an empty string.

        Returns true if the form has been sent to [email protected]
        Errors out if unsuccessful
        """
        builder = EnvironBuilder(method='POST',
                                 data={'name': 'Valid Guy',
                                       'email': '*****@*****.**',
                                       'send_to': '',
                                       'last_name': '',
                                       'token': conf.TOKEN,
                                       'redirect': 'http://www.example.com'})
        env = builder.get_environ()
        req = Request(env)

        # Construct message for assertion
        msg = handler.create_msg(req)
        msg_send = MIMEText(str(msg))
        msg_subj = handler.set_mail_subject(msg)
        msg_send['Subject'] = msg_subj
        msg_send['To'] = conf.EMAIL['default']

        # Mock sendmail function
        smtplib.SMTP.sendmail = Mock('smtplib.SMTP.sendmail')

        # Call send_email and assert sendmail was correctly called
        handler.send_email(msg, msg_subj, send_to_email='default')
        smtplib.SMTP.sendmail.assert_called_with(conf.FROM,
                                                 conf.EMAIL['default'],
                                                 msg_send.as_string())
    def test_send_reverse_xhr_request(self, mock):
        content = 'xhr content'
        builder = EnvironBuilder(headers=self.headers,
                                 path='/fake_app_id/xhr/api/v1/collector',
                                 method='POST')

        env = builder.get_environ()
        request = Request(env)
        context = PxContext(request, self.config)

        headers = {
            'host': self.config.collector_host,
            px_constants.FIRST_PARTY_HEADER: '1',
            px_constants.ENFORCER_TRUE_IP_HEADER: context.ip,
            px_constants.FIRST_PARTY_FORWARDED_FOR: '127.0.0.1'
        }
        mock.post(
            url=
            'https://collector-pxfake_app_id.perimeterx.net/api/v1/collector',
            text=content,
            request_headers=headers,
            status_code=200,
            reason='OK')
        px_proxy = PxProxy(self.config)
        status, headers, body = px_proxy.send_reverse_xhr_request(
            config=self.config, ctx=context, body=content)
        self.assertEqual(content, body)
    def test_03_no_detail_on_success(self):
        builder = EnvironBuilder(method='POST',
                                 data={'serial': "HOTP123435"},
                                 headers={})
        env = builder.get_environ()
        # Set the remote address so that we can filter for it
        env["REMOTE_ADDR"] = "10.0.0.1"
        req = Request(env)
        # The response contains the token type SPASS
        res = {"jsonrpc": "2.0",
               "result": {"status": True,
                          "value": True},
               "version": "privacyIDEA test",
               "id": 1,
               "detail": {"message": "matching 1 tokens",
                          "serial": "HOTP123456",
                          "type": "hotp"}}
        resp = Response(json.dumps(res))

        # Set a policy, that does not allow the detail on success
        set_policy(name="pol2",
                   scope=SCOPE.AUTHZ,
                   action="no_detail_on_success", client="10.0.0.0/8")
        g.policy_object = PolicyClass()

        new_response = no_detail_on_success(req, resp)
        jresult = json.loads(new_response.data)
        self.assertTrue("detail" not in jresult, jresult)
        delete_policy("pol2")
    def test_10_check_external(self):
        g.logged_in_user = {"username": "******",
                            "role": "user"}
        builder = EnvironBuilder(method='POST',
                                 data={'serial': "OATH123456"},
                                 headers={})
        env = builder.get_environ()
        req = Request(env)
        g.policy_object = PolicyClass()
        req.all_data = {
                        "user": "******",
                        "realm": "home"}

        # Check success on no definition
        r = check_external(req)
        self.assertTrue(r)

        # Check success with external function
        current_app.config["PI_INIT_CHECK_HOOK"] = \
            "privacyidea.api.lib.prepolicy.mock_success"
        r = check_external(req)
        self.assertTrue(r)

        # Check exception with external function
        current_app.config["PI_INIT_CHECK_HOOK"] = \
            "privacyidea.api.lib.prepolicy.mock_fail"
        self.assertRaises(Exception, check_external, req)
    def test_03_check_token_upload(self):
        g.logged_in_user = {"username": "******",
                            "role": "admin"}
        builder = EnvironBuilder(method='POST',
                                 data={'serial': "OATH123456"},
                                 headers={})
        env = builder.get_environ()
        # Set the remote address so that we can filter for it
        env["REMOTE_ADDR"] = "10.0.0.1"
        req = Request(env)
        req.all_data = {"filename": "token.xml"}

        # Set a policy, that does allow the action
        set_policy(name="pol1",
                   scope=SCOPE.ADMIN,
                   action="enrollTOTP, enrollHOTP, %s" % ACTION.IMPORT,
                   client="10.0.0.0/8")
        g.policy_object = PolicyClass()

        # Try to import tokens
        r = check_token_upload(req)
        self.assertTrue(r)

        # The admin can not upload from another IP address
        # An exception is raised
        env["REMOTE_ADDR"] = "192.168.0.1"
        req = Request(env)
        req.all_data = {"filename": "token.xml"}
        self.assertRaises(PolicyError,
                          check_token_upload, req)
        # finally delete policy
        delete_policy("pol1")
Beispiel #15
0
    def test_08_check_conditions_serial(self):
        uhandler = UserNotificationEventHandler()
        # check a serial with regexp
        builder = EnvironBuilder(method='POST',
                                 data={'user': "******"},
                                 headers={})

        env = builder.get_environ()
        req = Request(env)
        req.all_data = {"user": "******", "serial": "OATH123456"}
        req.User = User("cornelius", "realm1")
        resp = Response()
        resp.data = """{"result": {"value": true}}"""
        r = uhandler.check_condition({
            "g": {},
            "handler_def": {
                "conditions": {
                    "serial": "^OATH.*"
                }
            },
            "request": req,
            "response": resp
        })
        # Serial matches the regexp
        self.assertEqual(r, True)
Beispiel #16
0
    def test_06_check_conditions_realm(self):
        uhandler = UserNotificationEventHandler()
        # check a locked token with maxfail = failcount
        builder = EnvironBuilder(method='POST',
                                 data={'user': "******"},
                                 headers={})

        env = builder.get_environ()
        req = Request(env)
        req.all_data = {"user": "******"}
        req.User = User("cornelius", "realm1")
        resp = Response()
        resp.data = """{"result": {"value": false}}"""
        r = uhandler.check_condition({
            "g": {},
            "handler_def": {
                "conditions": {
                    "realm": "realm2"
                }
            },
            "request": req,
            "response": resp
        })
        # wrong realm
        self.assertEqual(r, False)
Beispiel #17
0
    def test_environ_builder_paths(self):
        b = EnvironBuilder(path='/foo', base_url='http://example.com/')
        assert b.base_url == 'http://example.com/'
        assert b.path == '/foo'
        assert b.script_root == ''
        assert b.host == 'example.com'

        b = EnvironBuilder(path='/foo', base_url='http://example.com/bar')
        assert b.base_url == 'http://example.com/bar/'
        assert b.path == '/foo'
        assert b.script_root == '/bar'
        assert b.host == 'example.com'

        b.host = 'localhost'
        assert b.base_url == 'http://localhost/bar/'
        b.base_url = 'http://localhost:8080/'
        assert b.host == 'localhost:8080'
        assert b.server_name == 'localhost'
        assert b.server_port == 8080

        b.host = 'foo.invalid'
        b.url_scheme = 'https'
        b.script_root = '/test'
        env = b.get_environ()
        assert env['SERVER_NAME'] == 'foo.invalid'
        assert env['SERVER_PORT'] == '443'
        assert env['SCRIPT_NAME'] == '/test'
        assert env['PATH_INFO'] == '/foo'
        assert env['HTTP_HOST'] == 'foo.invalid'
        assert env['wsgi.url_scheme'] == 'https'
        assert b.base_url == 'https://foo.invalid/test/'
def test_request_header_authorization(header, secrets, expected):
    builder = EnvironBuilder()
    builder.headers.extend(header)
    request = NotifyRequest(builder.get_environ())

    res = _check_proxy_header_secret(request, secrets, list(header.keys())[0])
    assert res == expected
Beispiel #19
0
def test_environ_builder_paths():
    b = EnvironBuilder(path="/foo", base_url="http://example.com/")
    assert b.base_url == "http://example.com/"
    assert b.path == "/foo"
    assert b.script_root == ""
    assert b.host == "example.com"

    b = EnvironBuilder(path="/foo", base_url="http://example.com/bar")
    assert b.base_url == "http://example.com/bar/"
    assert b.path == "/foo"
    assert b.script_root == "/bar"
    assert b.host == "example.com"

    b.host = "localhost"
    assert b.base_url == "http://localhost/bar/"
    b.base_url = "http://localhost:8080/"
    assert b.host == "localhost:8080"
    assert b.server_name == "localhost"
    assert b.server_port == 8080

    b.host = "foo.invalid"
    b.url_scheme = "https"
    b.script_root = "/test"
    env = b.get_environ()
    assert env["SERVER_NAME"] == "foo.invalid"
    assert env["SERVER_PORT"] == "443"
    assert env["SCRIPT_NAME"] == "/test"
    assert env["PATH_INFO"] == "/foo"
    assert env["HTTP_HOST"] == "foo.invalid"
    assert env["wsgi.url_scheme"] == "https"
    assert b.base_url == "https://foo.invalid/test/"
Beispiel #20
0
def test_envrion_builder_multiple_headers():
    h = Headers()
    h.add("FOO", "bar")
    h.add("FOO", "baz")
    b = EnvironBuilder(headers=h)
    env = b.get_environ()
    assert env["HTTP_FOO"] == "bar, baz"
Beispiel #21
0
def test_environ_builder_paths():
    b = EnvironBuilder(path="/foo", base_url="http://example.com/")
    strict_eq(b.base_url, "http://example.com/")
    strict_eq(b.path, "/foo")
    strict_eq(b.script_root, "")
    strict_eq(b.host, "example.com")

    b = EnvironBuilder(path="/foo", base_url="http://example.com/bar")
    strict_eq(b.base_url, "http://example.com/bar/")
    strict_eq(b.path, "/foo")
    strict_eq(b.script_root, "/bar")
    strict_eq(b.host, "example.com")

    b.host = "localhost"
    strict_eq(b.base_url, "http://localhost/bar/")
    b.base_url = "http://localhost:8080/"
    strict_eq(b.host, "localhost:8080")
    strict_eq(b.server_name, "localhost")
    strict_eq(b.server_port, 8080)

    b.host = "foo.invalid"
    b.url_scheme = "https"
    b.script_root = "/test"
    env = b.get_environ()
    strict_eq(env["SERVER_NAME"], "foo.invalid")
    strict_eq(env["SERVER_PORT"], "443")
    strict_eq(env["SCRIPT_NAME"], "/test")
    strict_eq(env["PATH_INFO"], "/foo")
    strict_eq(env["HTTP_HOST"], "foo.invalid")
    strict_eq(env["wsgi.url_scheme"], "https")
    strict_eq(b.base_url, "https://foo.invalid/test/")
def test_submit_handler_with_meta(conn):
    values = {'format': 'json', 'client': 'app1key', 'user': '******',
        'duration': str(TEST_1_LENGTH), 'fingerprint': TEST_1_FP, 'bitrate': 192,
        'mbid': 'b9c05616-1874-4d5d-b30e-6b959c922d28', 'fileformat': 'FLAC',
        'track': 'Voodoo People',
        'artist': 'The Prodigy',
        'album': 'Music For The Jitled People',
        'albumartist': 'Prodigy',
        'trackno': '2',
        'discno': '3',
        'year': '2030'
    }
    builder = EnvironBuilder(method='POST', data=values)
    handler = SubmitHandler(connect=provider(conn))
    resp = handler.handle(Request(builder.get_environ()))
    assert_equals('application/json; charset=UTF-8', resp.content_type)
    expected = {"status": "ok"}
    assert_json_equals(expected, resp.data)
    assert_equals('200 OK', resp.status)
    query = tables.submission.select().order_by(tables.submission.c.id.desc()).limit(1)
    submission = conn.execute(query).fetchone()
    assert_equals('b9c05616-1874-4d5d-b30e-6b959c922d28', submission['mbid'])
    assert_equals(1, submission['meta_id'])
    row = conn.execute("SELECT * FROM meta WHERE id=1").fetchone()
    expected = {
        'id': 1,
        'track': 'Voodoo People',
        'artist': 'The Prodigy',
        'album': 'Music For The Jitled People',
        'album_artist': 'Prodigy',
        'track_no': 2,
        'disc_no': 3,
        'year': 2030
    }
    assert_equals(expected, dict(row))
    def test_07_sign_response(self):
        builder = EnvironBuilder(method='POST',
                                 data={},
                                 headers={})
        env = builder.get_environ()
        env["REMOTE_ADDR"] = "192.168.0.1"
        req = Request(env)
        req.values = {"user": "******",
                      "pass": "******",
                      "nonce": "12345678"}

        res = {"jsonrpc": "2.0",
               "result": {"status": True,
                          "value": True},
               "version": "privacyIDEA test",
               "id": 1}
        resp = Response(json.dumps(res))
        from privacyidea.lib.crypto import Sign
        g.sign_object = Sign("tests/testdata/private.pem",
                             "tests/testdata/public.pem")

        new_response = sign_response(req, resp)
        jresult = json.loads(new_response.data)
        self.assertEqual(jresult.get("nonce"), "12345678")
        self.assertEqual(jresult.get("signature"), "7220461805369685253863294214862525311437731987121534735993146952136348520396812489782945679627890785973634896605293523175424850299832912878523161817380029213546063467888018205435416020286712762804412024065559270543774578319469096483246637875013247101135063221604113204491121777932147776087110152414627230087278622508771143940031542890514380486863296102037208395371717795767683973979032142677315402422403254992482761563612174177151960004042109847122772813717599078313600692433727690239340230353616318691769042290314664126975201679642739717702497638318611217001361093950139025744740660953017413716736691777322916588328")
Beispiel #24
0
    def test_loading_file(self):
        """Test that it loads image from disk."""
        self.hass.wsgi = mock.MagicMock()

        with NamedTemporaryFile() as fp:
            fp.write('hello'.encode('utf-8'))
            fp.flush()

            assert setup_component(
                self.hass, 'camera', {
                    'camera': {
                        'name': 'config_test',
                        'platform': 'local_file',
                        'file_path': fp.name,
                    }
                })

            image_view = self.hass.wsgi.mock_calls[0][1][0]

            builder = EnvironBuilder(method='GET')
            Request = request_class()
            request = Request(builder.get_environ())
            request.authenticated = True
            resp = image_view.get(request, 'camera.config_test')

            assert resp.status_code == 200, resp.response
            assert resp.response[0].decode('utf-8') == 'hello'
    def test_07_set_random_pin(self):
        g.logged_in_user = {"username": "******",
                            "role": "admin"}
        builder = EnvironBuilder(method='POST',
                                 data={'serial': "OATH123456"},
                                 headers={})
        env = builder.get_environ()
        # Set the remote address so that we can filter for it
        env["REMOTE_ADDR"] = "10.0.0.1"
        req = Request(env)

        # Set a policy that defines the tokenlabel
        set_policy(name="pol1",
                   scope=SCOPE.ENROLL,
                   action="%s=%s" % (ACTION.OTPPINRANDOM, "12"))
        set_policy(name="pinhandling",
                   scope=SCOPE.ENROLL,
                   action="%s=privacyidea.lib.pinhandling.base.PinHandler" %
                          ACTION.PINHANDLING)
        g.policy_object = PolicyClass()

        # request, that matches the policy
        req.all_data = {
                        "user": "******",
                        "realm": "home"}
        init_random_pin(req)

        # Check, if the tokenlabel was added
        self.assertEqual(len(req.all_data.get("pin")), 12)
        # finally delete policy
        delete_policy("pol1")
        delete_policy("pinhandling")
Beispiel #26
0
def test_full_access_to_name_request(test_name, \
                                    name_request_number, temp_request_number, user_email, user_phone, \
                                    header_name_request_number, header_temp_request_number, header_user_email, header_user_phone, \
                                    expected):
    """Assure that this contains the headers required to fully access an NR."""
    from namex.utils.auth import full_access_to_name_request

    # setup
    nr = RequestDAO()
    nr.nrNum = name_request_number or temp_request_number
    nr.stateCd = State.DRAFT
    nr._source = ValidSources.NAMEREQUEST.value
    applicant = Applicant()
    applicant.phoneNumber = user_phone
    applicant.emailAddress = user_email
    nr.applicants.append(applicant)
    nr.save_to_db()

    builder = EnvironBuilder(method='POST',
                             data={},
                             headers={
                                 'BCREG_NR': header_name_request_number,
                                 'BCREG_NRL': header_temp_request_number,
                                 'BCREG-User-Email': header_user_email,
                                 'BCREG-User-Phone': header_user_phone
                             })
    env = builder.get_environ()
    req = Request(env)

    print(req)

    assert expected == full_access_to_name_request(req)
    def test_14_required_email(self):
        g.logged_in_user = {"username": "******",
                            "role": "admin"}
        builder = EnvironBuilder(method='POST',
                                 data={'serial': "OATH123456"},
                                 headers={})
        env = builder.get_environ()
        # Set the remote address so that we can filter for it
        env["REMOTE_ADDR"] = "10.0.0.1"
        req = Request(env)
        # Set a mangle policy to change the username
        # and only use the last 4 characters of the username
        set_policy(name="email1",
                   scope=SCOPE.REGISTER,
                   action="%s=/.*@mydomain\..*" % ACTION.REQUIREDEMAIL)
        g.policy_object = PolicyClass()
        # request, that matches the policy
        req.all_data = {"email": "*****@*****.**"}
        # This emails is allowed
        r = required_email(req)
        self.assertTrue(r)

        # This email is not allowed
        req.all_data = {"email": "*****@*****.**"}
        # This emails is allowed
        self.assertRaises(RegistrationError, required_email, req)

        delete_policy("email1")
        g.policy_object = PolicyClass()
        # Without a policy, this email can register
        req.all_data = {"email": "*****@*****.**"}
        # This emails is allowed
        r = required_email(req)
        self.assertTrue(r)
Beispiel #28
0
    def test_tg_302(self):

        client = Client(application)
        builder = EnvironBuilder(path="/tg/http://www.espn.com",
                                 headers=[("Prefer", "tg_302")])
        env = builder.get_environ()
        app_iter, status, headers = client.run_wsgi_app(env)

        assert "302" in status
        assert headers.get("Link")
        assert "accept-datetime" in headers.get("Vary", "")
        assert headers.get("Location") is not None

        lh = parse_link_header(headers.get("Link"))

        assert get_uri_dt_for_rel(lh, ["original"])
        assert get_uri_dt_for_rel(lh, ["first"])
        f_dt = get_uri_dt_for_rel(lh, ["first"]).get("first")
        assert convert_to_datetime(f_dt["datetime"][0]) is not None
        assert get_uri_dt_for_rel(lh, ["last"])
        l_dt = get_uri_dt_for_rel(lh, ["last"]).get("last")
        assert convert_to_datetime(l_dt["datetime"][0]) is not None
        assert get_uri_dt_for_rel(lh, ["memento"])
        m_dt = get_uri_dt_for_rel(lh, ["memento"]).get("memento")
        assert convert_to_datetime(m_dt["datetime"][0]) is not None
Beispiel #29
0
    def test_callback_view_no_jwt(self):
        """Test that the notification callback view works without JWT."""
        hass = MagicMock()

        m = mock_open()
        with patch(
                'homeassistant.components.notify.html5.open', m, create=True
        ):
            hass.config.path.return_value = 'file.conf'
            service = html5.get_service(hass, {})

            assert service is not None

            # assert hass.called
            assert len(hass.mock_calls) == 3

            view = hass.mock_calls[2][1][0]

            builder = EnvironBuilder(method='POST', data=json.dumps({
                'type': 'push',
                'tag': '3bc28d69-0921-41f1-ac6a-7a627ba0aa72'
            }))
            Request = request_class()
            resp = view.post(Request(builder.get_environ()))

            assert resp.status_code == 401, resp.response
Beispiel #30
0
    def test_sync_1(self, mock_create_labbooks_no_lfs, mock_config_file):

        # Setup responses mock for this test
        responses.add(responses.GET, 'https://usersrv.gigantum.io/key',
                      json={'key': 'afaketoken'}, status=200)

        im = InventoryManager(mock_create_labbooks_no_lfs[0])
        test_user_lb = im.load_labbook('default', 'default', 'labbook1')
        test_user_wf = LabbookWorkflow(test_user_lb)
        test_user_wf.publish('default')

        # Mock the request context so a fake authorization header is present
        builder = EnvironBuilder(path='/labbook', method='POST', headers={'Authorization': 'Bearer AJDFHASD'})
        env = builder.get_environ()
        req = Request(environ=env)


        sally_wf = LabbookWorkflow.import_from_remote(test_user_wf.remote, 'sally', config_file=mock_config_file[0])
        sally_lb = sally_wf.labbook
        FileOperations.makedir(sally_lb, relative_path='code/sally-dir', create_activity_record=True)
        sally_wf.sync('sally')

        sync_query = """
        mutation x {
            syncLabbook(input: {
                labbookName: "labbook1",
                owner: "default"
            }) {
                jobKey
            }
        }
        """
        r = mock_create_labbooks_no_lfs[2].execute(sync_query, context_value=req)

        assert 'errors' not in r
    def test_10_api_endpoint(self):
        fixed = "ebedeeefegeheiej"
        otpkey = "cc17a4d77eaed96e9d14b5c87a02e718"
        uid = "000000000000"
        otps = ["ebedeeefegeheiejtjtrutblehenfjljrirgdihrfuetljtt",
                "ebedeeefegeheiejlekvlrlkrcluvctenlnnjfknrhgtjned",
                "ebedeeefegeheiejktudedbktcnbuntrhdueikggtrugckij",
                "ebedeeefegeheiejjvjncbnffdrvjcvrbgdfufjgndfetieu",
                "ebedeeefegeheiejdruibhvlvktcgfjiruhltketifnitbuk"
        ]

        token = init_token({"type": "yubikey",
                            "otpkey": otpkey,
                            "otplen": len(otps[0]),
                            "yubikey.prefix": fixed,
                            "serial": "UBAM12345678_1"})

        builder = EnvironBuilder(method='GET',
                                 headers={})
        env = builder.get_environ()
        # Set the remote address so that we can filter for it
        env["REMOTE_ADDR"] = "10.0.0.1"
        g.client_ip = env["REMOTE_ADDR"]
        req = Request(env)
        nonce = "random nonce"
        apiid = "hallo"
        apikey = "1YMEbMZijD3DzL21UfKGnOOI13c="
        set_privacyidea_config("yubikey.apiid.{0!s}".format(apiid), apikey)
        req.all_data = {'id': apiid,
                        "otp": otps[0],
                        "nonce": nonce}
        text_type, result = YubikeyTokenClass.api_endpoint(req, g)
        self.assertEqual(text_type, "plain")
        self.assertTrue("status=OK" in result, result)
        self.assertTrue("nonce={0!s}".format(nonce) in result, result)
Beispiel #32
0
    def test_reset_branch_to_remote(self, fixture_working_dir, mock_create_labbooks_no_lfs):
        # Mock the request context so a fake authorization header is present
        builder = EnvironBuilder(path='/labbook', method='POST', headers={'Authorization': 'Bearer AJDFHASD'})
        env = builder.get_environ()
        req = Request(environ=env)

        im = InventoryManager(mock_create_labbooks_no_lfs[0])
        test_user_lb = im.load_labbook('default', 'default', 'labbook1')
        wf = LabbookWorkflow(test_user_lb)
        wf.publish(username='******')
        hash_original = wf.labbook.git.commit_hash

        new_file_path = os.path.join(wf.labbook.root_dir, 'input', 'new-file')
        with open(new_file_path, 'w') as f: f.write('File data')
        wf.labbook.sweep_uncommitted_changes()
        hash_before_reset = wf.labbook.git.commit_hash

        publish_query = f"""
        mutation c {{
            resetBranchToRemote(input: {{
                labbookName: "labbook1",
                owner: "default"
            }}) {{
                labbook {{
                    activeBranchName
                }}
            }}
        }}
        """

        r = mock_create_labbooks_no_lfs[2].execute(publish_query, context_value=req)
        assert 'errors' not in r
        assert wf.labbook.git.commit_hash == hash_original
Beispiel #33
0
    def test_callback_view_no_jwt(self):
        """Test that the notification callback view works without JWT."""
        hass = MagicMock()

        with tempfile.NamedTemporaryFile() as fp:
            hass.config.path.return_value = fp.name
            fp.close()
            service = html5.get_service(hass, {})

            assert service is not None

            # assert hass.called
            assert len(hass.mock_calls) == 3

            view = hass.mock_calls[2][1][0]

            builder = EnvironBuilder(method='POST',
                                     data=json.dumps({
                                         'type':
                                         'push',
                                         'tag':
                                         '3bc28d69-0921-41f1-ac6a-7a627ba0aa72'
                                     }))
            Request = request_class()
            resp = view.post(Request(builder.get_environ()))

            assert resp.status_code == 401, resp.response
Beispiel #34
0
    def test_registering_new_device_view(self):
        """Test that the HTML view works."""
        hass = MagicMock()

        with tempfile.NamedTemporaryFile() as fp:
            hass.config.path.return_value = fp.name
            fp.close()
            service = html5.get_service(hass, {})

            assert service is not None

            # assert hass.called
            assert len(hass.mock_calls) == 3

            view = hass.mock_calls[1][1][0]
            assert view.json_path == fp.name
            assert view.registrations == {}

            builder = EnvironBuilder(method='POST',
                                     data=json.dumps(SUBSCRIPTION_1))
            Request = request_class()
            resp = view.post(Request(builder.get_environ()))

            expected = {
                'unnamed device': SUBSCRIPTION_1,
            }

            assert resp.status_code == 200, resp.response
            assert view.registrations == expected
            with open(fp.name) as fpp:
                assert json.load(fpp) == expected
    def test_loading_file(self):
        """Test that it loads image from disk."""
        self.hass.wsgi = mock.MagicMock()

        with NamedTemporaryFile() as fp:
            fp.write('hello'.encode('utf-8'))
            fp.flush()

            assert setup_component(self.hass, 'camera', {
                'camera': {
                    'name': 'config_test',
                    'platform': 'local_file',
                    'file_path': fp.name,
                }})

            image_view = self.hass.wsgi.mock_calls[0][1][0]

            builder = EnvironBuilder(method='GET')
            Request = request_class()
            request = Request(builder.get_environ())
            request.authenticated = True
            resp = image_view.get(request, 'camera.config_test')

            assert resp.status_code == 200, resp.response
            assert resp.response[0].decode('utf-8') == 'hello'
Beispiel #36
0
    def test_import_remote_labbook(self, remote_labbook_repo,
                                   fixture_working_dir, property_mocks_fixture,
                                   docker_socket_fixture, monkeypatch):

        # Mock the request context so a fake authorization header is present
        builder = EnvironBuilder(path='/labbook',
                                 method='POST',
                                 headers={'Authorization': 'Bearer AJDFHASD'})
        env = builder.get_environ()
        req = Request(environ=env)

        monkeypatch.setattr(Configuration, 'find_default_config',
                            lambda x: fixture_working_dir[0])

        def mock_dispatch(*args, **kwargs):
            return JobKey('rq:job:000-000-000')

        monkeypatch.setattr(Dispatcher, 'dispatch_task', mock_dispatch)

        query = f"""
        mutation importFromRemote {{
          importRemoteLabbook(
            input: {{
              owner: "test",
              labbookName: "sample-repo-lb",
              remoteUrl: "{remote_labbook_repo}"
            }}) {{
                jobKey
            }}
        }}
        """
        r = fixture_working_dir[2].execute(query, context_value=req)
        assert 'errors' not in r
        assert r['data']['importRemoteLabbook'][
            'jobKey'] == 'rq:job:000-000-000'
 def test_valid(self):
     builder = EnvironBuilder(method='POST', data={**valid_payload})
     env = builder.get_environ()
     req = Request(env)
     f = DatacheckSubmissionForm(req.form)
     f = set_dynamic_choices(f)
     self.assertTrue(f.validate())
Beispiel #38
0
    def test_publish_basic(self, fixture_working_dir,
                           mock_create_labbooks_no_lfs):

        # Mock the request context so a fake authorization header is present
        builder = EnvironBuilder(path='/labbook',
                                 method='POST',
                                 headers={'Authorization': 'Bearer AJDFHASD'})
        env = builder.get_environ()
        req = Request(environ=env)

        im = InventoryManager(mock_create_labbooks_no_lfs[0])
        test_user_lb = im.load_labbook('default', 'default', 'labbook1')

        publish_query = f"""
        mutation c {{
            publishLabbook(input: {{
                labbookName: "labbook1",
                owner: "default"
            }}) {{
                jobKey
            }}
        }}
        """

        r = mock_create_labbooks_no_lfs[2].execute(publish_query,
                                                   context_value=req)
        assert 'errors' not in r
def test_submit_handler_foreignid(conn):
    values = {'format': 'json', 'client': 'app1key', 'user': '******',
        'duration': str(TEST_1_LENGTH), 'fingerprint': TEST_1_FP, 'bitrate': 192,
        'foreignid': 'foo:123', 'fileformat': 'FLAC'}
    builder = EnvironBuilder(method='POST', data=values)
    handler = SubmitHandler(connect=provider(conn))
    resp = handler.handle(Request(builder.get_environ()))
    assert_equals('application/json; charset=UTF-8', resp.content_type)
    expected = {"status": "ok"}
    assert_json_equals(expected, resp.data)
    assert_equals('200 OK', resp.status)
    query = tables.submission.select().order_by(tables.submission.c.id.desc()).limit(1)
    submission = conn.execute(query).fetchone()
    assert_equals(None, submission['mbid'])
    assert_equals(None, submission['puid'])
    assert_equals(1, submission['foreignid_id'])
    assert_equals(1, submission['format_id'])
    assert_equals(192, submission['bitrate'])
    assert_equals(TEST_1_FP_RAW, submission['fingerprint'])
    assert_equals(TEST_1_LENGTH, submission['length'])
    query = tables.foreignid_vendor.select().order_by(tables.foreignid_vendor.c.id.desc()).limit(1)
    row = conn.execute(query).fetchone()
    assert_equals(1, row['id'])
    assert_equals('foo', row['name'])
    query = tables.foreignid.select().order_by(tables.foreignid.c.id.desc()).limit(1)
    row = conn.execute(query).fetchone()
    assert_equals(1, row['id'])
    assert_equals(1, row['vendor_id'])
    assert_equals('123', row['name'])
Beispiel #40
0
def test_submit_handler(conn):
    values = {
        'client': 'app1key',
        'user': '******',
        'length': str(TEST_1_LENGTH),
        'fingerprint': TEST_1_FP,
        'bitrate': 192,
        'mbid': 'b9c05616-1874-4d5d-b30e-6b959c922d28',
        'format': 'FLAC'
    }
    builder = EnvironBuilder(method='POST', data=values)
    handler = SubmitHandler.create_from_server(tests.script, conn=conn)
    resp = handler.handle(Request(builder.get_environ()))
    assert_equals('text/xml; charset=UTF-8', resp.content_type)
    expected = "<?xml version='1.0' encoding='UTF-8'?>\n<response><status>ok</status><submissions><submission><status>pending</status><id>1</id></submission></submissions></response>"
    assert_equals(expected, resp.data)
    assert_equals('200 OK', resp.status)
    query = tables.submission.select().order_by(
        tables.submission.c.id.desc()).limit(1)
    submission = conn.execute(query).fetchone()
    assert_equals('b9c05616-1874-4d5d-b30e-6b959c922d28', submission['mbid'])
    assert_equals(1, submission['format_id'])
    assert_equals(192, submission['bitrate'])
    assert_equals(TEST_1_FP_RAW, submission['fingerprint'])
    assert_equals(TEST_1_LENGTH, submission['length'])
    def test_01a_admin_realms(self):
        admin1 = {"username": "******",
                  "role": "admin",
                  "realm": "realm1"}

        admin2 = {"username": "******",
                  "role": "admin",
                  "realm": "realm2"}

        set_policy(name="pol",
                   scope=SCOPE.ADMIN,
                   action="*", adminrealm="realm1")
        g.policy_object = PolicyClass()
        builder = EnvironBuilder(method='POST',
                                 data={'serial': "OATH123456"},
                                 headers={})
        env = builder.get_environ()
        # Set the remote address so that we can filter for it
        env["REMOTE_ADDR"] = "10.0.0.1"
        req = Request(env)
        req.all_data = {}

        # admin1 is allowed to do everything
        g.logged_in_user = admin1
        r = check_base_action(req, action="delete")
        self.assertTrue(r)

        # admin2 is not allowed.
        g.logged_in_user = admin2
        self.assertRaises(PolicyError, check_base_action, req, action="delete")
        delete_policy("pol")
Beispiel #42
0
    def test_10_check_conditions_tokentype(self):
        uhandler = UserNotificationEventHandler()
        # check if tokenrealm is contained
        builder = EnvironBuilder(method='POST',
                                 data={'user': "******"},
                                 headers={})

        tok = init_token({"serial": "oath1234", "type": "spass"},
                         user=User("cornelius", "realm1"))

        env = builder.get_environ()
        req = Request(env)
        req.all_data = {"user": "******",
                        "serial": "oath1234"}
        req.User = User("cornelius", "realm1")
        resp = Response()
        resp.data = """{"result": {"value": true}}"""
        r = uhandler.check_condition(
            {"g": {},
             "handler_def": {"conditions": {"tokentype": "totp,spass,oath,"}},
             "request": req,
             "response": resp
             }
        )
        # Serial matches the regexp
        self.assertEqual(r, True)
    def test_06_set_tokenlabel(self):
        g.logged_in_user = {"username": "******",
                            "role": "admin"}
        builder = EnvironBuilder(method='POST',
                                 data={'serial': "OATH123456"},
                                 headers={})
        env = builder.get_environ()
        # Set the remote address so that we can filter for it
        env["REMOTE_ADDR"] = "10.0.0.1"
        req = Request(env)

        # Set a policy that defines the tokenlabel
        set_policy(name="pol1",
                   scope=SCOPE.ENROLL,
                   action="%s=%s" % (ACTION.TOKENLABEL, "<u>@<r>"))
        set_policy(name="pol2",
                   scope=SCOPE.ENROLL,
                   action="%s=%s" % (ACTION.TOKENISSUER, "myPI"))
        g.policy_object = PolicyClass()

        # request, that matches the policy
        req.all_data = {
                        "user": "******",
                        "realm": "home"}
        init_tokenlabel(req)

        # Check, if the tokenlabel was added
        self.assertEqual(req.all_data.get("tokenlabel"), "<u>@<r>")
        # Check, if the tokenissuer was added
        self.assertEqual(req.all_data.get("tokenissuer"), "myPI")
        # finally delete policy
        delete_policy("pol1")
        delete_policy("pol2")
    def test_publish_basic(self, fixture_working_dir, remote_bare_repo,
                           mock_create_labbooks_no_lfs):

        # Mock the request context so a fake authorization header is present
        builder = EnvironBuilder(path='/labbook',
                                 method='POST',
                                 headers={'Authorization': 'Bearer AJDFHASD'})
        env = builder.get_environ()
        req = Request(environ=env)

        test_user_lb = LabBook(mock_create_labbooks_no_lfs[0])
        test_user_lb.from_name('default', 'default', 'labbook1')

        publish_query = f"""
        mutation c {{
            publishLabbook(input: {{
                labbookName: "labbook1",
                owner: "default"
            }}) {{
                success
            }}
        }}
        """

        r = mock_create_labbooks_no_lfs[2].execute(publish_query,
                                                   context_value=req)
        assert 'errors' not in r
        assert r['data']['publishLabbook']['success'] is True
    def test_08_encrypt_pin(self):
        g.logged_in_user = {"username": "******",
                            "role": "admin"}
        builder = EnvironBuilder(method='POST',
                                 data={'serial': "OATH123456"},
                                 headers={})
        env = builder.get_environ()
        # Set the remote address so that we can filter for it
        env["REMOTE_ADDR"] = "10.0.0.1"
        req = Request(env)

        # Set a policy that defines the PIN to be encrypted
        set_policy(name="pol1",
                   scope=SCOPE.ENROLL,
                   action=ACTION.ENCRYPTPIN)
        g.policy_object = PolicyClass()

        # request, that matches the policy
        req.all_data = {
                        "user": "******",
                        "realm": "home"}
        encrypt_pin(req)

        # Check, if the tokenlabel was added
        self.assertEqual(req.all_data.get("encryptpin"), "True")
        # finally delete policy
        delete_policy("pol1")
Beispiel #46
0
 def filestorage(self, filename):
     data = open(filename)
     builder = EnvironBuilder(method='POST',
                              data={'file': (data, basename(filename))})
     env = builder.get_environ()
     req = Request(env)
     return req.files['file']
    def test_13_remote_user(self):
        g.logged_in_user = {"username": "******",
                            "role": "admin"}
        builder = EnvironBuilder(method='POST',
                                 data={'serial': "OATH123456"},
                                 headers={})
        env = builder.get_environ()
        # Set the remote address so that we can filter for it
        env["REMOTE_ADDR"] = "10.0.0.1"
        env["REMOTE_USER"] = "******"
        req = Request(env)

        # A user, for whom the login via REMOTE_USER is allowed.
        set_policy(name="ruser",
                   scope=SCOPE.WEBUI,
                   action="%s=%s" % (ACTION.REMOTE_USER, REMOTE_USER.ACTIVE))
        g.policy_object = PolicyClass()

        r = is_remote_user_allowed(req)
        self.assertEqual(r, [REMOTE_USER.ACTIVE])

        # Login for the REMOTE_USER is not allowed.
        # Only allowed for user "super", but REMOTE_USER=admin
        set_policy(name="ruser",
                   scope=SCOPE.WEBUI,
                   action="%s=%s" % (ACTION.REMOTE_USER, REMOTE_USER.ACTIVE),
                   user="******")
        g.policy_object = PolicyClass()

        r = is_remote_user_allowed(req)
        self.assertEqual(r, [])

        delete_policy("ruser")
Beispiel #48
0
def test_environ_builder_paths():
    b = EnvironBuilder(path='/foo', base_url='http://example.com/')
    strict_eq(b.base_url, 'http://example.com/')
    strict_eq(b.path, '/foo')
    strict_eq(b.script_root, '')
    strict_eq(b.host, 'example.com')

    b = EnvironBuilder(path='/foo', base_url='http://example.com/bar')
    strict_eq(b.base_url, 'http://example.com/bar/')
    strict_eq(b.path, '/foo')
    strict_eq(b.script_root, '/bar')
    strict_eq(b.host, 'example.com')

    b.host = 'localhost'
    strict_eq(b.base_url, 'http://localhost/bar/')
    b.base_url = 'http://localhost:8080/'
    strict_eq(b.host, 'localhost:8080')
    strict_eq(b.server_name, 'localhost')
    strict_eq(b.server_port, 8080)

    b.host = 'foo.invalid'
    b.url_scheme = 'https'
    b.script_root = '/test'
    env = b.get_environ()
    strict_eq(env['SERVER_NAME'], 'foo.invalid')
    strict_eq(env['SERVER_PORT'], '443')
    strict_eq(env['SCRIPT_NAME'], '/test')
    strict_eq(env['PATH_INFO'], '/foo')
    strict_eq(env['HTTP_HOST'], 'foo.invalid')
    strict_eq(env['wsgi.url_scheme'], 'https')
    strict_eq(b.base_url, 'https://foo.invalid/test/')
    def test_15_reset_password(self):
        builder = EnvironBuilder(method='POST',
                                 data={'user': "******",
                                       "realm": self.realm1},
                                 headers={})
        env = builder.get_environ()
        # Set the remote address so that we can filter for it
        env["REMOTE_ADDR"] = "10.0.0.1"
        req = Request(env)
        # Set a mangle policy to change the username
        # and only use the last 4 characters of the username
        set_policy(name="recover",
                   scope=SCOPE.USER,
                   action="%s" % ACTION.RESYNC)
        g.policy_object = PolicyClass()
        req.all_data = {"user": "******", "realm": self.realm1}
        # There is a user policy without password reset, so an exception is
        # raised
        self.assertRaises(PolicyError, check_anonymous_user, req,
                          ACTION.PASSWORDRESET)

        # The password reset is allowed
        set_policy(name="recover",
                   scope=SCOPE.USER,
                   action="%s" % ACTION.PASSWORDRESET)
        g.policy_object = PolicyClass()
        r = check_anonymous_user(req, ACTION.PASSWORDRESET)
        self.assertEqual(r, True)
Beispiel #50
0
 def test_get_base_uri(self):
     path = '/%s/' % self.test_jp2_color_id
     builder = EnvironBuilder(path=path)
     env = builder.get_environ()
     req = Request(env)
     base_uri = self.app._get_base_uri(req, self.test_jp2_color_id)
     self.assertEqual(base_uri, 'http://localhost/01%2F02%2F0001.jp2')
Beispiel #51
0
    def open(self, *args, **kwargs):
        as_tuple = kwargs.pop("as_tuple", False)
        buffered = kwargs.pop("buffered", False)
        follow_redirects = kwargs.pop("follow_redirects", False)

        if (not kwargs and len(args) == 1
                and isinstance(args[0], (werkzeug.test.EnvironBuilder, dict))):
            environ = self.environ_base.copy()

            if isinstance(args[0], werkzeug.test.EnvironBuilder):
                environ.update(args[0].get_environ())
            else:
                environ.update(args[0])

            environ["flask._preserve_context"] = self.preserve_context
        else:
            kwargs.setdefault(
                "environ_overrides",
                {})["flask._preserve_context"] = self.preserve_context
            kwargs.setdefault("environ_base", self.environ_base)
            builder = EnvironBuilder(self.application, *args, **kwargs)

            try:
                environ = builder.get_environ()
            finally:
                builder.close()

        return Client.open(
            self,
            environ,
            as_tuple=as_tuple,
            buffered=buffered,
            follow_redirects=follow_redirects,
        )
 def test_wrong_token_jwt_sso(self, sso):
     Config.jwt_secret = "jwt_token"
     builder = EnvironBuilder(headers=[("Cookie", "token=cookie")])
     request = Request(builder.get_environ())
     user = self.valid_token(token="lallabalalla", _request=request)
     self.assertEqual(42, user)
     sso.assert_called_once_with("cookie", "lallabalalla")
Beispiel #53
0
    def test_registering_new_device_view(self):
        """Test that the HTML view works."""
        hass = MagicMock()

        m = mock_open()
        with patch(
                'homeassistant.components.notify.html5.open', m, create=True
        ):
            hass.config.path.return_value = 'file.conf'
            service = html5.get_service(hass, {})

            assert service is not None

            # assert hass.called
            assert len(hass.mock_calls) == 3

            view = hass.mock_calls[1][1][0]
            assert view.json_path == hass.config.path.return_value
            assert view.registrations == {}

            builder = EnvironBuilder(method='POST',
                                     data=json.dumps(SUBSCRIPTION_1))
            Request = request_class()
            resp = view.post(Request(builder.get_environ()))

            expected = {
                'unnamed device': SUBSCRIPTION_1,
            }

            assert resp.status_code == 200, resp.response
            assert view.registrations == expected
            handle = m()
            assert json.loads(handle.write.call_args[0][0]) == expected
Beispiel #54
0
def test_submit_handler(conn):
    values = {
        'format': 'json',
        'client': 'app1key',
        'user': '******',
        'duration': str(TEST_1_LENGTH),
        'fingerprint': TEST_1_FP,
        'bitrate': 192,
        'mbid': 'b9c05616-1874-4d5d-b30e-6b959c922d28',
        'fileformat': 'FLAC'
    }
    builder = EnvironBuilder(method='POST', data=values)
    handler = SubmitHandler(connect=provider(conn))
    resp = handler.handle(Request(builder.get_environ()))
    assert_equals('application/json; charset=UTF-8', resp.content_type)
    expected = {"status": "ok"}
    assert_json_equals(expected, resp.data)
    assert_equals('200 OK', resp.status)
    query = tables.submission.select().order_by(
        tables.submission.c.id.desc()).limit(1)
    submission = conn.execute(query).fetchone()
    assert_equals('b9c05616-1874-4d5d-b30e-6b959c922d28', submission['mbid'])
    assert_equals(1, submission['format_id'])
    assert_equals(192, submission['bitrate'])
    assert_equals(TEST_1_FP_RAW, submission['fingerprint'])
    assert_equals(TEST_1_LENGTH, submission['length'])
Beispiel #55
0
    def test_environ_builder_paths(self):
        b = EnvironBuilder(path='/foo', base_url='http://example.com/')
        assert b.base_url == 'http://example.com/'
        assert b.path == '/foo'
        assert b.script_root == ''
        assert b.host == 'example.com'

        b = EnvironBuilder(path='/foo', base_url='http://example.com/bar')
        assert b.base_url == 'http://example.com/bar/'
        assert b.path == '/foo'
        assert b.script_root == '/bar'
        assert b.host == 'example.com'

        b.host = 'localhost'
        assert b.base_url == 'http://localhost/bar/'
        b.base_url = 'http://localhost:8080/'
        assert b.host == 'localhost:8080'
        assert b.server_name == 'localhost'
        assert b.server_port == 8080

        b.host = 'foo.invalid'
        b.url_scheme = 'https'
        b.script_root = '/test'
        env = b.get_environ()
        assert env['SERVER_NAME'] == 'foo.invalid'
        assert env['SERVER_PORT'] == '443'
        assert env['SCRIPT_NAME'] == '/test'
        assert env['PATH_INFO'] == '/foo'
        assert env['HTTP_HOST'] == 'foo.invalid'
        assert env['wsgi.url_scheme'] == 'https'
        assert b.base_url == 'https://foo.invalid/test/'
Beispiel #56
0
 def test_format_message(self):
     # Build test environment
     builder = EnvironBuilder(method='POST',
                              data={'name': 'Valid Guy',
                                    'email': '*****@*****.**',
                                    'some_field': ("This is multi line and "
                                                   "should not be on the "
                                                   "same line as the title"),
                                    'redirect': 'http://www.example.com',
                                    'last_name': '',
                                    'token': conf.TOKEN})
     env = builder.get_environ()
     req = Request(env)
     target_message = ("Contact:\n"
                       "--------\n"
                       "NAME:   Valid Guy\n"
                       "EMAIL:   [email protected]\n\n"
                       "Information:\n"
                       "------------\n"
                       "Some Field:\n\n"
                       "This is multi line and should not be on the same "
                       "line as the title\n\n")
     message = handler.create_msg(req)
     formatted_message = handler.format_message(message)
     self.assertEqual(formatted_message, target_message)
Beispiel #57
0
 def setUp(self):
     self.ctx = app.test_request_context()
     self.ctx.push()
     init_data()
     self.client = app.test_client()
     builder = EnvironBuilder(method='POST')
     self.post_env = builder.get_environ()
    def test_send_reverse_captcha_request(self, mock):
        content = 'captcha js content'
        builder = EnvironBuilder(
            headers=self.headers,
            path='/fake_app_id/captcha/captcha.js',
            query_string=
            'a=c&amp;u=cfe74220-f484-11e8-9b14-d7280325a290&amp;v=0701bb80-f482-11e8-8a31-a37cf9620569&amp;m=0'
        )

        env = builder.get_environ()
        request = Request(env)
        context = PxContext(request, self.config)
        headers = {
            'host': px_constants.CAPTCHA_HOST,
            px_constants.FIRST_PARTY_HEADER: '1',
            px_constants.ENFORCER_TRUE_IP_HEADER: context.ip,
            px_constants.FIRST_PARTY_FORWARDED_FOR: '127.0.0.1'
        }
        mock.get(
            url=
            'https://captcha.px-cdn.net/PXfake_app_id/captcha.js?a=c&amp;u=cfe74220-f484-11e8-9b14-d7280325a290&amp;v=0701bb80-f482-11e8-8a31-a37cf9620569&amp;m=0',
            text=content,
            request_headers=headers,
            status_code=200,
            reason='OK')
        px_proxy = PxProxy(self.config)
        status, headers, body = px_proxy.send_reverse_captcha_request(
            config=self.config, ctx=context)
        self.assertEqual(content, body)
Beispiel #59
0
    def test_environ_builder_paths(self):
        b = EnvironBuilder(path='/foo', base_url='http://example.com/')
        self.assert_strict_equal(b.base_url, 'http://example.com/')
        self.assert_strict_equal(b.path, '/foo')
        self.assert_strict_equal(b.script_root, '')
        self.assert_strict_equal(b.host, 'example.com')

        b = EnvironBuilder(path='/foo', base_url='http://example.com/bar')
        self.assert_strict_equal(b.base_url, 'http://example.com/bar/')
        self.assert_strict_equal(b.path, '/foo')
        self.assert_strict_equal(b.script_root, '/bar')
        self.assert_strict_equal(b.host, 'example.com')

        b.host = 'localhost'
        self.assert_strict_equal(b.base_url, 'http://localhost/bar/')
        b.base_url = 'http://localhost:8080/'
        self.assert_strict_equal(b.host, 'localhost:8080')
        self.assert_strict_equal(b.server_name, 'localhost')
        self.assert_strict_equal(b.server_port, 8080)

        b.host = 'foo.invalid'
        b.url_scheme = 'https'
        b.script_root = '/test'
        env = b.get_environ()
        self.assert_strict_equal(env['SERVER_NAME'], 'foo.invalid')
        self.assert_strict_equal(env['SERVER_PORT'], '443')
        self.assert_strict_equal(env['SCRIPT_NAME'], '/test')
        self.assert_strict_equal(env['PATH_INFO'], '/foo')
        self.assert_strict_equal(env['HTTP_HOST'], 'foo.invalid')
        self.assert_strict_equal(env['wsgi.url_scheme'], 'https')
        self.assert_strict_equal(b.base_url, 'https://foo.invalid/test/')
Beispiel #60
0
def filestorage(filename, content):
    data = StringIO(str(content)) if isinstance(content,
                                                basestring) else content
    builder = EnvironBuilder(method='POST', data={'file': (data, filename)})
    env = builder.get_environ()
    req = Request(env)
    return req.files['file']