Execution environment usage for running examples

This page describes how the execution environment is specifically used when running GT examples. For a general overview of execution environments, see the page Execution environment overview.

There are three main ways examples get executed:

  1. Interactive/IDE - When running individual examples from the UI via GtExample>>#runrun <return: #GtExampleResult> ^ self evaluator result or GtExample>>#debugdebug ^ self debugger result
  1. Command Line/CI - When running examples in batch via GtExamplesHudsonReportGtExamplesTestingHudsonReport << #GtExamplesHudsonReport slots: {}; tag: 'Testing'; package: 'GToolkit-Examples'
  1. Remote runner - When running examples in the remote runner using GtRrExamplesTaskGtRrAbstractExamplesTask << #GtRrExamplesTask slots: { #ignoreNoTest }; tag: 'Tests'; package: 'RemoteRunner'. This delegates the running directly to the GtExampleObject << #GtExample slots: { #methodClass . #selector . #label . #description . #form . #exceptions . #subjects . #children . #properties . #after . #problems . #timeLimit . #receiverClass }; sharedVariables: { #DefaultGlobalTimeLimit }; tag: 'Core'; package: 'GToolkit-Examples' instance.

The GtExampleEvaluator

The core class for example execution is GtExampleEvaluator GtExampleProcessor << #GtExampleEvaluator slots: { #result }; sharedVariables: { #StartMcpServer }; tag: 'Runtime'; package: 'GToolkit-Examples' . It provides two execution modes:
  • GtExampleEvaluator>>#runManagedrunManaged <return: #GtExampleResult> ^ CurrentExecutionEnvironment runExampleEvaluator: self - Runs with watchdog monitoring (time limits enforced) and cleans up after the example. GtExampleEvaluator>>#resultresult <return: #GtExampleResult> <gsCode: 'self do: [ result := self runManaged ] on: GtExampleResult signalableExceptions do: [ :anException | result := (self newResultFor: self example) exampleException: (GtSystemUtility freeze: anException) ]. ^ result'> self do: [ result := self runManaged ] on: GtExampleResult signalableExceptions do: [ :anException | (self class startMcpServerFor: anException) ifTrue: [ self startMcpServerWith: anException ]. result := (self newResultFor: self example) exampleException: (GtSystemUtility freeze: anException) ]. ^ result uses it, so it is the default.
  • GtExampleEvaluator>>#runUnmanagedrunUnmanaged "The ideal case would be to updade the example runner to use runManaged" <return: #GtExampleResult> <gsCode: '^ self value'> ^ CurrentExecutionEnvironment runUnmanagedExampleEvaluator: self - Runs without the watchdog and without the clean up: services that clean up after a test are disabled (TestExecutionEnvironment>>#disableServicesForUnmanagedExampleRundisableServicesForUnmanagedExampleRun "Disable the services that clean up after a test, because an unmanaged example run is not cleaned up" services do: [ :each | each isEnabledInUnmanagedExampleRuns ifFalse: [ each disable ] ]), so processes and promises the example starts keep running. Used when a user plays an example (GtPharoMethodCoder>>#playExampleplayExample "Run the example without the clean up of managed runs, so that promises and processes it started keep running while the user works with the returned object (see GtExample>>#runUnmanaged)" self isModified ifTrue: [ self save ifFalse: [ ^ self ] ]. self example runUnmanaged, GtExampleEvaluator>>#unmanagedResultunmanagedResult "Like #result, but run the example without the clean up of managed runs (see #runUnmanaged): processes it forks and promises it schedules keep running after it ends. Used when a user runs an example interactively and keeps working with the returned object" <return: #GtExampleResult> <gsCode: 'self do: [ result := self runUnmanaged ] on: GtExampleResult signalableExceptions do: [ :anException | result := (self newResultFor: self example) exampleException: (GtSystemUtility freeze: anException) ]. ^ result'> self do: [ result := self runUnmanaged ] on: GtExampleResult signalableExceptions do: [ :anException | (self class startMcpServerFor: anException) ifTrue: [ self startMcpServerWith: anException ]. result := (self newResultFor: self example) exampleException: (GtSystemUtility freeze: anException) ]. ^ result).

Both methods delegate to CurrentExecutionEnvironment ProcessLocalVariable << #CurrentExecutionEnvironment slots: {}; tag: 'Processes'; package: 'Kernel' :

"Managed execution with watchdog"
CurrentExecutionEnvironment runExampleEvaluator: anEvaluator.

"Unmanaged execution without watchdog"
CurrentExecutionEnvironment runUnmanagedExampleEvaluator: anEvaluator.
  

When you run an example interactively:

  1. GtExample>>#runrun <return: #GtExampleResult> ^ self evaluator result creates a GtExampleEvaluatorGtExampleProcessor << #GtExampleEvaluator slots: { #result }; sharedVariables: { #StartMcpServer }; tag: 'Runtime'; package: 'GToolkit-Examples'
  1. GtExampleEvaluator>>#resultresult <return: #GtExampleResult> <gsCode: 'self do: [ result := self runManaged ] on: GtExampleResult signalableExceptions do: [ :anException | result := (self newResultFor: self example) exampleException: (GtSystemUtility freeze: anException) ]. ^ result'> self do: [ result := self runManaged ] on: GtExampleResult signalableExceptions do: [ :anException | (self class startMcpServerFor: anException) ifTrue: [ self startMcpServerWith: anException ]. result := (self newResultFor: self example) exampleException: (GtSystemUtility freeze: anException) ]. ^ result calls GtExampleEvaluator>>#runManagedrunManaged <return: #GtExampleResult> ^ CurrentExecutionEnvironment runExampleEvaluator: self
  1. This calls CurrentExecutionEnvironment>>#runExampleEvaluator:runExampleEvaluator: anExampleEvaluator <gsCode: '^ DefaultExecutionEnvironment instance runExampleEvaluator: anExampleEvaluator'> ^ self value runExampleEvaluator: anExampleEvaluator
  1. Since no test environment is pre-installed, DefaultExecutionEnvironment>>#runExampleEvaluator:runExampleEvaluator: anExampleEvaluator | testEnv exampleResult | testEnv := TestExecutionEnvironment new. exampleResult := nil. testEnv beActiveDuring: [ exampleResult := testEnv runExampleEvaluator: anExampleEvaluator ]. ^ exampleResult creates and activates a new TestExecutionEnvironmentExecutionEnvironment << #TestExecutionEnvironment slots: { #watchDogProcess . #watchDogSemaphore . #testCase . #maxTimeForTest . #testCompleted . #services . #mainTestProcess }; tag: 'Kernel'; package: 'SUnit-Core'
  1. TestExecutionEnvironment>>#runExampleEvaluator:runExampleEvaluator: anExampleEvaluator | exampleResult | self isRunningTestCase ifTrue: [ ^ self runNestedExampleEvaluator: anExampleEvaluator ]. testCase := anExampleEvaluator. maxTimeForTest := anExampleEvaluator timeLimit. testCompleted := false. watchDogSemaphore signal. "signal about new test case" [ exampleResult := self runExampleUnderWatchdogUsingEvaluator: anExampleEvaluator ] ensure: [ testCompleted := true. watchDogSemaphore signal. "signal that test case is completed" self cleanUpAfterTest ]. ^ exampleResult sets the evaluator as the current testCase and runs it managed: under the watchdog, then handleCompletedTest and cleanUpAfterTest
"From DefaultExecutionEnvironment>>#runExampleEvaluator:"
testEnv := TestExecutionEnvironment new.
testEnv beActiveDuring: [
	exampleResult := testEnv runExampleEvaluator: anExampleEvaluator ].
  

Execution Flow from Command Line

When running examples in CI via GtExamplesHudsonReport GtExamplesTestingHudsonReport << #GtExamplesHudsonReport slots: {}; tag: 'Testing'; package: 'GToolkit-Examples' :
  1. GtExamplesTestingHudsonReport>>#runAllrunAll CurrentExecutionEnvironment runTestsBy: [ self testCasesToRun do: [ :each | self runTestCase: each ] ] calls CurrentExecutionEnvironment runTestsBy: [...]
  1. This installs a TestExecutionEnvironmentExecutionEnvironment << #TestExecutionEnvironment slots: { #watchDogProcess . #watchDogSemaphore . #testCase . #maxTimeForTest . #testCompleted . #services . #mainTestProcess }; tag: 'Kernel'; package: 'SUnit-Core' via DefaultExecutionEnvironment>>#runTestsBy:runTestsBy: aBlock TestExecutionEnvironment new beActiveDuring: aBlock for all examples of the report. GtExamplesHudsonReport>>#runPackage:runPackage: aString | theExamples theExamplesGroupedByClass | theExamples := (self packageOrganizer packageNamed: aString) gtExamplesAllContained. theExamplesGroupedByClass := theExamples groupedBy: [ :each | each methodClass ]. GtExamplesReportRunPackageSignal new packageName: aString; amountOfExampleClasses: theExamplesGroupedByClass size; amountOfExamples: theExamples size; emit. ^ theExamplesGroupedByClass associations collect: [ :eachAssoc | | eachClass classExamples sortFunction | eachClass := eachAssoc key. classExamples := eachAssoc value. sortFunction := GtMethodsSortFunction new. classExamples := classExamples sorted: [ :a :b | (sortFunction collate: a method with: b method) <= 0 ]. GtExamplesReportRunClassSignal new exampleClass: eachClass; amountOfExamples: classExamples size; emit. self new initializeWithTestCases: classExamples; reportName: aString, '-', eachClass name; run ] creates one report per example class, so each class gets its own environment
  1. Each example is then run via GtExamplesHudsonReport>>#runExample:runExample: anExample | errorDetails stacks runStatus retryCount lastError | errorDetails := nil. retryCount := 3. stacks := OrderedCollection new. "Retry only after a failed attempt has unwound: until then the watchdog of the execution environment keeps signalling TestTookTooMuchTime, which would escape a handler doing slow work" self beginTestCase: anExample runBlock: [ [ lastError := self runAttemptOf: anExample isLastAttempt: retryCount <= 1 addingStackTo: stacks. lastError notNil and: [ retryCount := retryCount - 1. self emitRetrySignalFor: anExample exception: lastError retryCount: retryCount. retryCount > 0 ] ] whileTrue: [ self prepareForRetryOf: anExample ]. lastError ifNotNil: [ errorDetails := Dictionary new. self initializeErrorDetails: errorDetails forError: lastError ] ]. errorDetails ifNil: [ runStatus := #success ] ifNotNil: [ | stackReport | stackReport := stacks size = 1 ifTrue: [ stacks first ] ifFalse: [ String streamContents: [ :aStream | | stackIndex | stackIndex := 1. stacks do: [ :aStack | aStream << 'Stack '; print: stackIndex; lf; << aStack. stackIndex := stackIndex +1 ] separatedBy: [ aStream lf; lf ] ] ]. ((errorDetails at: #errorClass) includesBehavior: AssertionFailure) ifTrue: [ runStatus := #failure. self writeFailure: errorDetails stack: stackReport ] ifFalse: [ runStatus := #error. self writeError: errorDetails stack: stackReport ] ]. self endTestCase. GtExamplesReportRunExampleSignal new example: anExample; runStatus: runStatus; emit. which calls GtExample>>#debugdebug ^ self debugger result
  1. GtExample>>#debugdebug ^ self debugger result uses a GtExampleDebuggerGtExampleEvaluator << #GtExampleDebugger slots: {}; tag: 'Runtime'; package: 'GToolkit-Examples', which runs the example managed. Since a test environment is already active, TestExecutionEnvironment>>#runExampleEvaluator:runExampleEvaluator: anExampleEvaluator | exampleResult | self isRunningTestCase ifTrue: [ ^ self runNestedExampleEvaluator: anExampleEvaluator ]. testCase := anExampleEvaluator. maxTimeForTest := anExampleEvaluator timeLimit. testCompleted := false. watchDogSemaphore signal. "signal about new test case" [ exampleResult := self runExampleUnderWatchdogUsingEvaluator: anExampleEvaluator ] ensure: [ testCompleted := true. watchDogSemaphore signal. "signal that test case is completed" self cleanUpAfterTest ]. ^ exampleResult is called directly (no new environment created): each example runs under the watchdog and is cleaned up after it ends

Notes:

The environment and its services (e.g. ProcessMonitorTestService TestExecutionService << #ProcessMonitorTestService slots: { #forkedProcesses . #testFailures . #shouldSuspendBackgroundFailures . #shouldFailTestLeavingProcesses . #shouldTerminateProcesses . #mutex }; tag: 'Kernel'; package: 'SUnit-Core' ) are shared by all examples one report runs, i.e. the examples of one class. Services therefore have to be safe for use from several processes (see Patches/changes to the base Pharo Image).

An example that is started while another example or test is running gets its own environment (TestExecutionEnvironment>>#runNestedExampleEvaluator: runNestedExampleEvaluator: anExampleEvaluator "Run an example that is started by the running test case or example (e.g. by a Lepiter example annotation or a locally executed example suite) in its own environment. Otherwise its clean up would stop the thread pool, promises and forked processes of the running one, and change its time limit" | aNestedEnvironment exampleResult | aNestedEnvironment := self class new. aNestedEnvironment beActiveDuring: [ exampleResult := aNestedEnvironment runExampleEvaluator: anExampleEvaluator ]. ^ exampleResult ), so that its clean up does not stop the processes, promises, and time limit of the running one.

GtExamplesHudsonReport>>#runExample: runExample: anExample | errorDetails stacks runStatus retryCount lastError | errorDetails := nil. retryCount := 3. stacks := OrderedCollection new. "Retry only after a failed attempt has unwound: until then the watchdog of the execution environment keeps signalling TestTookTooMuchTime, which would escape a handler doing slow work" self beginTestCase: anExample runBlock: [ [ lastError := self runAttemptOf: anExample isLastAttempt: retryCount <= 1 addingStackTo: stacks. lastError notNil and: [ retryCount := retryCount - 1. self emitRetrySignalFor: anExample exception: lastError retryCount: retryCount. retryCount > 0 ] ] whileTrue: [ self prepareForRetryOf: anExample ]. lastError ifNotNil: [ errorDetails := Dictionary new. self initializeErrorDetails: errorDetails forError: lastError ] ]. errorDetails ifNil: [ runStatus := #success ] ifNotNil: [ | stackReport | stackReport := stacks size = 1 ifTrue: [ stacks first ] ifFalse: [ String streamContents: [ :aStream | | stackIndex | stackIndex := 1. stacks do: [ :aStack | aStream << 'Stack '; print: stackIndex; lf; << aStack. stackIndex := stackIndex +1 ] separatedBy: [ aStream lf; lf ] ] ]. ((errorDetails at: #errorClass) includesBehavior: AssertionFailure) ifTrue: [ runStatus := #failure. self writeFailure: errorDetails stack: stackReport ] ifFalse: [ runStatus := #error. self writeError: errorDetails stack: stackReport ] ]. self endTestCase. GtExamplesReportRunExampleSignal new example: anExample; runStatus: runStatus; emit. retries a failing example up to three times. A failed attempt first unwinds (GtExamplesHudsonReport>>#runAttemptOf:isLastAttempt:addingStackTo: runAttemptOf: anExample isLastAttempt: isLastAttempt addingStackTo: aCollectionOfStacks "Run anExample once. Answer the signalled exception, or nil if anExample succeeded. The handler only records the stack and returns, so the stack unwinds and the execution environment marks anExample as completed (its watchdog stops) before any slow work, like #prepareForRetryOf:, starts. A late TestTookTooMuchTime signalled while the stack is recorded is ignored, so it cannot escape the handler." ^ [ anExample debug. nil ] on: self signalableExceptions do: [ :anError | [ (isLastAttempt not or: [ (anExample exceptions handles: anError) not ]) ifTrue: [ aCollectionOfStacks add: (self stackTraceString: anError of: anExample) ] ] on: TestTookTooMuchTime do: [ :aTimeout | aTimeout return: nil ]. anError return: anError ] ), so the environment marks the example as completed and the watchdog stops; only then GtExamplesHudsonReport>>#prepareForRetryOf: prepareForRetryOf: anExample "Give the system a chance to recover before the next attempt of anExample. I run after the failed attempt has unwound, so the watchdog of the execution environment does not interrupt me" 3 timesRepeat: [ Smalltalk garbageCollect ]. 3 seconds wait collects garbage and waits. See GtExamplesHudsonReportExamples>>#slowRetryOfTimedOutExampleIsReported slowRetryOfTimedOutExampleIsReported "An example runs out of time in every attempt, and the preparation for the next attempt takes longer than its time limit. The report must still finish and report the example as one error with a stack for each attempt. The preparation must run after the failed attempt has unwound. Otherwise the watchdog signals another TestTookTooMuchTime inside the retry handler, which escapes the report and aborts the whole examples run." <gtExample> <return: #GtExamplesHudsonReportWithSlowRetry> | aReport contents | aReport := GtExamplesHudsonReportWithSlowRetry new initializeWithTestCases: {(self class >> #exampleExceedingItsTimeLimit) gtExample}; reportName: 'GtExamplesHudsonReportExamples'; yourself. [ aReport run. contents := aReport resultsFileName asFileReference contents ] ensure: [ aReport deleteFiles ]. self assert: aReport errorCount equals: 1. self assert: aReport failureCount equals: 0. self assert: (contents includesSubstring: '<error type="TestTookTooMuchTime"'). self assert: (contents includesSubstring: 'Stack 3'). self assert: (contents endsWith: '</testsuite>'). ^ aReport .

"From GtExamplesTestingHudsonReport>>#runAll"
CurrentExecutionEnvironment runTestsBy: [ 
	self testCasesToRun do: [ :each |  
		self runTestCase: each ] ]
  

Playing an example in a method coder (GtPharoMethodCoder>>#playExample playExample "Run the example without the clean up of managed runs, so that promises and processes it started keep running while the user works with the returned object (see GtExample>>#runUnmanaged)" self isModified ifTrue: [ self save ifFalse: [ ^ self ] ]. self example runUnmanaged ) is different: it calls GtExample>>#runUnmanaged runUnmanaged "Run me without the clean up of managed runs (see GtExampleEvaluator>>#unmanagedResult): processes I fork and promises I schedule keep running after I end. Use it when a user runs me interactively, e.g. in a method coder" <return: #GtExampleResult> ^ self evaluator unmanagedResult , so the processes and promises the example starts keep running while the user works with the returned object.

Similarly, GtPharoMethodCoder>>#debugExample debugExample "Debug the example without the clean up of managed runs, so that promises and processes it started keep running while the user works with the returned object (see GtExampleOpenDebugger>>#unmanagedResult)" self isModified ifTrue: [ self save ifFalse: [ ^ self ] ]. self example openingDebugger unmanagedResult calls GtExampleOpenDebugger>>#unmanagedResult unmanagedResult "Debug the example without the clean up of managed runs, so that promises and processes it started keep running while the user works with the returned object (see GtExampleEvaluator>>#unmanagedResult)" ^ self resultOpeningDebuggerOn: [ super unmanagedResult ] , so the processes and promises the example starts keep running while the user debugs and then works with the returned object.

Managed execution (TestExecutionEnvironment>>#runExampleEvaluator: runExampleEvaluator: anExampleEvaluator | exampleResult | self isRunningTestCase ifTrue: [ ^ self runNestedExampleEvaluator: anExampleEvaluator ]. testCase := anExampleEvaluator. maxTimeForTest := anExampleEvaluator timeLimit. testCompleted := false. watchDogSemaphore signal. "signal about new test case" [ exampleResult := self runExampleUnderWatchdogUsingEvaluator: anExampleEvaluator ] ensure: [ testCompleted := true. watchDogSemaphore signal. "signal that test case is completed" self cleanUpAfterTest ]. ^ exampleResult ):

  • Signals the watchdog semaphore to start timing
  • Calls TestExecutionEnvironment>>#runExampleUnderWatchdogUsingEvaluator:runExampleUnderWatchdogUsingEvaluator: anEvaluator "Evaluate the example directly (not through #runUnmanaged, which would re-enter the environment and disable the process monitor service)." | exampleResult | exampleResult := nil. [ [ exampleResult := anEvaluator value ] ensure: [ "Terminated test is not considered as completed (user just closed a debugger for example)"mainTestProcess isTerminating ifFalse: [ self handleCompletedTest ] ] ] on: Exception do: [ :err | self handleException: err ]. ^ exampleResult
  • Will signal TestTookTooMuchTime if the example exceeds its time limit, GtExample>>#timeLimittimeLimit ^ timeLimit ifNil: [ ^ self defaultTimeLimit ] (the <timeLimit:> pragma, by default GtExample>>#defaultTimeLimitdefaultTimeLimit <gsCode: '^ Duration seconds: 60'> ^ self class defaultGlobalTimeLimit ifNil: [ 1 minute ], 1 minute)
  • Calls #handleCompletedTest on services when done
  • Calls #cleanUpAfterTest after every example: terminates forked processes, cancels unfinished promises and stops the thread pool of the example

Unmanaged execution (TestExecutionEnvironment>>#runUnmanagedExampleEvaluator: runUnmanagedExampleEvaluator: anExampleEvaluator "Run the example without the clean up of #runExampleEvaluator:, e.g. when a user plays it in a method coder: processes it forks and promises it schedules keep running after it ends. An example that starts while another test case or example is running (e.g. a scripter example clicking a play button) runs as a part of the running one, without changing its state, so that the running one's clean up still covers it" | exampleResult | self isRunningTestCase ifTrue: [ ^ anExampleEvaluator value ]. self disableServicesForUnmanagedExampleRun. testCase := anExampleEvaluator. testCompleted := false. [ exampleResult := anExampleEvaluator value ] ensure: [ testCompleted := true ]. ^ exampleResult ):

  • Sets the evaluator as the current testCase (for Epicea logging checks)
  • Executes the evaluator directly without watchdog timing
  • Disables the services that clean up after a test and does not clean up, so processes and promises the example starts keep running
  • If a test case or an example is already running, the evaluator simply runs as a part of it, so the running one's clean up still covers it