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