示例#1
0
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
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()
示例#3
0
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})
示例#4
0
def _do(fc, file_ext, parse):
    from pykern.pkcollections import PKDict
    from pykern import pkio, pkcompat
    from pykern import pkunit
    from pykern import pkcollections
    from pykern.pkdebug import pkdp, pkdlog
    from pykern.pkunit import pkeq, pkfail, pkok, pkre
    import re

    for suffix in (('',) if file_ext == 'py' else ('', ' 2', ' 3')):
        for f in pkio.sorted_glob(pkunit.data_dir().join('*.' + file_ext)):
            pkdlog('file={}', f)
            json = pkcompat.from_bytes(parse(f))
            sim_type = re.search(r'^([a-z]+)_', f.basename).group(1)
            fc.sr_get_root(sim_type)
            is_dev = 'deviance' in f.basename
            res = fc.sr_post_form(
                'importFile',
                PKDict(folder='/importer_test'),
                PKDict(simulation_type=sim_type),
                file=f,
            )
            if is_dev:
                m = re.search(r'Error: (.+)', json)
                if m:
                    expect = m.group(1)
                    pkre(expect, res.error)
                continue
            elif file_ext == 'py':
                sim_name = f.purebasename
            else:
                sim_name = pkcollections.json_load_any(json).models.simulation.name
            assert 'models' in res, \
                f'file={f} res={res}'
            pkeq(sim_name + suffix, res.models.simulation.name)
示例#5
0
def test_elegant_data_file(fc):
    from pykern import pkio
    from pykern import pkunit
    from pykern.pkcollections import PKDict
    from pykern.pkdebug import pkdp
    import sdds

    data = fc.sr_sim_data('bunchComp - fourDipoleCSR')
    run = fc.sr_post(
        'runSimulation',
        PKDict(
            forceRun=False,
            models=data.models,
            report='bunchReport1',
            simulationId=data.models.simulation.simulationId,
            simulationType=data.simulationType,
        ),
    )
    pkunit.pkeq('pending', run.state, 'not pending, run={}', run)
    for _ in range(10):
        if run.state == 'completed':
            break
        run = fc.sr_post(
            'runStatus',
            run.nextRequest
        )
        time.sleep(1)
    else:
        pkunit.pkfail('runStatus: failed to complete: {}', run)
    resp = fc.sr_get(
        'downloadDataFile',
        PKDict(
            simulation_type=data.simulationType,
            simulation_id=data.models.simulation.simulationId,
            model='bunchReport1',
            frame='-1',
            suffix='csv',
        ),
    )
    pkunit.pkre('no-cache', resp.headers['Cache-Control'])
    rows = csv.reader(StringIO.StringIO(resp.get_data()))
    pkunit.pkeq(50001, len(list(rows)), '50,000 particles plus header row')
    resp = fc.sr_get(
        'downloadDataFile',
        PKDict(
            simulation_type=data.simulationType,
            simulation_id=data.models.simulation.simulationId,
            model='bunchReport1',
            frame='-1',
        ),
    )
    m = re.search(r'attachment; filename="([^"]+)"', resp.headers['Content-Disposition'])
    d = pkunit.work_dir()
    path = d.join(m.group(1))
    path.write_binary(resp.get_data())
    assert sdds.sddsdata.InitializeInput(0, str(path)) == 1, \
        '{}: sdds failed to open'.format(path)
    # Verify we can read something
    assert 0 <= len(sdds.sddsdata.GetColumnNames(0))
    sdds.sddsdata.Terminate(0)
示例#6
0
def test_srw_validate_file(fc):
    from pykern import pkunit
    from pykern.pkcollections import PKDict
    from pykern.pkdebug import pkdp
    from pykern.pkunit import pkre, pkeq
    import sirepo.sim_data

    d = fc.sr_sim_data('Sample from Image')
    s = sirepo.sim_data.get_class(fc.sr_sim_type)
    r = fc.sr_get(
        'downloadFile',
        params=PKDict(
            simulation_type=fc.sr_sim_type,
            simulation_id=d.models.simulation.simulationId,
            filename='sample.tif',
        ),
        data=PKDict(),
        redirect=False,
    )
    pkre('/tif', r.mimetype)
    f = s.lib_file_resource_dir().join('sample.tif')
    r = fc.sr_post_form(
        'uploadFile',
        params=PKDict(
            simulation_type=fc.sr_sim_type,
            simulation_id=d.models.simulation.simulationId,
            file_type='sample',
        ),
        data=PKDict(confirm='1'),
        file=f,
    )
    pkeq('sample.tif', r.filename)
    pkeq('sample', r.fileType)
    pkeq(d.models.simulation.simulationId, r.simulationId)
示例#7
0
def test_follow_email_auth_link_twice(auth_fc):
    fc = auth_fc

    from pykern import pkconfig, pkunit, pkio
    from pykern.pkunit import pkok, pkre
    from pykern.pkdebug import pkdp
    import json

    r = fc.sr_post(
        'authEmailLogin',
        {
            'email': '[email protected]',
            'simulationType': fc.sr_sim_type
        },
    )
    # The link comes back in dev mode so we don't have to check email
    s = fc.sr_auth_state(isLoggedIn=False)
    fc.get(r.url)
    # get the url twice - should still be logged in
    d = fc.sr_get(r.url)
    assert not re.search(r'login-fail', d.data)
    fc.sr_email_confirm(fc, r)
    fc.sr_get('authLogout', {'simulation_type': fc.sr_sim_type})
    # now logged out, should see login fail for bad link
    pkre('login-fail', fc.get(r.url).data)
示例#8
0
def test_myapp_basic(fc):
    from pykern import pkunit

    resp = fc.get('/old')
    assert 'LandingPageController' in resp.get_data(), \
        'Top level document is the landing page'
    resp = fc.get('/robots.txt')
    pkunit.pkre('elegant.*myapp.*srw', resp.get_data())
示例#9
0
def test_myapp_basic(fc):
    from pykern import pkunit, pkcompat

    r = fc.get('/old')
    assert 'LandingPageController' in pkcompat.from_bytes(r.data), \
        'Top level document is the landing page'
    r = fc.get('/robots.txt')
    pkunit.pkre('elegant.*myapp.*srw', pkcompat.from_bytes(r.data))
示例#10
0
def test_myapp_basic(fc):
    from pykern import pkunit, pkcompat
    from pykern.pkunit import pkok, pkeq

    r = fc.sr_get('/robots.txt')
    pkunit.pkre('elegant.*myapp.*srw', pkcompat.from_bytes(r.data))
    r = fc.sr_get('/')
    pkok(not re.search(r'googletag', pkcompat.from_bytes(r.data)),
         'Unexpected injection of googletag data={}', r.data)
示例#11
0
def test_basic():
    from sirepo import srunit
    from pykern import pkunit
    fc = srunit.flask_client(sim_types='elegant:srw:myapp')
    resp = fc.get('/old')
    assert 'LandingPageController' in resp.get_data(), \
        'Top level document is the landing page'
    resp = fc.get('/robots.txt')
    pkunit.pkre('elegant.*myapp.*srw', resp.get_data())
示例#12
0
def test_missing_cookies():
    from pykern.pkunit import pkeq, pkre
    from sirepo import srunit
    import json
    fc = srunit.flask_client(sim_types='srw:myapp')
    sim_type = 'srw'
    resp = fc.post('/simulation-list',
                   data=json.dumps({'simulationType': sim_type}),
                   content_type='application/json')
    pkeq(400, resp.status_code)
    pkre('missingCookies', resp.data)
示例#13
0
def test_srw(fc):
    from pykern import pkio
    from pykern.pkdebug import pkdpretty
    from pykern.pkunit import pkeq, pkre
    import json

    r = fc.sr_get_root()
    pkre('<!DOCTYPE html', r.data)
    d = fc.sr_post('listSimulations', {'simulationType': fc.sr_sim_type})
    pkeq(fc.get('/find-by-name-auth/srw/default/UndulatorRadiation').status_code, 404)
    for sep in (' ', '%20', '+'):
        pkeq(fc.get('/find-by-name-auth/srw/default/Undulator{}Radiation'.format(sep)).status_code, 200)
示例#14
0
def test_deprecated():
    fc, sim_type = _fc(guest_deprecated=True)

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

    r = fc.sr_get('authGuestLogin', {'simulation_type': sim_type},
                  redirect=False)
    pkeq(302, r.status_code)
    pkre('guest/deprecated', r.data)
示例#15
0
def test_elegant(fc):
    from pykern.pkcollections import PKDict
    from pykern import pkunit

    r = fc.sr_post(
        'getApplicationData',
        PKDict(
            simulationType='elegant',
            method='get_beam_input_type',
            input_file='bunchFile-sourceFile.forward-beam-output.sdds',
        ),
    )
    pkunit.pkre('elegant', r.input_type)
示例#16
0
def test_injection(fc):
    from pykern import pkcompat, pkunit
    from pykern.pkdebug import pkdc, pkdp, pkdlog
    from pykern.pkunit import pkeq, pkok, pkre
    import re

    # test non-static page
    r = fc.get('myapp')
    pkok(not re.search(r'googletag', pkcompat.from_bytes(r.data)),
         'Unexpected injection of googletag data={}', r.data)

    # test successful injection
    r = fc.get('/en/landing.html')
    pkre(_TEST_ID, pkcompat.from_bytes(r.data))
示例#17
0
def test_synergia(fc):
    from pykern.pkcollections import PKDict
    from pykern.pkdebug import pkdp, pkdlog
    from pykern.pkunit import pkre
    import sirepo.sim_data
    import time

    data = fc.sr_sim_data('IOTA 6-6 with NL Element')
    cancel = None
    # this provokes an 'invalid data error'
    #    data.models.simulationSettings.space_charge = '2d-bassetti_erskine'
    s = sirepo.sim_data.get_class(fc.sr_sim_type)
    try:
        r = fc.sr_post(
            'runSimulation',
            PKDict(
                forceRun=True,
                models=data.models,
                report='animation',
                simulationId=data.models.simulation.simulationId,
                simulationType=data.simulationType,
            ),
        )
        cancel = r.nextRequest
        for _ in range(100):
            if r.state in ('completed', 'error'):
                pkdlog(r.state)
                cancel = None
                break
            r = fc.sr_post('runStatus', r.nextRequest)
            if r.frameCount > 0:
                for i in range(r.frameCount, r.frameCount - 5, -1):
                    f = fc.sr_get_json(
                        'simulationFrame',
                        PKDict(frame_id=s.frame_id(
                            data, r, 'beamEvolutionAnimation', r.frameCount -
                            i)),
                    )
                    if f.get('error'):
                        pkdlog(f.error)
                        pkre('not generated', f.error)
                        # cannot guarantee this happens, but exit if it does
                        break
            time.sleep(0.1)
    finally:
        try:
            if cancel:
                fc.sr_post('runCancel', cancel)
        except Exception:
            pass
示例#18
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'})
示例#19
0
    def sr_animation_run(self,
                         sim_name,
                         compute_model,
                         reports=None,
                         **kwargs):
        from pykern import pkunit
        from pykern.pkcollections import PKDict
        from pykern.pkdebug import pkdp, pkdlog
        import re

        data = self.sr_sim_data(sim_name)
        run = self.sr_run_sim(data, compute_model, **kwargs)
        for r, a in reports.items():
            if 'runSimulation' in a:
                f = self.sr_run_sim(data, r)
                for k, v in a.items():
                    m = re.search('^expect_(.+)', k)
                    if m:
                        pkunit.pkre(
                            v(i) if callable(v) else v,
                            str(f.get(m.group(1))),
                        )
                continue
            if 'frame_index' in a:
                c = [a.get('frame_index')]
            else:
                c = range(run.get(a.get('frame_count_key', 'frameCount')))
                assert c, \
                    'frame_count_key={} or frameCount={} is zero'.format(
                        a.get('frame_count_key'), a.get('frameCount'),
                    )
            pkdlog('frameReport={} count={}', r, c)
            import sirepo.sim_data

            s = sirepo.sim_data.get_class(self.sr_sim_type)
            for i in c:
                pkdlog('frameIndex={} frameCount={}', i, run.get('frameCount'))
                f = self.sr_get_json(
                    'simulationFrame',
                    PKDict(frame_id=s.frame_id(data, run, r, i)),
                )
                for k, v in a.items():
                    m = re.search('^expect_(.+)', k)
                    if m:
                        pkunit.pkre(
                            v(i) if callable(v) else v,
                            str(f.get(m.group(1))),
                        )
示例#20
0
def test_oauth_conversion(monkeypatch):
    """See `x_test_oauth_conversion_setup`"""
    fc, sim_type = _fc()

    from pykern import pkcollections
    from pykern.pkdebug import pkdp
    from pykern.pkunit import pkok, pkre, pkeq
    from pykern import pkunit
    from pykern import pkio
    from sirepo.auth import github
    from sirepo import github_srunit
    from sirepo import server
    import re
    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
    r = fc.sr_post('listSimulations', {'simulationType': sim_type})
    pkeq('loginWith', r.srException.routeName)
    pkeq('github', r.srException.params.method)
    r = fc.sr_get('authGithubLogin', {'simulation_type': sim_type})
    state = oc.values.state
    pkeq(302, r.status_code)
    pkre(state, r.headers['location'])
    fc.sr_get('authGithubAuthorized', query={'state': state})
    r = fc.sr_post(
        'authEmailLogin',
        {
            'email': '*****@*****.**',
            'simulationType': sim_type
        },
    )
    fc.sr_auth_state(isLoggedIn=True, method='github', uid=uid)
    fc.get(r.url)
    fc.sr_auth_state(
        isLoggedIn=True,
        method='email',
        uid=uid,
        userName='******',
    )
示例#21
0
def test_token_reuse(auth_fc):
    fc = auth_fc

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

    r = fc.sr_post(
        'authEmailLogin',
        {'email': '[email protected]', 'simulationType': fc.sr_sim_type},
    )
    fc.sr_email_confirm(fc, r)
    s = fc.sr_auth_state(userName='******')
    fc.sr_get('authLogout', {'simulation_type': fc.sr_sim_type})
    r = fc.sr_get(r.url, redirect=False)
    pkre('/login-fail/email', r.headers['Location'])
    fc.sr_auth_state(isLoggedIn=False)
示例#22
0
def test_myapp_user_dir_deleted(fc):
    from pykern import pkunit
    from pykern.pkcollections import PKDict
    from pykern.pkdebug import pkdp
    import sirepo.srdb

    sirepo.srdb.root().join(
        'user',
        fc.sr_auth_state().uid,
    ).remove(rec=1)
    r = fc.sr_post(
        'listSimulations',
        PKDict(simulationType=fc.sr_sim_type),
        raw_response=True,
    )
    pkunit.pkre('^<!DOCTYPE html.*APP_NAME:', r.data)
    fc.sr_auth_state(displayName=None, isLoggedIn=False, method=None)
示例#23
0
def test_illegals(fc):
    from pykern.pkcollections import PKDict
    from pykern.pkdebug import pkdp
    from pykern.pkunit import pkeq, pkexcept, pkre
    import copy

    d = fc.sr_sim_data()
    for x in (
        (PKDict(name='new/sim'), 'illegal character'),
        (PKDict(name='some*sim'), 'illegal character'),
        (PKDict(folder='.foo'), 'with a dot'),
        (PKDict(folder=''), 'blank folder'),
        (PKDict(name=''), 'blank name'),
    ):
        c = d.copy().pkupdate(folder='folder', name='name')
        r = fc.sr_post('newSimulation', c.pkupdate(x[0]))
        pkre(x[1], r.error)
示例#24
0
def test_different_email():
    fc, sim_type = _fc()

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

    r = fc.sr_post(
        'authEmailLogin',
        {
            'email': '[email protected]',
            'simulationType': sim_type
        },
    )
    s = fc.sr_auth_state(isLoggedIn=False)
    fc.get(r.url)
    s = fc.sr_auth_state(isLoggedIn=True, needCompleteRegistration=True)
    fc.sr_post(
        'authCompleteRegistration',
        {
            'displayName': 'abc',
            'simulationType': sim_type,
        },
    )
    t = fc.sr_auth_state(userName='******', displayName='abc')
    r = fc.sr_get('authLogout', {'simulation_type': sim_type})
    pkre('/{}$'.format(sim_type), r.headers['Location'])
    uid = fc.sr_auth_state(userName=None, isLoggedIn=False).uid
    r = fc.sr_post('authEmailLogin', {
        'email': '[email protected]',
        'simulationType': sim_type
    })
    fc.get(r.url)
    fc.sr_post(
        'authCompleteRegistration',
        {
            'displayName': 'xyz',
            'simulationType': sim_type,
        },
    )
    uid2 = fc.sr_auth_state(displayName='xyz',
                            isLoggedIn=True,
                            userName='******').uid
    pkok(uid != uid2, 'did not get a new uid={}', uid)
示例#25
0
    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'})
示例#26
0
def test_srw():
    from pykern import pkio
    from pykern.pkdebug import pkdpretty
    from pykern.pkunit import pkeq, pkre
    from sirepo import srunit
    import json

    fc = srunit.flask_client(sim_types='elegant:srw:myapp')
    sim_type = 'srw'
    r = fc.sr_get_root(sim_type)
    pkre('<!DOCTYPE html', r.data)
    fc.sr_login_as_guest(sim_type)
    d = fc.sr_post('listSimulations', {'simulationType': sim_type})
    pkeq(
        fc.get('/find-by-name/srw/default/UndulatorRadiation').status_code,
        404)
    for sep in (' ', '%20', '+'):
        pkeq(
            fc.get('/find-by-name/srw/default/Undulator{}Radiation'.format(
                sep)).status_code, 200)
示例#27
0
def test_add_code():
    from pykern import pkio
    from pykern import pkjson
    from pykern import pkunit
    from pykern.pkunit import pkok, pkeq, pkre
    from pykern.pkdebug import pkdp
    from pykern.pkcli import rsmanifest
    import re

    with pkunit.save_chdir_work(is_pkunit_prefix=True) as d:
        rsmanifest.add_code('A', 'b', 'c', 'd', pyenv='v')
        j = pkjson.load_any(pkio.py_path(rsmanifest.USER_FILE).read())
        pkok(20170101.0  < float(j.version), 'version must be after 2017')
        pkeq('A', j.codes.v.a.name)
        pkeq('b', j.codes.v.a.version)
        rsmanifest.add_code('a', 'bb', 'cc', 'dd')
        j = pkjson.load_any(pkio.expand_user_path(rsmanifest.USER_FILE).read())
        pkeq('A', j.codes.v.a.name)
        pkeq('a', j.codes[''].a.name)
        pkeq('bb', j.codes[''].a.version)
        pkre('20.*T.*Z', j.codes[''].a.installed)
示例#28
0
def test_add_code():
    from pykern import pkio
    from pykern import pkjson
    from pykern import pkunit
    from pykern.pkunit import pkok, pkeq, pkre
    from pykern.pkdebug import pkdp
    from pykern.pkcli import rsmanifest
    import re

    with pkunit.save_chdir_work(is_pkunit_prefix=True) as d:
        rsmanifest.add_code('A', 'b', 'c', 'd', pyenv='v')
        j = pkjson.load_any(pkio.py_path(rsmanifest.USER_FILE).read())
        pkok(20170101.0 < float(j.version), 'version must be after 2017')
        pkeq('A', j.codes.v.a.name)
        pkeq('b', j.codes.v.a.version)
        rsmanifest.add_code('a', 'bb', 'cc', 'dd')
        j = pkjson.load_any(pkio.expand_user_path(rsmanifest.USER_FILE).read())
        pkeq('A', j.codes.v.a.name)
        pkeq('a', j.codes[''].a.name)
        pkeq('bb', j.codes[''].a.version)
        pkre('20.*T.*Z', j.codes[''].a.installed)
示例#29
0
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.srdb
    import sirepo.util
    import shutil

    pkio.unchecked_remove(sirepo.srdb.root())
    pkunit.data_dir().join('db').copy(sirepo.srdb.root())
    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='******',
    )
示例#30
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)
示例#31
0
def test_happy_path():
    fc, sim_type = _fc()

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

    # login as a new user, not in db
    r = fc.sr_post('authEmailLogin', {
        'email': '[email protected]',
        'simulationType': sim_type
    })
    fc.get(r.url)
    fc.sr_post(
        'authCompleteRegistration',
        {
            'displayName': 'abc',
            'simulationType': sim_type,
        },
    )
    fc.sr_post('listSimulations', {'simulationType': sim_type})
    uid = fc.sr_auth_state(
        avatarUrl=
        'https://www.gravatar.com/avatar/5d60d4e28066df254d5452f92c910092?d=mp&s=40',
        displayName='abc',
        isLoggedIn=True,
        userName='******',
    ).uid
    r = fc.sr_get('authLogout', {'simulation_type': sim_type})
    pkre('/{}$'.format(sim_type), r.headers['Location'])
    fc.sr_auth_state(
        displayName=None,
        isLoggedIn=False,
        needCompleteRegistration=False,
        uid=uid,
        userName=None,
    )