Esempio n. 1
0
def test_assert_object_with_json():
    from pykern import pkunit

    pkunit.empty_work_dir()
    pkunit.assert_object_with_json('assert1', {'a': 1})
    with pytest.raises(AssertionError):
        pkunit.assert_object_with_json('assert1', {'b': 1})
Esempio n. 2
0
def test_save_chdir():
    from pykern import pkunit
    from pykern import pkio

    expect_prev = py.path.local().realpath()
    expect_new = py.path.local('..').realpath()
    try:
        with pkio.save_chdir(expect_new) as new:
            assert expect_new == new, \
                'save_chdir returns current directory before chdir'
            assert expect_new == py.path.local().realpath(), \
                'When in save_chdir, expect current directory to be new directory'
            os.chdir('..')
            assert expect_new != py.path.local().realpath(), \
                'When in save_chdir, expect chdir to still work'
            raise IndentationError()
    except IndentationError as benign_exception:
        pass
    assert expect_prev == py.path.local().realpath(), \
        'When exception is raised, current directory should be reverted.'
    expect_new = pkunit.empty_work_dir().join('new_folder').realpath()
    with pytest.raises(OSError):
        with pkio.save_chdir(expect_new) as new:
            assert False, \
                'When save_chdir given non-existent dir, should throw exception'
    with pkio.save_chdir(expect_new, mkdir=True) as new:
        assert expect_new == py.path.local().realpath(), \
            'When save_chdir given non-existent dir and mkdir=True, should pass'
Esempio n. 3
0
    def t():
        from sirepo.template import srw
        from pykern import pkcollections

        # Needed to initialize simulation_db
        data = pkcollections.json_load_any('''{
            "models": {
                "simulation": {
                    "sourceType": "t"
                },
                "tabulatedUndulator": {
                    "magneticFile": "magnetic_measurements.zip",
                    "indexFile": "",
                    "magnMeasFolder": ""
                },
                "beamline": { }
            },
            "report": "intensityReport"
        }''')
        d = pkunit.empty_work_dir()
        srw.prepare_aux_files(d, data)
        tu = data.models.tabulatedUndulator
        assert tu.magnMeasFolder == './'
        assert tu.indexFileName == 'ivu21_srx_sum.txt'
        assert d.join(tu.indexFileName).exists()
Esempio n. 4
0
def test_srw_create_predefined():
    from pykern import pkunit
    from pykern import pkjson
    import sirepo.pkcli.srw

    d = pkunit.empty_work_dir()
    sirepo.pkcli.srw.create_predefined(d)
    j = pkjson.load_any(d.listdir()[0])
    pkunit.pkeq(22, len(j.beams))
Esempio n. 5
0
def test_empty_work_dir():
    expect = _expect('pkunit_work')
    if os.path.exists(str(expect)):
        expect.remove(rec=1)
    assert not os.path.exists(str(expect)), \
        'Ensure directory was removed'
    d = pkunit.empty_work_dir()
    assert isinstance(d, PY_PATH_LOCAL_TYPE), \
        'Verify type of empty_work_dir is same as returned by py.path.local'
    assert expect == d, \
        'Verify empty_work_dir has correct return value'
    assert os.path.exists(str(d)), \
        'Ensure directory was created'
Esempio n. 6
0
def test_write_text():
    """Also tests read_text"""
    d = pkunit.empty_work_dir()
    expect_res = d.join('anything')
    expect_content = 'something'
    res = pkio.write_text(str(expect_res), expect_content)
    assert expect_res == res, \
        'Verify result is file path as py.path.Local'
    with open(str(expect_res)) as f:
        assert expect_content == f.read(), \
            'When write_text is called, it should write "something"'
    assert expect_content == pkio.read_text(str(expect_res)), \
        'When read_text, it should read "something"'
Esempio n. 7
0
def test_empty_work_dir():
    expect = _expect('pkunit_work')
    if os.path.exists(str(expect)):
        expect.remove(rec=1)
    assert not os.path.exists(str(expect)), \
        'Ensure directory was removed'
    d = pkunit.empty_work_dir()
    assert isinstance(d, PY_PATH_LOCAL_TYPE), \
        'Verify type of empty_work_dir is same as returned by py.path.local'
    assert expect == d, \
        'Verify empty_work_dir has correct return value'
    assert os.path.exists(str(d)), \
        'Ensure directory was created'
Esempio n. 8
0
def test_write_text():
    """Also tests read_text"""
    from pykern import pkunit
    from pykern import pkio

    d = pkunit.empty_work_dir()
    expect_res = d.join('anything')
    expect_content = 'something'
    res = pkio.write_text(str(expect_res), expect_content)
    assert expect_res == res, \
        'Verify result is file path as py.path.Local'
    with open(str(expect_res)) as f:
        assert expect_content == f.read(), \
            'When write_text is called, it should write "something"'
    assert expect_content == pkio.read_text(str(expect_res)), \
        'When read_text, it should read "something"'
Esempio n. 9
0
def _files():
    """Return dict of file args in data and work directories"""
    d = pkunit.data_dir()
    w = pkunit.empty_work_dir()

    existing_filename = w.join('exists.txt')
    with existing_filename.open('w'):
        pass

    return {
        'existing': existing_filename,
        'ini': d.join('rslinac.ini'),
        'input': d.join('input.txt'),
        'output': w.join('output.txt'),
        'not found': w.join('guaranteed not to exist'),
    }
Esempio n. 10
0
def test_init(capsys):
    from pykern import pkunit
    f = pkunit.empty_work_dir().join('f1')
    from pykern.pkdebug import pkdp, init
    init(output=f)
    pkdp('init1')
    out, err = capsys.readouterr()
    assert '' == err, \
        'When output is a file name, nothing goes to err'
    from pykern import pkio
    assert 'init1\n' in pkio.read_text(f), \
        'File output should contain msg'
    init(output=None, want_pid_time=True)
    pkdp('init2')
    out, err = capsys.readouterr()
    assert re.search(r'\w{3} .\d \d\d:\d\d:\d\d +\d+ +\d+ ', err), \
        'When output has time, matches regex'
Esempio n. 11
0
 def t():
     from sirepo.template import srw
     # Needed to initialize simulation_db
     data = {
         'models': {
             'simulation': {
                 'sourceType': 't'
             },
             'tabulatedUndulator': {
                 'magneticFile': 'magnetic_measurements.zip',
                 'indexFile': '',
                 'magnMeasFolder': '',
             },
             'beamline': { },
         },
     }
     srw.prepare_aux_files(pkunit.empty_work_dir(), data)
     assert data['models']['tabulatedUndulator']['magnMeasFolder'] == './'
     assert data['models']['tabulatedUndulator']['indexFile'] == 'ivu21_srx_sum.txt'
Esempio n. 12
0
 def t():
     from sirepo.template import srw
     # Needed to initialize simulation_db
     data = {
         'models': {
             'simulation': {
                 'sourceType': 't'
             },
             'tabulatedUndulator': {
                 'magneticFile': 'magnetic_measurements.zip',
                 'indexFile': '',
                 'magnMeasFolder': '',
             },
             'beamline': {},
         },
     }
     srw.prepare_aux_files(pkunit.empty_work_dir(), data)
     assert data['models']['tabulatedUndulator']['magnMeasFolder'] == './'
     assert data['models']['tabulatedUndulator'][
         'indexFile'] == 'ivu21_srx_sum.txt'
Esempio n. 13
0
def _project_dir(project):
    """Copy "data_dir/project" to "work_dir/project"

    Initializes as a git repo.

    Args:
        project (str): subdirectory name

    Returns:
        py.path.local: working directory"""
    d = pkunit.empty_work_dir().join(project)
    pkunit.data_dir().join(d.basename).copy(d)
    with pkio.save_chdir(d):
        check_call(['git', 'init', '.'])
        check_call(['git', 'config', 'user.email', '*****@*****.**'])
        check_call(['git', 'config', 'user.name', 'pykern'])
        check_call(['git', 'add', '.'])
        # Need a commit
        check_call(['git', 'commit', '-m', 'n/a'])
        yield d
Esempio n. 14
0
def _project_dir(project):
    """Copy "data_dir/project" to "work_dir/project"

    Initializes as a git repo.

    Args:
        project (str): subdirectory name

    Returns:
        py.path.local: working directory"""
    d = pkunit.empty_work_dir().join(project)
    pkunit.data_dir().join(d.basename).copy(d)
    with pkio.save_chdir(d):
        check_call(['git', 'init', '.'])
        check_call(['git', 'config', 'user.email', '*****@*****.**'])
        check_call(['git', 'config', 'user.name', 'pykern'])
        check_call(['git', 'add', '.'])
        # Need a commit
        check_call(['git', 'commit', '-m', 'n/a'])
        yield d
Esempio n. 15
0
    def t():
        from sirepo.template import template_common
        from pykern import pkcollections

        # Needed to initialize simulation_db
        data = pkcollections.json_load_any('''{
            "simulationType": "srw",
            "models": {
                "simulation": {
                    "sourceType": "t"
                },
                "tabulatedUndulator": {
                    "undulatorType": "u_t",
                    "magneticFile": "magnetic_measurements.zip"
                },
                "beamline": { }
            },
            "report": "intensityReport"
        }''')
        d = pkunit.empty_work_dir()
        template_common.copy_lib_files(data, None, d)
Esempio n. 16
0
def test_assert_object_with_json():
    pkunit.empty_work_dir()
    pkunit.assert_object_with_json('assert1', {'a': 1})
    with pytest.raises(AssertionError):
        pkunit.assert_object_with_json('assert1', {'b': 1})