test_pvs2pd.py 2.76 KB
Newer Older
1 2
#!/usr/bin/env python
# -*- coding: utf-8 -*-
3 4 5
"""
Unit tests for cassandra.pd
"""
6 7 8 9
# :title: Unittests for calc_phasespaces.py
# :lastupdate: 2016-09-15
import datetime
import doctest
10
import json
11
import sys
12
import unittest
13
from typing import List, NamedTuple
14 15

import cassandra
16
import pytest
17
from cassandra.pd import pvs2pd
18

19 20 21 22 23 24 25 26 27
try:
    import pathlib
except ImportError:
    pass
try:
    from urllib import request
except ImportError:
    import urllib2 as request

28
setup = NamedTuple("setup", [
29 30 31 32 33
    ("start", datetime.datetime),
    ("end", datetime.datetime),
    ("pv_list", List[str]),
])

34

35
class TestCassandraPD(object):
36

37
    @pytest.fixture()
38
    def setup_pd(self) -> setup:
39
        """Return `start` and `end` times and a list of PVs"""
40 41
        pv_list = ["nu_x", "nu_y"]
        start = datetime.datetime(2016, 8, 5, 18, 28, 36)
42
        end = datetime.datetime(2016, 8, 5, 18, 28, 36) + datetime.timedelta(seconds=15)
43
        # setup = namedtuple("setup", ["start", "end", "pv_list"])
44
        return setup(start, end, pv_list)
45

46 47
    @staticmethod
    def urlopen_nus(url: str, *args, **kwargs):
48
        """Return a filehandler with the JSON file of a tune readback for X and Y tune"""
49 50 51 52 53 54
        if "A:SR:BBB:01:Y:SRAM:PEAKTUNE2" in url:
            plane = "Y"
        elif "" in url:
            plane = "X"
        else:
            raise ValueError("Mocking failed!")
55 56 57
        return (pathlib.Path(__file__).parent /
                "data/A:SR:BBB:01:{plane}:SRAM:PEAKTUNE2_18:28:36_18:28:51_None.json".format(
                    plane=plane)).open("rb")
58

59
    @pytest.mark.skipif(sys.version_info < (3, 4), reason="requires python3.4")
60
    def test_pvs2pd(self, monkeypatch, setup_pd, cleandir, shared_datadir):
61 62 63
        monkeypatch.setattr(request, "urlopen", self.urlopen_nus)
        ret = pvs2pd(*setup_pd)
        assert [0.81171229137420042, 0.72489568710029628] == list(ret.mean())
64

65 66
        ret = pvs2pd(*setup_pd, upsample="ms")
        assert [0.81168935758343974, 0.72495481466421241] == list(ret.mean())
67

68 69 70
        with pytest.raises(ValueError):
            pvs2pd(*setup_pd, upsample=True)

71 72
        fn_in = "A:SR:BBB:01:X:SRAM:PEAKTUNE2_18:28:36_18:28:51_None.json"
        fn = "A:SR:BBB:01:X:SRAM:PEAKTUNE2_2016-08-05T18:28:36_2016-08-05T18:28:51_None.json"
73 74
        assert not pathlib.Path(cleandir / fn).is_file()
        pvs2pd(*setup_pd, save_local=True)
75 76
        with open(str(cleandir / fn), "r") as got, \
                open((shared_datadir / fn_in).absolute(), "r", ) as expected:
77
            assert json.load(expected) == json.load(got)
78 79 80


if __name__ == "__main__":
81
    # unittest.main()d
82 83 84 85 86
    testSuite = unittest.TestSuite()
    testSuite.addTest(doctest.DocTestSuite(cassandra.cassandra))
    unittest.TextTestRunner(verbosity=2).run(testSuite)

# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4