Package mvpa :: Package tests :: Module test_state
[hide private]
[frames] | no frames]

Source Code for Module mvpa.tests.test_state

  1  # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- 
  2  # vi: set ft=python sts=4 ts=4 sw=4 et: 
  3  ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## 
  4  # 
  5  #   See COPYING file distributed along with the PyMVPA package for the 
  6  #   copyright and license terms. 
  7  # 
  8  ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## 
  9  """Unit tests for PyMVPA State parent class""" 
 10   
 11  import unittest, copy 
 12   
 13  import numpy as N 
 14   
 15  from mvpa.base import externals 
 16   
 17  from mvpa.misc.state import StateVariable, ClassWithCollections, \ 
 18       ParameterCollection, _def_sep 
 19  from mvpa.misc.param import * 
 20  from mvpa.misc.exceptions import UnknownStateError 
 21   
 22  if __debug__: 
 23      from mvpa.base import debug 
 24   
25 -class TestClassEmpty(ClassWithCollections):
26 pass
27
28 -class TestClassBlank(ClassWithCollections):
29 # We can force to have 'states' present even though we don't have 30 # any StateVariable defined here -- it might be added later on at run time 31 _ATTRIBUTE_COLLECTIONS = ['states'] 32 pass
33
34 -class TestClassBlankNoExplicitStates(ClassWithCollections):
35 pass
36
37 -class TestClassProper(ClassWithCollections):
38 39 state1 = StateVariable(enabled=False, doc="state1 doc") 40 state2 = StateVariable(enabled=True, doc="state2 doc")
41 42
43 -class TestClassProperChild(TestClassProper):
44 45 state4 = StateVariable(enabled=False, doc="state4 doc")
46 47
48 -class TestClassParametrized(TestClassProper, ClassWithCollections):
49 p1 = Parameter(0) 50 state0 = StateVariable(enabled=False) 51
52 - def __init__(self, **kwargs):
53 # XXX make such example when we actually need to invoke 54 # constructor 55 # TestClassProper.__init__(self, **kwargs) 56 ClassWithCollections.__init__(self, **kwargs)
57 58
59 -class StateTests(unittest.TestCase):
60
61 - def testBlankState(self):
62 empty = TestClassEmpty() 63 blank = TestClassBlank() 64 blank2 = TestClassBlank() 65 66 self.failUnlessRaises(AttributeError, empty.__getattribute__, 'states') 67 68 self.failUnlessEqual(blank.states.items, {}) 69 self.failUnless(blank.states.enabled == []) 70 self.failUnlessRaises(AttributeError, blank.__getattribute__, 'dummy') 71 self.failUnlessRaises(AttributeError, blank.__getattribute__, '_') 72 73 # we shouldn't use _registerState now since metaclass statecollector wouldn't 74 # update the states... may be will be implemented in the future if necessity comes 75 return 76 77 # add some state variable 78 blank._registerState('state1', False) 79 self.failUnless(blank.states == ['state1']) 80 81 self.failUnless(blank.states.isEnabled('state1') == False) 82 self.failUnless(blank.states.enabled == []) 83 self.failUnlessRaises(UnknownStateError, blank.__getattribute__, 'state1') 84 85 # assign value now 86 blank.state1 = 123 87 # should have no effect since the state variable wasn't enabled 88 self.failUnlessRaises(UnknownStateError, blank.__getattribute__, 'state1') 89 90 # lets enable and assign 91 blank.states.enable('state1') 92 blank.state1 = 123 93 self.failUnless(blank.state1 == 123) 94 95 # we should not share states across instances at the moment, so an arbitrary 96 # object could carry some custom states 97 self.failUnless(blank2.states == []) 98 self.failUnlessRaises(AttributeError, blank2.__getattribute__, 'state1')
99 100
101 - def testProperState(self):
102 proper = TestClassProper() 103 proper2 = TestClassProper(enable_states=['state1'], disable_states=['state2']) 104 105 # disable_states should override anything in enable_states 106 proper3 = TestClassProper(enable_states=['all'], disable_states='all') 107 108 self.failUnlessEqual(len(proper3.states.enabled), 0, 109 msg="disable_states should override anything in enable_states") 110 111 proper.state2 = 1000 112 value = proper.state2 113 self.failUnlessEqual(proper.state2, 1000, msg="Simple assignment/retrieval") 114 115 proper.states.disable('state2') 116 proper.state2 = 10000 117 self.failUnlessEqual(proper.state2, 1000, msg="Simple assignment after being disabled") 118 119 proper4 = copy.deepcopy(proper) 120 121 proper.states.reset('state2') 122 self.failUnlessRaises(UnknownStateError, proper.__getattribute__, 'state2') 123 """Must be blank after being reset""" 124 125 self.failUnlessEqual(proper4.state2, 1000, 126 msg="Simple assignment after being reset in original instance") 127 128 129 proper.states.enable(['state2']) 130 self.failUnlessEqual(set(proper.states.names), set(['state1', 'state2'])) 131 if __debug__ and 'ENFORCE_STATES_ENABLED' in debug.active: 132 # skip testing since all states are on now 133 return 134 self.failUnless(proper.states.enabled == ['state2']) 135 136 self.failUnless(set(proper2.states.enabled) == set(['state1'])) 137 138 self.failUnlessRaises(AttributeError, proper.__getattribute__, 'state12') 139 140 # if documentary on the state is appropriate 141 self.failUnlessEqual(proper2.states.listing, 142 ['%sstate1+%s: state1 doc' % (_def_sep, _def_sep), 143 '%sstate2%s: state2 doc' % (_def_sep, _def_sep)]) 144 145 # if __str__ lists correct number of states 146 str_ = str(proper2) 147 self.failUnless(str_.find('2 states:') != -1) 148 149 # check if disable works 150 self.failUnless(set(proper2.states.enabled), set(['state1'])) 151 152 proper2.states.disable("all") 153 self.failUnlessEqual(set(proper2.states.enabled), set()) 154 155 proper2.states.enable("all") 156 self.failUnlessEqual(len(proper2.states.enabled), 2) 157 158 proper2.state1, proper2.state2 = 1,2 159 self.failUnlessEqual(proper2.state1, 1) 160 self.failUnlessEqual(proper2.state2, 2) 161 162 # now reset them 163 proper2.states.reset('all') 164 self.failUnlessRaises(UnknownStateError, proper2.__getattribute__, 'state1') 165 self.failUnlessRaises(UnknownStateError, proper2.__getattribute__, 'state2')
166 167
168 - def testGetSaveEnabled(self):
169 """Check if we can store/restore set of enabled states""" 170 171 if __debug__ and 'ENFORCE_STATES_ENABLED' in debug.active: 172 # skip testing since all states are on now 173 return 174 175 proper = TestClassProper() 176 enabled_states = proper.states.enabled 177 proper.states.enable('state1') 178 179 self.failUnless(enabled_states != proper.states.enabled, 180 msg="New enabled states should differ from previous") 181 182 self.failUnless(set(proper.states.enabled) == set(['state1', 'state2']), 183 msg="Making sure that we enabled all states of interest") 184 185 proper.states.enabled = enabled_states 186 self.failUnless(enabled_states == proper.states.enabled, 187 msg="List of enabled states should return to original one")
188 189 190 # TODO: make test for _copy_states_ or whatever comes as an alternative 191
192 - def testStoredTemporarily(self):
193 proper = TestClassProper() 194 properch = TestClassProperChild(enable_states=["state1"]) 195 196 if __debug__ and 'ENFORCE_STATES_ENABLED' in debug.active: 197 # skip testing since all states are on now 198 return 199 200 self.failUnlessEqual(proper.states.enabled, ["state2"]) 201 proper.states._changeTemporarily( 202 enable_states=["state1"], other=properch) 203 self.failUnlessEqual(set(proper.states.enabled), 204 set(["state1", "state2"])) 205 proper.states._resetEnabledTemporarily() 206 self.failUnlessEqual(proper.states.enabled, ["state2"]) 207 208 # allow to enable disable without other instance 209 proper.states._changeTemporarily( 210 enable_states=["state1", "state2"]) 211 self.failUnlessEqual(set(proper.states.enabled), 212 set(["state1", "state2"])) 213 proper.states._resetEnabledTemporarily() 214 self.failUnlessEqual(proper.states.enabled, ["state2"])
215 216
217 - def testProperStateChild(self):
218 """ 219 Simple test if child gets state variables from the parent as well 220 """ 221 proper = TestClassProperChild() 222 self.failUnlessEqual(set(proper.states.names), 223 set(['state1', 'state2', 'state4']))
224 225
226 - def testStateVariables(self):
227 """To test new states""" 228 229 class S1(ClassWithCollections): 230 v1 = StateVariable(enabled=True, doc="values1 is ...") 231 v1XXX = StateVariable(enabled=False, doc="values1 is ...")
232 233 234 class S2(ClassWithCollections): 235 v2 = StateVariable(enabled=True, doc="values12 is ...")
236 237 class S1_(S1): 238 pass 239 240 class S1__(S1_): 241 v1__ = StateVariable(enabled=False) 242 243 class S12(S1__, S2): 244 v12 = StateVariable() 245 246 s1, s2, s1_, s1__, s12 = S1(), S2(), S1_(), S1__(), S12() 247 248 self.failUnlessEqual(s1.states.isEnabled("v1"), True) 249 s1.v1 = 12 250 s12.v1 = 120 251 s2.v2 = 100 252 253 self.failUnlessEqual(len(s2.states.listing), 1) 254 255 self.failUnlessEqual(s1.v1, 12) 256 try: 257 tempvalue = s1__.v1__ 258 self.fail("Should have puked since values were not enabled yet") 259 except: 260 pass 261 262
263 - def testParametrized(self):
264 265 self.failUnlessRaises(TypeError, TestClassParametrized, 266 p2=34, enable_states=['state1'], 267 msg="Should raise an exception if argument doesn't correspond to" 268 "any parameter") 269 a = TestClassParametrized(p1=123, enable_states=['state1']) 270 self.failUnlessEqual(a.p1, 123, msg="We must have assigned value to instance") 271 self.failUnless('state1' in a.states.enabled, 272 msg="state1 must have been enabled") 273 274 if (__debug__ and 'ID_IN_REPR' in debug.active): 275 # next tests would fail due to ID in the tails 276 return 277 278 # validate that string representation of the object is valid and consistent 279 a_str = `a` 280 try: 281 import test_state 282 exec "a2=%s" % a_str 283 except Exception, e: 284 self.fail(msg="Failed to generate an instance out of " 285 "representation %s. Got exception: %s" % (a_str, e)) 286 287 a2_str = `a2` 288 self.failUnless(a2_str == a_str, 289 msg="Generated object must have the same repr. Got %s and %s" % 290 (a_str, a2_str)) 291 292 # Test at least that repr of collection is of correct syntax 293 aparams_str = `a.params` 294 try: 295 import test_state 296 exec "aparams2=%s" % aparams_str 297 except Exception, e: 298 self.fail(msg="Failed to generate an instance out of " 299 "representation %s of params. Got exception: %s" % (aparams_str, e))
300 301
302 -def suite():
303 return unittest.makeSuite(StateTests)
304 305 306 if __name__ == '__main__': 307 import runner 308