コード例 #1
0
ファイル: auth1_test.py プロジェクト: JiayangY/sirepo
def test_login():
    from pykern import pkunit
    from pykern.pkdebug import pkdp
    from pykern.pkunit import pkeq, pkok, pkre, pkexcept
    from sirepo import auth
    import flask
    import sirepo.auth.guest
    import sirepo.cookie
    import sirepo.http_request

    r = auth.api_authState()
    pkre('LoggedIn": false.*Registration": false', r.data)
    delattr(flask.g, 'sirepo_cookie')
    auth.process_request()
    with pkunit.pkexcept('SRException.*routeName=login'):
        auth.logged_in_user()
    with pkexcept('SRException.*routeName=login'):
        auth.require_user()
    sirepo.cookie.set_sentinel()
    # copying examples for new user takes time
    with pkunit.pkexcept('SRException.*routeName=None'):
        r = auth.login(sirepo.auth.guest, sim_type='myapp')
    r = auth.api_authState()
    pkre('LoggedIn": true.*Registration": false', r.data)
    u = auth.logged_in_user()
    pkok(u, 'user should exist')
    # guests do not require completeRegistration
    auth.require_user()
コード例 #2
0
ファイル: cookie_test.py プロジェクト: njsmith/sirepo
def test_1():
    import shutil
    from pykern import pkconfig, pkunit, pkio
    from pykern.pkunit import pkeq
    from pykern.pkdebug import pkdp
    from sirepo import srunit
    srunit.flask_client()

    from sirepo import cookie
    cookie.init_mock()
    cookie.init('x')
    with pkunit.pkexcept('Unauthorized'):
        cookie.get_user()
    with pkunit.pkexcept('Unauthorized'):
        cookie.get_user(checked=False)
    cookie.set_sentinel()
    cookie.set_user('abc')
    cookie.set_value('hi', 'hello')
    r = _Response(status_code=200)
    cookie.save_to_cookie(r)
    pkeq('sirepo_dev', r.args[0])
    pkeq(False, r.kwargs['secure'])
    pkeq('abc', cookie.get_user())
    cookie.clear_user()
    cookie.unchecked_remove('hi')
    pkeq(None, cookie.get_user(checked=False))
    cookie.init('sirepo_dev={}'.format(r.args[1]))
    pkeq('hello', cookie.get_value('hi'))
    pkeq('abc', cookie.get_user())
コード例 #3
0
ファイル: cookie2_test.py プロジェクト: JiayangY/sirepo
def test_set_get():
    from pykern import pkunit
    from pykern.pkunit import pkeq
    from pykern.pkdebug import pkdp
    from pykern import pkcollections
    from sirepo import cookie

    class _Response(pkcollections.Dict):
        def set_cookie(self, *args, **kwargs):
            self.args = args
            self.kwargs = kwargs

    cookie.process_header('x')
    with pkunit.pkexcept('KeyError'):
        cookie.get_value('hi')
    with pkunit.pkexcept('AssertionError'):
        cookie.set_value('hi', 'hello')
    pkeq(None, cookie.unchecked_get_value('hi'))
    cookie.init_mock()
    cookie.set_value('hi', 'hello')
    r = _Response(status_code=200)
    cookie.save_to_cookie(r)
    pkeq('sirepo_dev', r.args[0])
    pkeq(False, r.kwargs['secure'])
    pkeq('hello', cookie.get_value('hi'))
    cookie.unchecked_remove('hi')
    pkeq(None, cookie.unchecked_get_value('hi'))
    cookie.process_header('sirepo_dev={}'.format(r.args[1]))
    pkeq('hello', cookie.get_value('hi'))
コード例 #4
0
def test_validate_safe_zip():

    from sirepo.template.template_common import validate_safe_zip
    from sirepo.template.srw import validate_magnet_data_file

    zip_dir = str(pkunit.data_dir() + '/zip_dir')

    # Reject a zip that would overwrite files
    with pkunit.pkexcept(AssertionError):
        validate_safe_zip(zip_dir + '/bad_zip_would_overwrite.zip', zip_dir)

    # Reject a zip that would extract a file above the target directory
    with pkunit.pkexcept(AssertionError):
        validate_safe_zip(zip_dir + '/bad_zip_external_file.zip', zip_dir)

    # Reject a zip with unacceptably large file
    with pkunit.pkexcept(AssertionError):
        validate_safe_zip(zip_dir + '/bad_zip_large_file.zip', zip_dir)

    # Reject a zip with executable permissions set
    with pkunit.pkexcept(AssertionError):
        validate_safe_zip(zip_dir + '/bad_zip_executables.zip', zip_dir)

    # Finally, accept a zip file known to be safe
    validate_safe_zip(zip_dir + '/good_zip.zip', zip_dir,
                      validate_magnet_data_file)
コード例 #5
0
def test_validate_safe_zip():
    from sirepo.template import srw
    zip_dir = str(pkunit.data_dir() + '/zip_dir')

    # Reject a zip with no index file
    with pkunit.pkexcept(AssertionError):
        srw._validate_safe_zip(zip_dir + '/bad_zip_no_index.zip', zip_dir,
                               srw.validate_magnet_data_file)

    # Reject a zip with an incomplete index file
    with pkunit.pkexcept(AssertionError):
        srw._validate_safe_zip(zip_dir + '/bad_zip_incomplete_index.zip',
                               zip_dir, srw.validate_magnet_data_file)

    # Reject a zip with entries in index file that are not in zip
    with pkunit.pkexcept(AssertionError):
        srw._validate_safe_zip(zip_dir + '/bad_zip_extra_index.zip', zip_dir,
                               srw.validate_magnet_data_file)

    # Reject a zip with unacceptable file types
    with pkunit.pkexcept(AssertionError):
        srw._validate_safe_zip(zip_dir + '/bad_zip_bad_types.zip', zip_dir,
                               srw.validate_magnet_data_file)

    # Finally, make sure the included measurement files are OK
    # We're not really extracting them so just send the test directory as target
    for f in [
            'magn_meas_chx.zip', 'magn_meas_esm.zip', 'magn_meas_fmx.zip',
            'magn_meas_srx.zip', 'magn_meas_u20_hxn.zip', 'magn_meas_chx.zip'
    ]:
        srw._validate_safe_zip(pkresource.filename('template/srw/' + f, srw),
                               zip_dir, srw.validate_magnet_data_file)
コード例 #6
0
ファイル: systemd_test.py プロジェクト: radiasoft/rsconf
def test_on_calendar():
    from pykern.pkunit import pkeq, pkexcept
    from rsconf.systemd import _on_calendar
    import datetime

    z = 'America/Denver'
    d = datetime.datetime(2019, 8, 1)
    s = datetime.datetime(2019, 12, 1)
    pkeq('Sun *-*-* 6:0:0', _on_calendar('Sun 0', z, d))
    pkeq('Sun *-*-* 7:0:0', _on_calendar('Sun 0', z, s))
    pkeq('*-*-* 9:0:0', _on_calendar(3, z, d))
    pkeq('*-*-* 9:0:0', _on_calendar('3', z, d))
    pkeq('*-*-* 10:0:0', _on_calendar('3', z, s))
    pkeq('Mon-Fri *-*-* 23:0:0', _on_calendar('Mon-Fri 17', z, d))
    pkeq('Mon-Fri *-*-* 23:59:0', _on_calendar('Mon-Fri 17', z, s))
    pkeq("*-*-* *:0/5:0", _on_calendar('*:0/5', z, d))
    pkeq('*-*-* 0:0:0', _on_calendar('18', z, d))
    pkeq('*-*-* 1:0:0', _on_calendar('18', z, s))
    pkeq('*-*-1 12:0:0', _on_calendar('1 6', z, d))
    pkeq('*-*-1 13:0:0', _on_calendar('1 6', z, s))
    pkeq('*-*-* 3:30:0', _on_calendar('21:30', z, d))
    pkeq('*-*-* 4:30:0', _on_calendar('21:30', z, s))
    pkeq('Thu *-*-* 22:00:0', _on_calendar('Thu 16:00', z, d))
    pkeq('Thu *-*-* 23:00:0', _on_calendar('Thu 16:00', z, s))
    with pkexcept('midnight'):
        _on_calendar('1 18', z, s)
    with pkexcept('midnight'):
        _on_calendar('1 18:30', z, s)
コード例 #7
0
ファイル: test_test.py プロジェクト: moellep/pykern
def test_simple(capsys):
    from pykern import pkunit
    import pykern.pkcli.test

    with pkunit.save_chdir_work() as d:
        t = d.join('tests')
        pkunit.data_dir().join('tests').copy(t)
        with pkunit.pkexcept('FAILED=1 passed=1'):
            pykern.pkcli.test.default_command()
        o, e = capsys.readouterr()
        pkunit.pkre('1_test.py pass', o)
        pkunit.pkre('2_test.py FAIL', o)
        t.join('2_test.py').rename(t.join('2_test.py-'))
        pkunit.pkre('passed=1', pykern.pkcli.test.default_command())
        o, e = capsys.readouterr()
        pkunit.pkre('1_test.py pass', o)
        pkunit.pkre('passed=1',
                    pykern.pkcli.test.default_command('tests/1_test.py'))
        o, e = capsys.readouterr()
        pkunit.pkre('1_test.py pass', o)
        t.join('2_test.py-').rename(t.join('2_test.py'))
        t.join('1_test.py').rename(t.join('1_test.py-'))
        with pkunit.pkexcept('FAILED=1 passed=0'):
            pykern.pkcli.test.default_command()
        o, e = capsys.readouterr()
        pkunit.pkre('2_test.py FAIL', o)
        pkunit.pkre('x = 1 / 0', o)
コード例 #8
0
def test_validate_safe_zip():
    from sirepo.template.template_common import validate_safe_zip
    from sirepo.template import srw
    from sirepo.template.srw import validate_magnet_data_file

    zip_dir = str(pkunit.data_dir() + '/zip_dir')

    # Reject a zip with no index file
    with pkunit.pkexcept(AssertionError):
        validate_safe_zip(zip_dir + '/bad_zip_no_index.zip', zip_dir, validate_magnet_data_file)

    # Reject a zip with an incomplete index file
    with pkunit.pkexcept(AssertionError):
        validate_safe_zip(zip_dir + '/bad_zip_incomplete_index.zip', zip_dir, validate_magnet_data_file)

    # Reject a zip with entries in index file that are not in zip
    with pkunit.pkexcept(AssertionError):
        validate_safe_zip(zip_dir + '/bad_zip_extra_index.zip', zip_dir, validate_magnet_data_file)

    # Reject a zip with unacceptable file types
    with pkunit.pkexcept(AssertionError):
        validate_safe_zip(zip_dir + '/bad_zip_bad_types.zip', zip_dir, validate_magnet_data_file)

    # Finally, make sure the included measurement files are OK
    # We're not really extracting them so just send the test directory as target
    validate_safe_zip(pkresource.filename('template/srw/magn_meas_chx.zip', srw), zip_dir, validate_magnet_data_file)
    validate_safe_zip(pkresource.filename('template/srw/magn_meas_esm.zip', srw), zip_dir, validate_magnet_data_file)
    validate_safe_zip(pkresource.filename('template/srw/magn_meas_fmx.zip', srw), zip_dir, validate_magnet_data_file)
    validate_safe_zip(pkresource.filename('template/srw/magn_meas_srx.zip', srw), zip_dir, validate_magnet_data_file)
    validate_safe_zip(pkresource.filename('template/srw/magn_meas_u20_hxn.zip', srw), zip_dir, validate_magnet_data_file)
    validate_safe_zip(pkresource.filename('template/srw/magnetic_measurements.zip', srw), zip_dir, validate_magnet_data_file)
コード例 #9
0
def test_login():
    from pykern import pkunit, pkcompat
    from pykern.pkunit import pkeq, pkok, pkre, pkfail, pkexcept
    from sirepo import auth
    import flask
    import sirepo.auth.guest
    import sirepo.cookie
    import sirepo.http_request
    import sirepo.util

    r = auth.api_authState()
    pkre('LoggedIn": false.*Registration": false', pkcompat.from_bytes(r.data))
    delattr(flask.g, 'sirepo_cookie')
    auth.process_request()
    with pkunit.pkexcept('SRException.*routeName=login'):
        auth.logged_in_user()
    with pkexcept('SRException.*routeName=login'):
        auth.require_user()
    sirepo.cookie.set_sentinel()
    # copying examples for new user takes time
    try:
        r = auth.login(sirepo.auth.guest, sim_type='myapp')
        pkfail('expecting sirepo.util.Response')
    except sirepo.util.Response as e:
        r = e.sr_args.response
    pkre(r'LoggedIn":\s*true.*Registration":\s*false',
         pkcompat.from_bytes(r.data))
    u = auth.logged_in_user()
    pkok(u, 'user should exist')
    # guests do not require completeRegistration
    auth.require_user()
コード例 #10
0
ファイル: cookie_test.py プロジェクト: e-carlin/sirepo
def test_1():
    import shutil
    from pykern import pkconfig, pkunit, pkio
    from pykern.pkunit import pkeq
    from pykern.pkdebug import pkdp
    from sirepo import srunit
    srunit.flask_client()

    from sirepo import cookie
    cookie.init_mock()
    cookie.init('x')
    with pkunit.pkexcept('Unauthorized'):
        cookie.get_user()
    with pkunit.pkexcept('Unauthorized'):
        cookie.get_user(checked=False)
    cookie.set_sentinel()
    cookie.set_user('abc')
    cookie.set_value('hi', 'hello')
    r = _Response(status_code=200)
    cookie.save_to_cookie(r)
    pkeq('sirepo_dev', r.args[0])
    pkeq(False, r.kwargs['secure'])
    pkeq('abc', cookie.get_user())
    cookie.clear_user()
    cookie.unchecked_remove('hi')
    pkeq(None, cookie.get_user(checked=False))
    cookie.init('sirepo_dev={}'.format(r.args[1]))
    pkeq('hello', cookie.get_value('hi'))
    pkeq('abc', cookie.get_user())
コード例 #11
0
def test_set_get():
    from pykern import pkunit, pkcompat
    from pykern.pkunit import pkeq
    from pykern.pkdebug import pkdp
    from sirepo import cookie

    with cookie.process_header('x'):
        with pkunit.pkexcept('KeyError'):
            cookie.get_value('hi1')
        with pkunit.pkexcept('AssertionError'):
            cookie.set_value('hi2', 'hello')
        pkeq(None, cookie.unchecked_get_value('hi3'))
コード例 #12
0
    def t():
        from pykern.pkdebug import pkdp
        from pykern.pkunit import pkeq, pkexcept, pkre
        from sirepo import uri_router
        import re

        fc = srunit.flask_client()
        uri = uri_router.uri_for_api('homePage')
        pkre('http://[^/]+/about$', uri)
        uri = uri_router.uri_for_api('homePage', external=False)
        pkre('^/about$', uri)
        with pkexcept(KeyError):
            uri_router.uri_for_api('notAnApi')
        with pkexcept('missing parameter'):
            uri_router.uri_for_api('exportArchive', {'simulation_type': 'srw'})
コード例 #13
0
def test_happy_path(monkeypatch):
    from pykern.pkdebug import pkdp
    from pykern import pkjson
    from pykern.pkunit import pkfail, pkok, pkeq, pkre, pkexcept

    fc, sim_type, oc = _fc(monkeypatch, 'happy')
    fc.sr_auth_state(isLoggedIn=False)
    r = fc.sr_get('authGithubLogin', {'simulation_type': sim_type},
                  redirect=False)
    pkeq(302, r.status_code)
    with pkexcept('SRException.*routeName=login'):
        d = fc.sr_post('listSimulations', {'simulationType': sim_type})
    state = oc.values.state
    pkre(state, r.headers['location'])
    fc.sr_auth_state(displayName=None,
                     isLoggedIn=False,
                     uid=None,
                     userName=None)
    r = fc.sr_get('authGithubAuthorized',
                  query={'state': state},
                  redirect=False)
    pkeq(302, r.status_code)
    pkre('complete-registration', r.headers['location'])
    with pkexcept('SRException.*routeName=completeRegistration'):
        fc.sr_post('listSimulations', {'simulationType': sim_type})
    fc.sr_post(
        'authCompleteRegistration',
        {
            'displayName': 'Happy Path',
            'simulationType': sim_type,
        },
    )
    s = fc.sr_auth_state(
        avatarUrl='https://avatars.githubusercontent.com/happy?size=40',
        displayName='Happy Path',
        isLoggedIn=True,
        userName='******',
    )
    uid = s.uid
    r = fc.sr_get('authLogout', {'simulation_type': sim_type}, redirect=False)
    pkre('/{}$'.format(sim_type), r.headers['Location'])
    fc.sr_auth_state(
        avatarUrl=None,
        displayName=None,
        isLoggedIn=False,
        uid=uid,
        userName=None,
    )
コード例 #14
0
def test_force_login(auth_fc):
    fc = auth_fc

    from pykern import pkcollections
    from pykern import pkconfig, pkunit, pkio
    from pykern.pkdebug import pkdp
    from pykern.pkunit import pkok, pkre, pkeq, pkexcept
    from sirepo import http_reply
    from sirepo import util

    # login as a new user, not in db
    r = fc.sr_post('authEmailLogin', {
        'email': '[email protected]',
        'simulationType': fc.sr_sim_type
    })
    fc.get(r.url)
    fc.sr_get('authLogout', {'simulation_type': fc.sr_sim_type})
    with pkexcept('SRException.*routeName.*login'):
        fc.sr_post('listSimulations', {'simulationType': fc.sr_sim_type})
    r = fc.sr_post('authEmailLogin', {
        'email': '[email protected]',
        'simulationType': fc.sr_sim_type
    })
    fc.sr_email_confirm(fc, r)
    fc.sr_post(
        'authCompleteRegistration',
        {
            'displayName': 'xyz',
            'simulationType': fc.sr_sim_type,
        },
    )
    d = fc.sr_post('listSimulations', {'simulationType': fc.sr_sim_type})
    pkeq(1, len(d))
コード例 #15
0
def test_warppba_invalid_creds(new_user_fc):
    from pykern.pkunit import pkexcept

    c, d = _warppba_login_setup(new_user_fc)
    with pkexcept('SRException.*no-creds'):
        new_user_fc.sr_run_sim(d, c, expect_completed=False)
    with pkexcept('SRException.*invalid-creds'):
        new_user_fc.sr_post(
            'sbatchLogin',
            PKDict(
                password='******',
                report=c,
                simulationId=d.models.simulation.simulationId,
                simulationType=d.simulationType,
                username='******',
            ))
コード例 #16
0
ファイル: guest1_test.py プロジェクト: ahebnl/Sirepo
def test_timeout(auth_fc):
    fc = auth_fc

    from pykern import pkconfig, pkunit, pkio
    from pykern import pkjson
    from pykern.pkdebug import pkdp
    from pykern.pkunit import pkok, pkre, pkeq, pkexcept
    import re

    r = fc.sr_get('authGuestLogin', {'simulation_type': fc.sr_sim_type}, redirect=False)
    pkeq(200, r.status_code)
    d = pkjson.load_any(r.data)
    pkeq(True, d.authState.isLoggedIn)
    fc.sr_post('listSimulations', {'simulationType': fc.sr_sim_type})
    fc.sr_auth_state(
        isGuestUser=True,
        isLoggedIn=True,
        isLoginExpired=False,
    )
    fc.sr_get_json('adjustTime', params={'days': '2'})
    fc.sr_auth_state(
        isGuestUser=True,
        isLoggedIn=True,
        isLoginExpired=True,
    )
    with pkexcept('SRException.*guest-expired'):
        fc.sr_post('listSimulations', {'simulationType': fc.sr_sim_type})
コード例 #17
0
ファイル: guest1_test.py プロジェクト: JiayangY/sirepo
def test_timeout(auth_fc):
    fc = auth_fc

    from pykern import pkconfig, pkunit, pkio
    from pykern.pkunit import pkok, pkre, pkeq, pkexcept
    from pykern.pkdebug import pkdp
    import re

    r = fc.sr_get('authGuestLogin', {'simulation_type': fc.sr_sim_type}, redirect=False)
    pkeq(302, r.status_code)
    pkre(fc.sr_sim_type, r.headers['location'])
    fc.sr_post('listSimulations', {'simulationType': fc.sr_sim_type})
    fc.sr_auth_state(
        isGuestUser=True,
        isLoggedIn=True,
        isLoginExpired=False,
    )
    fc.sr_get_json('adjustTime', params={'days': '2'})
    fc.sr_auth_state(
        isGuestUser=True,
        isLoggedIn=True,
        isLoginExpired=True,
    )
    with pkexcept('SRException.*guest-expired'):
        fc.sr_post('listSimulations', {'simulationType': fc.sr_sim_type})
コード例 #18
0
def test_auth_hash(monkeypatch):
    from pykern import pkconfig

    pkconfig.reset_state_for_testing({
        'SIREPO_AUTH_METHODS':
        'bluesky',
        'SIREPO_AUTH_BLUESKY_SECRET':
        'a simple string is fine',
        'SIREPO_FEATURE_CONFIG_SIM_TYPES':
        'srw:myapp',
    })
    from sirepo.auth import bluesky
    from pykern import pkcollections
    from pykern.pkunit import pkexcept, pkre
    import time
    import werkzeug.exceptions

    bluesky.init_apis()
    monkeypatch.setattr(bluesky, '_AUTH_NONCE_REPLAY_SECS', 1)
    req = pkcollections.Dict(
        simulationType='xyz',
        simulationId='1234',
    )
    bluesky.auth_hash(req)
    bluesky.auth_hash(req, verify=True)
    time.sleep(2)
    with pkexcept(werkzeug.exceptions.Unauthorized):
        bluesky.auth_hash(req, verify=True)
コード例 #19
0
def test_srw_missing_cookies(fc):
    from pykern.pkunit import pkeq, pkre, pkexcept
    from sirepo import srunit
    import json

    fc.cookie_jar.clear()
    with pkexcept('missingCookies'):
        fc.sr_post('/simulation-list', {'simulationType': fc.sr_sim_type})
コード例 #20
0
ファイル: simulation_db_test.py プロジェクト: mkeilman/sirepo
def _do(path, uid, expect=True):
    from pykern.pkunit import pkeq, pkexcept, pkre
    import sirepo.simulation_db

    if expect:
        with pkexcept(AssertionError):
            sirepo.simulation_db.validate_sim_db_file_path(path, uid)
    else:
        sirepo.simulation_db.validate_sim_db_file_path(path, uid)
コード例 #21
0
def test_elegant_server_upgraded(fc):
    from pykern.pkdebug import pkdp, pkdpretty
    from pykern.pkunit import pkexcept
    from pykern.pkcollections import PKDict

    d = fc.sr_sim_data('Backtracking')
    d.version = d.version[:-1] + str(int(d.version[-1]) - 1)
    with pkexcept('serverupgraded'):
        fc.sr_post('saveSimulationData', d)
コード例 #22
0
ファイル: uri_router_test.py プロジェクト: ahebnl/Sirepo
    def t():
        from pykern.pkdebug import pkdp
        from pykern.pkunit import pkeq, pkexcept, pkre, pkeq
        from sirepo import uri_router
        import re

        fc = srunit.flask_client()
        uri = uri_router.uri_for_api('homePage', params={'path_info': None})
        pkre('http://[^/]+/en$', uri)
        uri = uri_router.uri_for_api(
            'homePage',
            params={'path_info': 'terms.html'},
            external=False,
        )
        pkeq('/en/terms.html', uri)
        with pkexcept(KeyError):
            uri_router.uri_for_api('notAnApi')
        with pkexcept('missing parameter'):
            uri_router.uri_for_api('exportArchive', {'simulation_type': 'srw'})
コード例 #23
0
ファイル: srunit.py プロジェクト: JiayangY/sirepo
    def sr_sbatch_animation_run(self, sim_name, compute_model, reports, **kwargs):
        from pykern.pkunit import pkexcept

        d = self.sr_sim_data(sim_name)
        if not self.sr_sbatch_logged_in:
            with pkexcept('SRException.*no-creds'):
                # Must try to run sim first to seed job_supervisor.db
                self.sr_run_sim(d, compute_model, expect_completed=False)
            self.sr_sbatch_login(compute_model, d)
            self.sr_sbatch_logged_in = True
        self.sr_animation_run(sim_name, compute_model, reports, **kwargs)
コード例 #24
0
ファイル: auth_db_test.py プロジェクト: yeeon/sirepo
def test_migration():
    """See if user gets migrated"""
    from pykern.pkunit import pkeq, pkok, pkexcept, work_dir
    from pykern.pkdebug import pkdp
    from sirepo import auth

    # deprecated methods raise Unauthorized, but still login
    with pkexcept('UNAUTHORIZED'):
        auth.login(auth.github, uid='jeTJR5G4')
    # verify logged in
    pkeq('jeTJR5G4', auth.user_if_logged_in('github'))
    pkok(work_dir().join('db/auth.db').exists(), 'auth.db does not exist')
コード例 #25
0
def test_pkexcept():
    import re, inspect
    from pykern.pkunit import pkexcept, pkfail

    with pkexcept(KeyError, 'should see a KeyError'):
        {}['not found']
    with pkexcept('KeyError.*xyzzy'):
        {}['xyzzy']
    try:
        lineno = inspect.currentframe().f_lineno + 2
        with pkexcept(KeyError, 'xyzzy'):
            pass
    except AssertionError as e:
        assert 'xyzzy' in str(e.args)
        assert 'pkunit_test.py:{}:test_pkexcept'.format(lineno) in str(e.args)
    except Exception as e:
        pkfail('{}: got exception, but not AssertionError', e)
    else:
        pkfail('did not raise AssertionError')
    try:
        with pkexcept(KeyError):
            raise NameError('whatever')
    except AssertionError as e:
        assert re.search(r'exception was raised.*but expected.*KeyError',
                         str(e.args))
    except Exception as e:
        pkfail('{}: got exception, but not AssertionError', e)
    else:
        pkfail('did not raise AssertionError')
    try:
        lineno = inspect.currentframe().f_lineno + 2
        with pkexcept('any pattern'):
            pass
    except AssertionError as e:
        assert 'pkunit_test.py:{}:test_pkexcept'.format(lineno) in str(e.args)
        assert 'was not raised' in str(e.args)
    except Exception as e:
        pkfail('{}: got exception, but not AssertionError', e)
    else:
        pkfail('did not raise AssertionError')
コード例 #26
0
def test_dict():
    """Validate Dict()"""
    n = Dict()
    n.a = 1
    pkok(
        1 == n.a,
        'new attribute should work with x.y format',
    )
    pkok(
        1 == n['a'], \
        'x["y"] should retrieve 1',
    )
    n.a = 2
    pkok(
        2 == n.a,
        'overwrite attr',
    )
    with pkexcept(pkcollections.DictNameError):
        delattr(n, 'a')
    with pkexcept(pkcollections.DictNameError):
        setattr(n, 'keys', 3)
    expect = 'invalid key for Dict'
    with pkexcept(expect):
        setattr(n, '__getattr__', 3)
    with pkexcept(pkcollections.DictNameError):
        delattr(n, 'items')
    n = Dict(items=1)
    pkok(list(n.items()) == [('items', 1)], 'items() should be retrievable')
    n['items'] = ''
    del n['items']
    pkok(n.items() == [], 'items() should be deletabley')
    with pkexcept(AttributeError):
        n.missing_attribute()
    with pkexcept(KeyError):
        n['missing key']
コード例 #27
0
def test_dict():
    """Validate Dict()"""
    n = Dict()
    n.a = 1
    pkok(
        1 == n.a,
        'new attribute should work with x.y format',
    )
    pkok(
        1 == n['a'], \
        'x["y"] should retrieve 1',
    )
    n.a = 2
    pkok(
        2 == n.a,
        'overwrite attr',
    )
    with pkexcept(pkcollections.DictNameError):
        delattr(n, 'a')
    with pkexcept(pkcollections.DictNameError):
        setattr(n, 'keys', 3)
    expect = 'invalid key for Dict'
    with pkexcept(expect):
        setattr(n, '__getattr__', 3)
    with pkexcept(pkcollections.DictNameError):
        delattr(n, 'items')
    n = Dict(items=1)
    pkok(list(n.items()) == [('items', 1)], 'items() should be retrievable')
    n['items'] = ''
    del n['items']
    pkok(n.items() == [], 'items() should be deletabley')
    with pkexcept(AttributeError):
        n.missing_attribute()
    with pkexcept(KeyError):
        n['missing key']
コード例 #28
0
def test_init(pkconfig_setup):
    """Validate parse_set"""
    pkconfig = pkconfig_setup(
        cfg=dict(
            PYKERN_PKCONFIG_CHANNEL='alpha',
            P1_M1_SET3='',
            P1_M1_SET4='a:b',
        ),
        env=dict(P1_M1_REQ8='99', P1_M1_HOSTS='h1'),
    )
    from pykern import pkunit
    with pkunit.pkexcept('p1.m1.req10: config'):
        from p1.m1 import cfg
コード例 #29
0
def test_lock(monkeypatch):
    from pykern import pkunit
    import os
    
    def _create_lock(d, offset=0):
        lock_pid = (d + '.lock').join('pid')
        lock_pid.write(str(os.getpid() + offset), ensure=True)
        return None

    with pkunit.pkexcept('unable to create lock', 'should fail to create lock'):
        _move_all(monkeypatch, hook=_create_lock)

    _move_all(monkeypatch, hook=lambda x: _create_lock(x, 100000))
コード例 #30
0
ファイル: pkunit_test.py プロジェクト: elventear/pykern
def test_pkexcept():
    import re, inspect
    from pykern.pkunit import pkexcept, pkfail
    with pkexcept(KeyError, 'should see a KeyError'):
        {}['not found']
    with pkexcept('KeyError.*xyzzy'):
        {}['xyzzy']
    try:
        lineno = inspect.currentframe().f_lineno + 2
        with pkexcept(KeyError, 'xyzzy'):
            pass
    except AssertionError as e:
        assert 'xyzzy' in e.message
        assert 'pkunit_test.py:{}:test_pkexcept'.format(lineno) in e.message
    except Exception as e:
        pkfail('{}: got exception, but not AssertionError', e)
    else:
        pkfail('did not raise AssertionError')
    try:
        with pkexcept(KeyError):
            raise NameError('whatever')
    except AssertionError as e:
        assert re.search(r'exception was raised.*but expected.*KeyError', e.message)
    except Exception as e:
        pkfail('{}: got exception, but not AssertionError', e)
    else:
        pkfail('did not raise AssertionError')
    try:
        lineno = inspect.currentframe().f_lineno + 2
        with pkexcept('any pattern'):
            pass
    except AssertionError as e:
        assert 'pkunit_test.py:{}:test_pkexcept'.format(lineno) in e.message
        assert 'was not raised' in e.message
    except Exception as e:
        pkfail('{}: got exception, but not AssertionError', e)
    else:
        pkfail('did not raise AssertionError')
コード例 #31
0
ファイル: email2_test.py プロジェクト: JiayangY/sirepo
def test_oauth_conversion(auth_fc, monkeypatch):
    """See `x_test_oauth_conversion_setup`"""
    fc = auth_fc

    from pykern import pkcollections
    from pykern.pkdebug import pkdp
    from pykern.pkunit import pkok, pkre, pkeq, pkexcept, pkfail
    from pykern import pkunit
    from pykern import pkio
    from sirepo.auth import github
    from sirepo import github_srunit
    from sirepo import server
    import sirepo.util
    import shutil

    pkio.unchecked_remove(server._app.sirepo_db_dir)
    pkunit.data_dir().join('db').copy(server._app.sirepo_db_dir)
    fc.cookie_jar.clear()
    fc.set_cookie(
        'localhost', 'sirepo_dev',
        'Z0FBQUFBQmN2bGQzaGc1MmpCRkxIOWNpWi1yd1JReXUxZG5FV2VqMjFwU2w2cmdOSXhlaWVkOC1VUzVkLVR5NzdiS080R3p1aGUwUEFfdmpmdDcxTmJlOUR2eXpJY2l1YUVWaUVVa3dCYXpnZGIwTV9fei1iTWNCdkp0eXJVY0Ffenc2SVoxSUlLYVM='
    )
    oc = github_srunit.MockOAuthClient(monkeypatch, 'emailer')
    uid = fc.sr_auth_state(isLoggedIn=False, method='github').uid
    with pkexcept('SRException.*method.*github.*routeName=loginWith'):
        fc.sr_post('listSimulations', {'simulationType': fc.sr_sim_type})
    r = fc.sr_get('authGithubLogin', {'simulation_type': fc.sr_sim_type},
                  redirect=False)
    pkre(oc.values.state, r.headers['Location'])
    state = oc.values.state
    fc.sr_get('authGithubAuthorized', query={'state': state})
    r = fc.sr_post(
        'authEmailLogin',
        {
            'email': '*****@*****.**',
            'simulationType': fc.sr_sim_type
        },
    )
    fc.sr_auth_state(isLoggedIn=True, method='github', uid=uid)
    fc.sr_email_confirm(fc, r)
    fc.sr_auth_state(
        isLoggedIn=True,
        method='email',
        uid=uid,
        userName='******',
    )
コード例 #32
0
ファイル: auth_test.py プロジェクト: yeeon/sirepo
def test_login():
    from pykern import pkunit
    from pykern.pkdebug import pkdp
    from pykern.pkunit import pkeq, pkok, pkre
    from sirepo import auth
    import flask
    import sirepo.auth.guest
    import sirepo.cookie
    import sirepo.http_request

    r = auth.api_authState()
    pkre('LoggedIn": false.*Registration": false', r.data)
    delattr(flask.g, 'sirepo_cookie')
    auth.process_request()
    with pkunit.pkexcept('Unauthorized'):
        auth.logged_in_user()
    r = auth.require_user()
    pkeq(400, r.status_code, 'status should be BAD REQUEST')
    pkre('"routeName": "login"', r.data)
    sirepo.cookie.set_sentinel()
    # copying examples for new user takes time
    r = auth.login(sirepo.auth.guest)
    pkeq(None, r, 'user created')
    r = auth.api_authState()
    pkre('LoggedIn": true.*Registration": true', r.data)
    u = auth.logged_in_user()
    pkok(u, 'user should exist')
    r = auth.require_user()
    pkeq(400, r.status_code, 'status should be BAD REQUEST')
    pkre('"routeName": "completeRegistration"', r.data)
    flask.request = 'abcdef'

    def parse_json(*args, **kwargs):
        return pkcollections.Dict(simulationType='myapp',
                                  displayName='Joe Bob')

    setattr(sirepo.http_request, 'parse_json', parse_json)
    auth.api_authCompleteRegistration()
    r = auth.api_authState()
    pkre('Name": "Joe Bob".*In": true.*.*Registration": false', r.data)
コード例 #33
0
ファイル: bluesky_test.py プロジェクト: e-carlin/sirepo
def test_auth_hash(monkeypatch):
    from pykern import pkconfig

    pkconfig.reset_state_for_testing({
        'SIREPO_FEATURE_CONFIG_API_MODULES': 'bluesky',
        'SIREPO_BLUESKY_AUTH_SECRET': 'a simple string is fine',
    })
    from sirepo import bluesky
    from pykern import pkcollections
    from pykern.pkunit import pkexcept, pkre
    import time
    import werkzeug.exceptions

    monkeypatch.setattr(bluesky, '_AUTH_NONCE_REPLAY_SECS', 1)
    req = pkcollections.Dict(
        simulationType='xyz',
        simulationId='1234',
    )
    bluesky.auth_hash(req)
    bluesky.auth_hash(req, verify=True)
    time.sleep(2)
    with pkexcept(werkzeug.exceptions.NotFound):
        bluesky.auth_hash(req, verify=True)
コード例 #34
0
ファイル: bluesky_test.py プロジェクト: kalebswartz7/sirepo
def test_auth_hash(monkeypatch):
    from pykern import pkconfig

    pkconfig.reset_state_for_testing({
        'SIREPO_BLUESKY_AUTH_SECRET':
        'a simple string is fine',
    })
    from sirepo import bluesky
    from pykern import pkcollections
    from pykern.pkunit import pkexcept, pkre
    import time
    import werkzeug.exceptions

    monkeypatch.setattr(bluesky, '_AUTH_NONCE_REPLAY_SECS', 1)
    req = pkcollections.Dict(
        simulationType='xyz',
        simulationId='1234',
    )
    bluesky.auth_hash(req)
    bluesky.auth_hash(req, verify=True)
    time.sleep(2)
    with pkexcept(werkzeug.exceptions.NotFound):
        bluesky.auth_hash(req, verify=True)
コード例 #35
0
ファイル: admin_test.py プロジェクト: mkeilman/sirepo
def test_no_user():
    import sirepo.pkcli.admin
    from pykern import pkunit
    u = 'xxx'
    with pkunit.pkexcept('.*no registered user with uid=' + u):
        sirepo.pkcli.admin.delete_user(u)