def test_callback(): p1 = Parameter('test_parameter', 1.0, min_value=-5.0, max_value=5.0, delta=0.2, desc='test', free=False, unit='MeV') class Callback(object): def __init__(self): self._control_value = None def __call__(self, p): assert p == p1 self._control_value = p1.value working_callback = Callback() p1.add_callback(working_callback) # Test the callback p1.value = 2.0 assert working_callback._control_value == p1.value def not_working_callback(): # Wrong calling sequence pass p1.add_callback(not_working_callback) # This should work because we do not change the parameter, so the callback # does not get called p1.value = 2.0 # This should instead raise because we do change the value with pytest.raises(NotCallableOrErrorInCall): p1.value = 3.0 p1.empty_callbacks() assert len(p1._callbacks) == 0
def test_pickle(): from astromodels.core.cpickle_compatibility_layer import cPickle p_orig = Parameter('test_parameter', 1.0, min_value=-5.0, max_value=5.0, delta=0.2, desc='test', free=False, unit=u.MeV, prior=Uniform_prior()) # Add a callback working_callback = Callback() p_orig.add_callback(working_callback) # Now pickle and unpickle d = cPickle.dumps(p_orig) p = cPickle.loads(d) # Check that everything is fine assert p.min_value == -5.0 assert p.max_value == 5.0 assert p.value == 1.0 assert p.delta == 0.2 assert p.name == 'test_parameter' assert p.description == 'test' assert p.fix == True assert p.free == False assert p.has_prior() == True assert p.unit == u.MeV # Test the callback p.value = 2.0 callback = p.get_callbacks()[0] assert callback._control_value == p.value