SUnit.st 11 KB

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