github.com/ouraigua/jenkins-library@v0.0.0-20231028010029-fbeaf2f3aa9b/test/groovy/util/StepTracker.groovy (about)

     1  package util
     2  
     3  import static com.lesfurets.jenkins.unit.MethodSignature.method
     4  import static util.StepHelper.getSteps
     5  
     6  import org.codehaus.groovy.runtime.MetaClassHelper
     7  import com.lesfurets.jenkins.unit.MethodSignature
     8  import com.lesfurets.jenkins.unit.PipelineTestHelper
     9  import groovy.json.JsonBuilder
    10  
    11  class StepTracker {
    12  
    13      /*
    14       * Contains the piper steps as key (derived from the test name, so this is blurry since it might
    15       * contains also other cases than only piper step name) and the observed calls in a collection.
    16       */
    17      static Map piperStepCallMapping = [:]
    18      static Set piperSteps = StepHelper.getSteps()
    19  
    20      static Set calls
    21  
    22      static {
    23          initialize()
    24      }
    25  
    26      final static void initialize() {
    27  
    28          PipelineTestHelper.metaClass.getAllowedMethodEntry = {
    29  
    30              // We need to be careful here, in case we switch to another
    31              // version of the Les Furets framework we have to check if
    32              // this here still works.
    33  
    34              String name, Object[] args ->
    35  
    36              Class[] paramTypes = MetaClassHelper.castArgumentsToClassArray(args)
    37              MethodSignature signature = method(name, paramTypes)
    38              def intercepted = allowedMethodCallbacks.find { k, v -> k == signature }
    39  
    40              if(intercepted != null)
    41                  StepTracker.add(name)
    42  
    43              return intercepted
    44          }
    45      }
    46  
    47      static void before(String stepName) {
    48  
    49          if(piperStepCallMapping[stepName] == null)
    50              piperStepCallMapping[stepName] = (Set)[]
    51          calls = piperStepCallMapping[stepName]
    52      }
    53  
    54      static void after() {
    55          calls = null
    56          write()
    57      }
    58      static void add (String call) {
    59          calls.add(call)
    60      }
    61  
    62      static private void write() {
    63          Map root = [
    64              piperSteps: piperSteps,
    65              calls: piperStepCallMapping.sort()
    66          ]
    67          new File('target/trackedCalls.json').write(new JsonBuilder(root).toPrettyString())
    68      }
    69  }