List of methods if their implementation has at least two occurences of a word 'assert' in Smalltalk

69 Views Asked by At

I wanted to get the list of methods of a class if their implementation has at least two occurrences of a word 'assert' in Smalltalk.

Can somebody help me with this? Thanks in advance!

1

There are 1 best solutions below

2
On BEST ANSWER

I'm not sure about the details of gnu-Smalltalk, but in Pharo, you can do something like this:

YourClass methods select: [ :method |
    method sourceCode matchesRegex: '.*assert.*assert.*'. ]

Here I use a trivial regex to see if I can match two "assert" words in the source code.

However, with Smalltalk, it's easy to do more precise searches. Image, you want to see if a method sends at least two assert: messages. You can find such methods this way:

YourClass methods select: [ :method |
    | numAsserts |
    numAsserts := method ast allChildren count: [ :node |
        node isMessage and: [ node selector = #assert: ] ].
    numAsserts >= 2
]

In the example above, for each method, we simply count the number of AST nodes that are message sends, and have the assert: selector. Then we check if the number of these nodes is greater or equal to 2.