SUnit.st 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. Smalltalk createPackage: 'SUnit'!
  2. Object subclass: #ResultAnnouncement
  3. slots: {#result}
  4. package: 'SUnit'!
  5. !ResultAnnouncement commentStamp!
  6. I get signaled when a `TestCase` has been run.
  7. My instances hold the result (instance of `TestResult`) of the test run.!
  8. !ResultAnnouncement methodsFor: 'accessing'!
  9. result
  10. ^ result
  11. !
  12. result: aTestResult
  13. result := aTestResult
  14. ! !
  15. Object subclass: #Teachable
  16. slots: {#learnings}
  17. package: 'SUnit'!
  18. !Teachable commentStamp!
  19. An object you can teach how to behave. Have a look at the
  20. class side for an example.
  21. For more infos have a look at: http://lists.squeakfoundation.org/pipermail/squeak-dev/2002-April/038170.html!
  22. !Teachable methodsFor: 'private'!
  23. doesNotUnderstand: aMessage
  24. | learning |
  25. learning := self learnings
  26. at: aMessage selector
  27. ifAbsent:[ ^super doesNotUnderstand: aMessage ].
  28. ^ learning class == Association
  29. ifTrue: [learning value]
  30. ifFalse: [learning valueWithPossibleArguments: aMessage arguments]
  31. !
  32. learnings
  33. learnings isNil ifTrue: [learnings := Dictionary new].
  34. ^learnings
  35. ! !
  36. !Teachable methodsFor: 'teaching'!
  37. acceptSend: aSymbol
  38. self whenSend: aSymbol return: self
  39. !
  40. whenSend: aSymbol evaluate: aBlock
  41. self learnings at: aSymbol put: aBlock
  42. !
  43. whenSend: aSymbol return: anObject
  44. self learnings at: aSymbol put: (#return -> anObject)
  45. ! !
  46. !Teachable class methodsFor: 'examples'!
  47. example
  48. | teachable |
  49. teachable := self new.
  50. teachable
  51. whenSend: #help return: 'ok';
  52. whenSend: #doit evaluate: [1 inspect];
  53. acceptSend: #noDebugger;
  54. whenSend: #negate: evaluate: [:num | num negated].
  55. teachable help.
  56. teachable doit.
  57. teachable noDebugger.
  58. teachable negate: 120
  59. ! !
  60. Object subclass: #TestCase
  61. slots: {#testSelector. #asyncTimeout. #context}
  62. package: 'SUnit'!
  63. !TestCase commentStamp!
  64. I am an implementation of the command pattern to run a test.
  65. ## API
  66. My instances are created with the class method `#selector:`,
  67. passing the symbol that names the method to be executed when the test case runs.
  68. When you discover a new fixture, subclass `TestCase` and create a `#test...` method for the first test.
  69. As that method develops and more `#test...` methods are added, you will find yourself refactoring temps
  70. into instance variables for the objects in the fixture and overriding `#setUp` to initialize these variables.
  71. As required, override `#tearDown` to nil references, release objects and deallocate.!
  72. !TestCase methodsFor: 'accessing'!
  73. context: aRunningTestContext
  74. context := aRunningTestContext
  75. !
  76. selector
  77. ^ testSelector
  78. !
  79. setTestSelector: aSelector
  80. testSelector := aSelector
  81. ! !
  82. !TestCase methodsFor: 'async'!
  83. async: aBlock
  84. | c |
  85. self errorIfNotAsync: '#async'.
  86. c := context.
  87. ^ [ self isAsync ifTrue: [ c execute: aBlock ] ]
  88. !
  89. finished
  90. self errorIfNotAsync: '#finished'.
  91. asyncTimeout ifNotNil: [ asyncTimeout clearTimeout ].
  92. asyncTimeout := nil
  93. !
  94. timeout: aNumber
  95. "Set a grace time timeout in milliseconds to run the test asynchronously"
  96. asyncTimeout ifNotNil: [ asyncTimeout clearTimeout ].
  97. "to allow #async: message send without throwing an error"
  98. asyncTimeout := 0.
  99. asyncTimeout := (self async: [
  100. self assert: false description: 'SUnit grace time exhausted' ])
  101. valueWithTimeout: aNumber
  102. ! !
  103. !TestCase methodsFor: 'error handling'!
  104. errorIfNotAsync: aString
  105. self isAsync ifFalse: [
  106. self error: aString, ' used without prior #timeout:' ]
  107. ! !
  108. !TestCase methodsFor: 'private'!
  109. signalFailure: aString
  110. TestFailure new
  111. messageText: aString;
  112. signal
  113. ! !
  114. !TestCase methodsFor: 'running'!
  115. debugCase
  116. self deprecatedAPI: 'Use #runCase instead.'.
  117. ^ self runCase
  118. !
  119. performTest
  120. asyncTimeout := nil.
  121. ^ self perform: self selector
  122. !
  123. runCase
  124. "Runs a test case in isolated context, leaking all errors."
  125. (TestContext testCase: self) start
  126. !
  127. setUp
  128. !
  129. tearDown
  130. ! !
  131. !TestCase methodsFor: 'testing'!
  132. assert: aBoolean
  133. self assert: aBoolean description: 'Assertion failed'
  134. !
  135. assert: aBoolean description: aString
  136. aBoolean ifFalse: [ self signalFailure: aString ]
  137. !
  138. assert: actual equals: expected
  139. ^ self assert: (actual = expected) description: 'Expected: ', expected printString, ' but was: ', actual printString
  140. !
  141. deny: aBoolean
  142. self assert: aBoolean not
  143. !
  144. isAsync
  145. ^ asyncTimeout notNil
  146. !
  147. should: aBlock
  148. self assert: aBlock value
  149. !
  150. should: aBlock raise: anExceptionClass
  151. self assert: ([ aBlock value. false ]
  152. on: anExceptionClass
  153. do: [ :ex | true ])
  154. !
  155. shouldnt: aBlock raise: anExceptionClass
  156. self assert: ([ aBlock value. true ]
  157. on: anExceptionClass
  158. do: [ :ex | false ])
  159. ! !
  160. !TestCase class methodsFor: 'accessing'!
  161. allTestSelectors
  162. | selectors |
  163. selectors := self testSelectors.
  164. self shouldInheritSelectors ifTrue: [
  165. selectors addAll: self superclass allTestSelectors ].
  166. ^ selectors asSet
  167. !
  168. buildSuite
  169. ^ self allTestSelectors collect: [ :each | self selector: each ]
  170. !
  171. classTag
  172. "Returns a tag or general category for this class.
  173. Typically used to help tools do some reflection.
  174. Helios, for example, uses this to decide what icon the class should display."
  175. ^ 'test'
  176. !
  177. lookupHierarchyRoot
  178. ^ TestCase
  179. !
  180. selector: aSelector
  181. ^ self new
  182. setTestSelector: aSelector;
  183. yourself
  184. !
  185. testSelectors
  186. ^ self methodDictionary keys select: [ :each | each match: '^test' ]
  187. ! !
  188. !TestCase class methodsFor: 'testing'!
  189. isAbstract
  190. ^ self name = TestCase name
  191. !
  192. isTestClass
  193. ^ self isAbstract not
  194. !
  195. shouldInheritSelectors
  196. ^ self ~= self lookupHierarchyRoot
  197. ! !
  198. Object subclass: #TestContext
  199. slots: {#testCase}
  200. package: 'SUnit'!
  201. !TestContext commentStamp!
  202. I govern running a particular test case.
  203. My main added value is `#execute:` method which runs a block as a part of test case (restores context, nilling it afterwards, cleaning/calling `#tearDown` as appropriate for sync/async scenario).!
  204. !TestContext methodsFor: 'accessing'!
  205. testCase: aTestCase
  206. testCase := aTestCase
  207. ! !
  208. !TestContext methodsFor: 'running'!
  209. execute: aBlock
  210. | failed result |
  211. testCase context: self.
  212. [
  213. failed := true.
  214. result := aBlock value.
  215. testCase isAsync ifFalse: [
  216. testCase assert: result isThenable not description: testCase asString, ' returned promise without sending #timeout:' ].
  217. failed := false
  218. ]
  219. ensure: [
  220. "testCase context: nil."
  221. (failed and: [ testCase isAsync ]) ifTrue: [ testCase finished ].
  222. testCase isAsync
  223. ifFalse: [ testCase tearDown ]
  224. ifTrue: [ result isThenable ifTrue: [
  225. result
  226. then: [ testCase isAsync ifTrue: [ self execute: [ testCase finished ] ] ]
  227. catch: [ :error | testCase isAsync ifTrue: [ self execute: [ error signal ] ] ] ] ] ]
  228. !
  229. start
  230. self execute: [
  231. testCase setUp.
  232. testCase performTest ]
  233. ! !
  234. !TestContext class methodsFor: 'instance creation'!
  235. testCase: aTestCase
  236. ^ self new
  237. testCase: aTestCase;
  238. yourself
  239. ! !
  240. TestContext subclass: #ReportingTestContext
  241. slots: {#finished. #result}
  242. package: 'SUnit'!
  243. !ReportingTestContext commentStamp!
  244. I add `TestResult` reporting to `TestContext`.
  245. Errors are caught and save into a `TestResult`,
  246. When test case is finished (which can be later for async tests), a callback block is executed; this is used by a `TestSuiteRunner`.!
  247. !ReportingTestContext methodsFor: 'accessing'!
  248. finished: aBlock
  249. finished := aBlock
  250. !
  251. result: aTestResult
  252. result := aTestResult
  253. ! !
  254. !ReportingTestContext methodsFor: 'private'!
  255. withErrorReporting: aBlock
  256. [ aBlock
  257. on: TestFailure
  258. do: [ :ex | result addFailure: testCase ]
  259. ]
  260. on: Error
  261. do: [ :ex | result addError: testCase ]
  262. ! !
  263. !ReportingTestContext methodsFor: 'running'!
  264. execute: aBlock
  265. [
  266. self withErrorReporting: [ super execute: aBlock ]
  267. ]
  268. ensure: [
  269. testCase isAsync ifFalse: [
  270. result increaseRuns. finished value ] ]
  271. ! !
  272. !ReportingTestContext class methodsFor: 'instance creation'!
  273. testCase: aTestCase result: aTestResult finished: aBlock
  274. ^ (super testCase: aTestCase)
  275. result: aTestResult;
  276. finished: aBlock;
  277. yourself
  278. ! !
  279. Error subclass: #TestFailure
  280. slots: {}
  281. package: 'SUnit'!
  282. !TestFailure commentStamp!
  283. I am raised when the boolean parameter of an #`assert:` or `#deny:` call is the opposite of what the assertion claims.
  284. The test framework distinguishes between failures and errors.
  285. A failure is an event whose possibiity is explicitly anticipated and checked for in an assertion,
  286. whereas an error is an unanticipated problem like a division by 0 or an index out of bounds.!
  287. Object subclass: #TestResult
  288. slots: {#timestamp. #runs. #errors. #failures. #total}
  289. package: 'SUnit'!
  290. !TestResult commentStamp!
  291. I implement the collecting parameter pattern for running a bunch of tests.
  292. My instances hold tests that have run, sorted into the result categories of passed, failures and errors.
  293. `TestResult` is an interesting object to subclass or substitute. `#runCase:` is the external protocol you need to reproduce!
  294. !TestResult methodsFor: 'accessing'!
  295. addError: anError
  296. self errors add: anError
  297. !
  298. addFailure: aFailure
  299. self failures add: aFailure
  300. !
  301. errors
  302. ^ errors
  303. !
  304. failures
  305. ^ failures
  306. !
  307. increaseRuns
  308. runs := runs + 1
  309. !
  310. runs
  311. ^ runs
  312. !
  313. status
  314. ^ self errors ifNotEmpty: [ 'error' ] ifEmpty: [
  315. self failures ifNotEmpty: [ 'failure' ] ifEmpty: [
  316. 'success' ]]
  317. !
  318. timestamp
  319. ^ timestamp
  320. !
  321. total
  322. ^ total
  323. !
  324. total: aNumber
  325. total := aNumber
  326. ! !
  327. !TestResult methodsFor: 'initialization'!
  328. initialize
  329. super initialize.
  330. timestamp := Date now.
  331. runs := 0.
  332. errors := Array new.
  333. failures := Array new.
  334. total := 0
  335. ! !
  336. !TestResult methodsFor: 'running'!
  337. nextRunDo: aBlock
  338. "Runs aBlock with index of next run or does nothing if no more runs"
  339. ^ self runs == self total
  340. ifFalse: [ aBlock value: self runs + 1 ]
  341. !
  342. runCase: aTestCase
  343. [ [ self increaseRuns.
  344. aTestCase runCase ]
  345. on: TestFailure do: [ :ex | self addFailure: aTestCase ]]
  346. on: Error do: [ :ex | self addError: aTestCase ]
  347. ! !
  348. Object subclass: #TestSuiteRunner
  349. slots: {#suite. #result. #announcer. #runNextTest}
  350. package: 'SUnit'!
  351. !TestSuiteRunner commentStamp!
  352. I am responsible for running a collection (`suite`) of tests.
  353. ## API
  354. Instances should be created using the class-side `#on:` method, taking a collection of tests to run as parameter.
  355. To run the test suite, use `#run`.!
  356. !TestSuiteRunner methodsFor: 'accessing'!
  357. announcer
  358. ^ announcer
  359. !
  360. result
  361. ^ result
  362. !
  363. suite: aCollection
  364. suite := aCollection
  365. ! !
  366. !TestSuiteRunner methodsFor: 'actions'!
  367. resume
  368. runNextTest fork.
  369. announcer announce: (ResultAnnouncement new result: result)
  370. !
  371. run
  372. result total: suite size.
  373. self resume
  374. ! !
  375. !TestSuiteRunner methodsFor: 'initialization'!
  376. initialize
  377. super initialize.
  378. announcer := Announcer new.
  379. result := TestResult new.
  380. runNextTest := [ | runs | runs := result runs. runs < result total ifTrue: [ (self contextOf: runs + 1) start ] ].
  381. ! !
  382. !TestSuiteRunner methodsFor: 'private'!
  383. contextOf: anInteger
  384. ^ ReportingTestContext testCase: (suite at: anInteger) result: result finished: [ self resume ]
  385. ! !
  386. !TestSuiteRunner class methodsFor: 'instance creation'!
  387. new
  388. self shouldNotImplement
  389. !
  390. on: aCollection
  391. ^ super new suite: aCollection
  392. ! !
  393. !Package methodsFor: '*SUnit'!
  394. isTestPackage
  395. ^ self classes anySatisfy: [ :each | each isTestClass ]
  396. ! !
  397. !TBehaviorDefaults methodsFor: '*SUnit'!
  398. isTestClass
  399. ^ false
  400. ! !