SUnit.st 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  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. delay: millis
  90. ^ Promise new: [ :model | [ model value: nil ] valueWithTimeout: millis ]
  91. !
  92. finished
  93. self errorIfNotAsync: '#finished'.
  94. asyncTimeout ifNotNil: [ asyncTimeout clearTimeout ].
  95. asyncTimeout := nil
  96. !
  97. timeout: aNumber
  98. "Set a grace time timeout in milliseconds to run the test asynchronously"
  99. asyncTimeout ifNotNil: [ asyncTimeout clearTimeout ].
  100. "to allow #async: message send without throwing an error"
  101. asyncTimeout := 0.
  102. asyncTimeout := (self async: [
  103. self assert: false description: 'SUnit grace time exhausted' ])
  104. valueWithTimeout: aNumber
  105. ! !
  106. !TestCase methodsFor: 'error handling'!
  107. errorIfNotAsync: aString
  108. self isAsync ifFalse: [
  109. self error: aString, ' used without prior #timeout:' ]
  110. ! !
  111. !TestCase methodsFor: 'private'!
  112. signalFailure: aString
  113. TestFailure new
  114. messageText: aString;
  115. signal
  116. ! !
  117. !TestCase methodsFor: 'running'!
  118. debugCase
  119. self deprecatedAPI: 'Use #runCase instead.'.
  120. ^ self runCase
  121. !
  122. performTest
  123. asyncTimeout := nil.
  124. ^ self perform: self selector
  125. !
  126. runCase
  127. "Runs a test case in isolated context, leaking all errors."
  128. (TestContext testCase: self) start
  129. !
  130. setUp
  131. !
  132. tearDown
  133. ! !
  134. !TestCase methodsFor: 'testing'!
  135. assert: aBoolean
  136. self assert: aBoolean description: 'Assertion failed'
  137. !
  138. assert: aBoolean description: aString
  139. aBoolean ifFalse: [ self signalFailure: aString ]
  140. !
  141. assert: actual equals: expected
  142. ^ self assert: (actual = expected) description: 'Expected: ', expected printString, ' but was: ', actual printString
  143. !
  144. deny: aBoolean
  145. self assert: aBoolean not
  146. !
  147. isAsync
  148. ^ asyncTimeout notNil
  149. !
  150. should: aBlock
  151. self assert: aBlock value
  152. !
  153. should: aBlock raise: anExceptionClass
  154. self assert: ([ aBlock value. false ]
  155. on: anExceptionClass
  156. do: [ :ex | true ])
  157. !
  158. shouldnt: aBlock raise: anExceptionClass
  159. self assert: ([ aBlock value. true ]
  160. on: anExceptionClass
  161. do: [ :ex | false ])
  162. ! !
  163. !TestCase class methodsFor: 'accessing'!
  164. allTestSelectors
  165. | selectors |
  166. selectors := self testSelectors.
  167. self shouldInheritSelectors ifTrue: [
  168. selectors addAll: self superclass allTestSelectors ].
  169. ^ selectors asSet
  170. !
  171. buildSuite
  172. ^ self allTestSelectors collect: [ :each | self selector: each ]
  173. !
  174. classTag
  175. "Returns a tag or general category for this class.
  176. Typically used to help tools do some reflection.
  177. Helios, for example, uses this to decide what icon the class should display."
  178. ^ 'test'
  179. !
  180. lookupHierarchyRoot
  181. ^ TestCase
  182. !
  183. selector: aSelector
  184. ^ self new
  185. setTestSelector: aSelector;
  186. yourself
  187. !
  188. testSelectors
  189. ^ self methodDictionary keys select: [ :each | each match: '^test' ]
  190. ! !
  191. !TestCase class methodsFor: 'testing'!
  192. isAbstract
  193. ^ self name = TestCase name
  194. !
  195. isTestClass
  196. ^ self isAbstract not
  197. !
  198. shouldInheritSelectors
  199. ^ self ~= self lookupHierarchyRoot
  200. ! !
  201. Object subclass: #TestContext
  202. slots: {#testCase}
  203. package: 'SUnit'!
  204. !TestContext commentStamp!
  205. I govern running a particular test case.
  206. 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).!
  207. !TestContext methodsFor: 'accessing'!
  208. testCase: aTestCase
  209. testCase := aTestCase
  210. ! !
  211. !TestContext methodsFor: 'running'!
  212. execute: aBlock
  213. | failed result |
  214. testCase context: self.
  215. [
  216. failed := true.
  217. result := aBlock value.
  218. testCase isAsync ifFalse: [
  219. testCase assert: result isThenable not description: testCase asString, ' returned promise without sending #timeout:' ].
  220. failed := false
  221. ]
  222. ensure: [
  223. "testCase context: nil."
  224. (failed and: [ testCase isAsync ]) ifTrue: [ testCase finished ].
  225. testCase isAsync
  226. ifFalse: [ testCase tearDown ]
  227. ifTrue: [ result isThenable ifTrue: [
  228. result
  229. then: [ testCase isAsync ifTrue: [ self execute: [ testCase finished ] ] ]
  230. catch: [ :error | testCase isAsync ifTrue: [ self execute: [ error signal ] ] ] ] ] ]
  231. !
  232. start
  233. self execute: [
  234. testCase setUp.
  235. testCase performTest ]
  236. ! !
  237. !TestContext class methodsFor: 'instance creation'!
  238. testCase: aTestCase
  239. ^ self new
  240. testCase: aTestCase;
  241. yourself
  242. ! !
  243. TestContext subclass: #ReportingTestContext
  244. slots: {#finished. #result}
  245. package: 'SUnit'!
  246. !ReportingTestContext commentStamp!
  247. I add `TestResult` reporting to `TestContext`.
  248. Errors are caught and save into a `TestResult`,
  249. When test case is finished (which can be later for async tests), a callback block is executed; this is used by a `TestSuiteRunner`.!
  250. !ReportingTestContext methodsFor: 'accessing'!
  251. finished: aBlock
  252. finished := aBlock
  253. !
  254. result: aTestResult
  255. result := aTestResult
  256. ! !
  257. !ReportingTestContext methodsFor: 'private'!
  258. withErrorReporting: aBlock
  259. [ aBlock
  260. on: TestFailure
  261. do: [ :ex | result addFailure: testCase ]
  262. ]
  263. on: Error
  264. do: [ :ex | result addError: testCase ]
  265. ! !
  266. !ReportingTestContext methodsFor: 'running'!
  267. execute: aBlock
  268. [
  269. self withErrorReporting: [ super execute: aBlock ]
  270. ]
  271. ensure: [
  272. testCase isAsync ifFalse: [
  273. result increaseRuns. finished value ] ]
  274. ! !
  275. !ReportingTestContext class methodsFor: 'instance creation'!
  276. testCase: aTestCase result: aTestResult finished: aBlock
  277. ^ (super testCase: aTestCase)
  278. result: aTestResult;
  279. finished: aBlock;
  280. yourself
  281. ! !
  282. Error subclass: #TestFailure
  283. slots: {}
  284. package: 'SUnit'!
  285. !TestFailure commentStamp!
  286. I am raised when the boolean parameter of an #`assert:` or `#deny:` call is the opposite of what the assertion claims.
  287. The test framework distinguishes between failures and errors.
  288. A failure is an event whose possibiity is explicitly anticipated and checked for in an assertion,
  289. whereas an error is an unanticipated problem like a division by 0 or an index out of bounds.!
  290. Object subclass: #TestResult
  291. slots: {#timestamp. #runs. #errors. #failures. #total}
  292. package: 'SUnit'!
  293. !TestResult commentStamp!
  294. I implement the collecting parameter pattern for running a bunch of tests.
  295. My instances hold tests that have run, sorted into the result categories of passed, failures and errors.
  296. `TestResult` is an interesting object to subclass or substitute. `#runCase:` is the external protocol you need to reproduce!
  297. !TestResult methodsFor: 'accessing'!
  298. addError: anError
  299. self errors add: anError
  300. !
  301. addFailure: aFailure
  302. self failures add: aFailure
  303. !
  304. errors
  305. ^ errors
  306. !
  307. failures
  308. ^ failures
  309. !
  310. increaseRuns
  311. runs := runs + 1
  312. !
  313. runs
  314. ^ runs
  315. !
  316. status
  317. ^ self errors ifNotEmpty: [ 'error' ] ifEmpty: [
  318. self failures ifNotEmpty: [ 'failure' ] ifEmpty: [
  319. 'success' ]]
  320. !
  321. timestamp
  322. ^ timestamp
  323. !
  324. total
  325. ^ total
  326. !
  327. total: aNumber
  328. total := aNumber
  329. ! !
  330. !TestResult methodsFor: 'initialization'!
  331. initialize
  332. super initialize.
  333. timestamp := Date now.
  334. runs := 0.
  335. errors := Array new.
  336. failures := Array new.
  337. total := 0
  338. ! !
  339. !TestResult methodsFor: 'running'!
  340. nextRunDo: aBlock
  341. "Runs aBlock with index of next run or does nothing if no more runs"
  342. ^ self runs == self total
  343. ifFalse: [ aBlock value: self runs + 1 ]
  344. !
  345. runCase: aTestCase
  346. [ [ self increaseRuns.
  347. aTestCase runCase ]
  348. on: TestFailure do: [ :ex | self addFailure: aTestCase ]]
  349. on: Error do: [ :ex | self addError: aTestCase ]
  350. ! !
  351. Object subclass: #TestSuiteRunner
  352. slots: {#suite. #result. #announcer. #runNextTest}
  353. package: 'SUnit'!
  354. !TestSuiteRunner commentStamp!
  355. I am responsible for running a collection (`suite`) of tests.
  356. ## API
  357. Instances should be created using the class-side `#on:` method, taking a collection of tests to run as parameter.
  358. To run the test suite, use `#run`.!
  359. !TestSuiteRunner methodsFor: 'accessing'!
  360. announcer
  361. ^ announcer
  362. !
  363. result
  364. ^ result
  365. !
  366. suite: aCollection
  367. suite := aCollection
  368. ! !
  369. !TestSuiteRunner methodsFor: 'actions'!
  370. resume
  371. runNextTest fork.
  372. announcer announce: (ResultAnnouncement new result: result)
  373. !
  374. run
  375. result total: suite size.
  376. self resume
  377. ! !
  378. !TestSuiteRunner methodsFor: 'initialization'!
  379. initialize
  380. super initialize.
  381. announcer := Announcer new.
  382. result := TestResult new.
  383. runNextTest := [ | runs | runs := result runs. runs < result total ifTrue: [ (self contextOf: runs + 1) start ] ].
  384. ! !
  385. !TestSuiteRunner methodsFor: 'private'!
  386. contextOf: anInteger
  387. ^ ReportingTestContext testCase: (suite at: anInteger) result: result finished: [ self resume ]
  388. ! !
  389. !TestSuiteRunner class methodsFor: 'instance creation'!
  390. new
  391. self shouldNotImplement
  392. !
  393. on: aCollection
  394. ^ super new suite: aCollection
  395. ! !
  396. !Package methodsFor: '*SUnit'!
  397. isTestPackage
  398. ^ self classes anySatisfy: [ :each | each isTestClass ]
  399. ! !
  400. !TBehaviorDefaults methodsFor: '*SUnit'!
  401. isTestClass
  402. ^ false
  403. ! !