Skip to content

Investigate filtering with annotations #14

Open

Description

@marchof

brock_j@SF

It may be useful to tag a method/class as unable to be covered. Elements that are tagged with this annotation will not be instrumented and will be skipped during structure analysis.

The annotation would have to have a retention of 'class' so it doesn't have to be present at runtime. The annotation could eventually be replaced by one provided by the JDK (if one is ever added)

It might be a good idea to actually mark the element as explicitly 'skipped' in reports so the total element counts are accurate.

marchof

We should put this on the list of filtering szenarios. Some concerns:

  • If the annotation is JaCoCo API, we get a dependency from production code to a particular code tool :-(
  • When we have a reasonable set of filtering patterns (e.g. for private, empty default constructors) the annotation requirement might become obsolete.

brock_j@SF

You are correct about the dependency issue. It is a compile time only link, which is slightly better, but probably still not acceptable.

How about something a little bit different?

We don't need to filter out members during instrumentation, instead, it could be done at the reporting/view stage. We could simple provide a file with instructions on what is to be skipped in the report. This would probably fit better with your idea of filtering options. This would just be a 'static' filtering rule (ignore the method called x in class org.example.Foo)

Eclipse integration could mark the ignored elements in some way (perhaps a special annotation of background colour)

brock_j@SF

How common would it be to not want to record coverage information for test classes? Could we look for classes that have test methods defined in them?

Or might we in future want to instrument test classes differently to put extra information into the execution data stream?

marchof

Test cases itself should not be in the scope of the coverage analysis. But as the test implementation typically has a different class path entry it can be easily ignored by the coverage analysis (see JaCoCo coverage report).

What could be useful indeed is a annotation, that defines the scope of a test case (something like @testscope(MyClass.class). When the coverage runtime encounters this annotation e.g. on a method it would track execution information only for the given class(es). This would result in precise 1:1 test coverage data, filtering out all execution data that results from side effects from other tests. Actually for the JaCoCo build I already implemented this on bundle level by specifying an instrumentation filter that for the classes in the bundle under test only (so e.g. report tests do not produce any execution data for the core bundle, even though core classes are heavily used by the tests).

Activity

  1. mchr3k commented on Nov 4, 2012

    @mchr3k

    Filtering by annotations would not be sufficient for my needs as AFAIK annotations can't be added to arbitrary lines of Java source code - only to class/method/field/variable declarations.

    I agree with what johnduffell has said in Issue #15 that comment based exclusions are an ideal way to get to 100% code coverage. The other comments in that thread suggest that a lower enforced target such as 80% would be sufficient but I don't agree with this. Any coverage figure less than 100% is going to be imprecise as in a large code base I could add several new uncovered lines and not change the overall coverage %.

    As I stated in "Enhancement: Coverage exclusions" I am aware that comment processing would be tricky for JaCoCo as comments are not present in bytecode. A cheap NO-OP method call might provide a mechanism that JaCoCo could detect.

    Finally, this issue and Issue #15 seem very similar - perhaps they should be merged?

  2. mchr3k commented on Nov 4, 2012

    @mchr3k

    I should add a couple of things:

    1. Coverage exclusions is the single missing feature which prevents JaCoCo from being really useful for me so I'm keen to see this enhancement progressed.

    2. I might be able to find some time to help implement this feature. Let me know if this would be helpful.

  3. mchr3k commented on Nov 11, 2012

    @mchr3k

    I've made a start looking at the JaCoCo code. Here are my current notes about what needs to be changed to resolve this bug. It would be great to get feedback about this.


    IProbeIdGenerator.nextId() allocates probe IDs. A block of code which has coverage turned off should not include any probes so the callers of this method need to be modified.

    MethodProbesAdapter is the caller of nextId() so should be modified to track whether coverage is turned on/off and only call nextId() when coverage is turned on.

    The results of nextId() get used in MethodAnalzer (at coverage analysis time) and MethodInstrumenter (at code instrumentation time). A special value such as -1 could be used to signal to these classes to act as if there is no probe in these code locations which would normally include a probe.

  4. marchof commented on Nov 11, 2012

    @marchof
    MemberAuthor

    I would prefer to implement filtering only at analysis time - not at instrumentation time - for a couple of reasons:

    • If we drop probes based on filtering settings the Agent as well as the report must be exactly configured the same way, otherwise probe ids will not match
    • No need to configure the runtime agent for filtering
    • Different filtering options possible for the same execution data set
    • Performance isn't an issue. Even today the JaCoCo runtime does not add any significant overhead.

    Also, for many filtering scenarios probes are probably not the right granularity. JaCoCo determines the minimal number of probes to extrapolate the execution of all possible branches. This means that a single probe can be used to flag multiple subsequent branches. The probe insertion strategy is described here: http://www.eclemma.org/jacoco/trunk/doc/flow.html

  5. mchr3k commented on Nov 11, 2012

    @mchr3k

    Thanks for the feedback. Addressing your concerns in turn:

    1. This is a fair concern and a good argument for doing analysis-time filtering.
    2. I'm not imagining that there will be any configuration - the filtered sections will be indicated in the code somehow.
    3. I'll bear this in mind.
    4. I don't think my proposed analysis would add noticeable extra work to the class transformation step.

    My intention is that classes have coverage turned on/off with a particular pattern of bytecode - such as System.setProperty("jacaco", "off").

    For example:

    System.out.println("foo");
    System.setProperty("jacaco", "off");
    if (trickyToHitCondition)
      doSomething();
    System.out.println("bar");
    System.setProperty("jacaco", "on");
    

    I've given it a bit more thought and I think I actually need to insert extra probes before each coverage on/off call. This would allow coverage tracking to respect exclusions. The analyser could then optionally ignore the sections which have coverage turned off.

  6. mchr3k commented on Nov 11, 2012

    @mchr3k

    Hmmm. System.setProperty won't be suitable as the underlying property is stored in a HashTable which has a synchronized put method.

    I really just need a convenient bytecode no-op that won't look too stupid in the source code.

    Perhaps this would be better:

    Runtime.getRuntime().equals("jacoco.off")
    
  7. marchof commented on Nov 12, 2012

    @marchof
    MemberAuthor

    We have many more scenarios for filtering, explicit tagging is just one of them, please see https://github.com/jacoco/jacoco/wiki/FilteringOptions

  8. mchr3k commented on Nov 12, 2012

    @mchr3k

    That's useful context. Presumably not all of those ideas have been implemented?

    I see that one of the ideas is to have a comment based mechanism for turning off coverage. Is there any precedent for the analyser having to parse source code alongside bytecode?

  9. marchof commented on Nov 12, 2012

    @marchof
    MemberAuthor

    Actually none of them are implemented. This is just a collection of requirements and possible solutions. What we need is a pluggable filtering API with default implementations for the common use cases. This API should allow users to write and add custom filters based on their specific requirements.

  10. mchr3k commented on Nov 13, 2012

    @mchr3k

    I've had a go at coming up with an interface which can be used to define these filters. You can see my changes here: mchr3k@0b26b29

    The key approach is to allow an ICoverageFilter to inject a MethodProbesVisitor to monitor the instructions contained in methods. This is sufficient for my immediate purposes but the ICoverageFilter mechanism could be enhanced in future.

    Would you mind quickly reviewing my proposed changes and confirming whether they are likely to have the desired effect?

  11. mchr3k commented on Nov 16, 2012

    @mchr3k

    My current proposed changes uses

    Runtime.getRuntime().equals("jacoco.off")
    

    as a mechanism to turn on/off code coverage. I have chosen this as a relatively concise distinctive line of code which will have no effect. Using a line of code like this means the directive is preserved in the compiled bytecode.

    On reflection, I am concerned that this mechanism is still too awkward compared to directives in comments as per Clover (https://confluence.atlassian.com/display/CLOVER/Using+Source+Directives). In particular I am concerned that it won't be possible to conveniently turn off coverage in a few cases:

    1. For several consecutive methods
    2. For an entire class

    In light of this I think the best solution is to parse the source code at the same time as the bytecode during analysis.

    I'm not sure whether this approach would require the instrumentation phase to be changed to generate a different set of probes.

    What do you think? Would you be happy to accept an implementation which introduced source code parsing during analysis (and possibly during instrumentation if required)?

  12. marchof commented on Nov 16, 2012

    @marchof
    MemberAuthor

    In general I don't like the idea to blur the source code to "improve" code coverage results. But annotations (of retention CLASS) or source comments might still be acceptable in certain cases.

    Creating useless runtime overhead is IMHO not acceptable. JaCoCo should not encourage users to do so.

  13. mchr3k commented on Nov 16, 2012

    @mchr3k

    I'm inclined to agree that useless method calls are a rubbish way of doing this. However, annotations aren't good enough as it is very restrictive where you can place them.

    Here is an example of some code which I would like to exclude from coverage tracking:

    ///CLOVER:OFF because this case is simpler to verify by code read
    if (lFile.isFile() &&
        lFile.getName().endsWith(FILE_EXTN) &&
        !lFile.delete())
    {
      throw new IOException("delete() failed for: " + lFile);
    }
    ///CLOVER:ON
    

    Are you happy for me to pursue a solution which required processing the source code in parallel with the bytecode? Do you have any thoughts about how this will alter probe generation or analysis?

  14. 57 remaining items

  15. jrep commented on Aug 2, 2016

    @jrep

    Interested in the topic, but only at the sub-method granularity (block or line).

  16. SamSoldatenko commented on Oct 15, 2016

    @SamSoldatenko

    Can jacoco have plugin to opt out some coverage data for particular code generators? Like jacoco-skip-groovy-generated-code-coverage, or jacoco-skip-lombock-generated-code-coverage?

  17. andrioli commented on Oct 16, 2016

    @andrioli
    Contributor

    Seems it is a good approach for general method filtering. JaCoCo can provide a SPI for filtering and simply adding a implementation to the classpath should work for remove an entire method from report. (but unfortunately the ServiceLoaded is only available for Java >= 6)

    Now looks that filtering generated bytecode constructs within a method is much harder than simply filtering a entire method.

  18. rjwut commented on Dec 29, 2017

    @rjwut

    It seems like there hasn't been any discussion on this issue in a while, but I would just like to add my support for it. It bugs me that the private constructor on my static utility class is marked as uncovered when it's clearly there to prevent instantiation of the class. I'd love to be able to annotate the constructor to tell JaCoCo to ignore it.

  19. marchof commented on Dec 31, 2017

    @marchof
    MemberAuthor

    @rjwut Your specific requirement will be part of the next release: #529

  20. pgelinas commented on Mar 22, 2018

    @pgelinas

    Is there anything that can be done to help getting this feature in? I'm very much interested in having a way, either annotation or comment tag, to manually exclude some part of the code from coverage. I haven't found any clear consensus reading the whole thread (well, most of it) and the wiki page for filtering.
    I understand that it would be implemented at analysis-time, is there some part of the code I can start looking to help you with it? I'd say filtering the report based on a comment might be the lowest hanging fruit, where should I start looking? Or is it still undecided whether to implement this? I really really want to help you guys make it happen 😃

  21. cal101 commented on May 22, 2018

    @cal101

    Hi!

    I am interested in filtering out code by source code comments.
    I read the whole ticket history and after @mchr3k experiments I see only the comment of @Godin
    that there is no agreement between mchr3k, Godin and @marchof about whether using source code comments is an acceptable solution.
    Did you actually discuss the matter and what is the outcome?
    Annotations would cover a lot of the cases we have but not all, especially not catch blocks.

  22. almondtools commented on Aug 3, 2020

    @almondtools

    Now - lombok.Generated Annotations are already excluded from coverage. So exclusion by annotation seems to be possible.

    Yet the documentation says to use @Generated only for generated code. I agree, yet what shall I use to exclude a non generated class. Of course one could put an exclude into the pom.xml, but this will be quite confusing for the developers that want to understand why some class is not reported.

  23. pbludov commented on Nov 27, 2021

    @pbludov

    @marchof is there a chance that #117 can be solved with a filter?

  24. marchof commented on Nov 27, 2021

    @marchof
    MemberAuthor

    @pbludov Probably. But I cannot imagine why anyone is interested in getting code coverage for System.exit() calls. We will definitely not invest time on such a feature.

  25. pbludov commented on Nov 27, 2021

    @pbludov

    We want to keep the coverage at 100%. Before the JDK17 comes, it was possible to mock System.exit() and prove that all the lines are covered by tests. For example, this code has 50% coverage:

    public static void main(String... args) {
      System.exit(1);
      // This line is reported as uncovered because System.exit() will never return
    }

    As a workaround it is possible to extract this call to a helper class:

    public static void main(String... args) {
      ExitHelper.exit(1);
    }
    
    // This class is excluded from the coverage report
    private static class  ExitHelper {
      private void exit(int code) {
        System.exit(code);
      }
    }
  26. hjohn commented on Feb 4, 2022

    @hjohn

    Just wanted to share my use case for wanting such a feature. First, I'm not aiming for 100% coverage, but there are lines that should never be covered or are uncoverable. Typically these are assertions that would signal a serious problem in the code if they're ever triggered. If I knew of a way to trigger them (in order to get coverage) that would be a bug and after the bug is fixed they would again be uncoverable.

    Some classes can have complicated logic and therefore may have quite a few assertions in them resulting in poor coverage.

    Some examples:

    private void removeInternal(T qualifiedType) {
      try {
        for(Class<?> type : Types.getSuperTypes(TypeUtils.getRawType(qualifiedType.getType(), null))) {
          if(type != Provider.class) {
            unregister(type, null, qualifiedType);
    
            for(Annotation qualifier : qualifiedType.getQualifiers()) {
              unregister(type, qualifier, qualifiedType);
            }
          }
        }
      }
      catch(Exception e) {
        throw new AssertionError("Fatal exception (store might be inconsistent) while removing: " + qualifiedType, e);
      }
    }
    
    private void unregister(Class<?> type, Annotation qualifier, T qualifiedType) {
      Map<Annotation, Set<T>> qualifiedTypesByQualifier = qualifiedTypesByQualifierByType.get(type);
    
      if(qualifiedTypesByQualifier == null) {
        throw new AssertionError("Store must contain: " + qualifiedType + " for class: " + type);
      }
    
      Set<T> qualifiedTypes = qualifiedTypesByQualifier.get(qualifier);
    
      if(qualifiedTypes == null || !qualifiedTypes.remove(qualifiedType)) {
        throw new AssertionError("Store must contain: " + qualifiedType + " for class: " + type + " -> " + qualifier + " qualified types: " + qualifiedTypes);
      }
    
      if(qualifiedTypes.isEmpty()) {
        qualifiedTypesByQualifier.remove(qualifier);
    
        if(qualifiedTypesByQualifier.isEmpty()) {
          qualifiedTypesByQualifierByType.remove(type);
        }
      }
    }
    

    All the above code is called only after making sure all invariants can be met. If this check is buggy, an exception that shouldn't trigger will trigger. All the catch blocks that throw an AssertionError cannot be covered unless:

    • I mock certain stuff to return things they normally never could -- this is bad, as the tests then give the impression that it is actually valid input while it isn't
    • I make the method accessible from outside the class so I can provide it with input it normally could never receive -- bad as I don't want to break encapsulation (even a little) for tests, not to mention that it again would be testing input that is impossible during normal operation
    • I discover a bug in the logic -- such a test would be written, but would also promptly be fixed

    I was hoping it would be possible to configure Jacoco to automatically ignore any code blocks (or catch blocks) where an AssertionError is thrown. Something similar applies to the assert keyword, except I'm not comfortable using that as the check can be switched off.

  27. moved this to Awaiting triage in Filteringon Jul 11, 2024
  28. realdadfish commented on Jul 1, 2026

    @realdadfish

    I'd also love to see this, but I would not add a tool-specific annotation, but a way to configure your own annotation inside the build configuration, e.g. for Gradle

    jacoco {
        ...
        ignoreCodeInstrumentationAnnotation = "my.package.IgnoreCoverage"
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    • Status
      Awaiting triage

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions