Java Code Coverage Mechanics

Similar documents
Java Code Coverage Mechanics. by Evgeny Mandrikov at EclipseCon Europe 2017

Java Code Coverage Mechanics Evgeny Mandrikov Marc Hoffmann #JokerConf 2017, Saint-Petersburg

The Future of Code Coverage for Eclipse

Are You Covered? Keith D Gregory Philly JUG 14 October 2009

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Class, Variable, Constructor, Object, Method Questions

Java Security. Compiler. Compiler. Hardware. Interpreter. The virtual machine principle: Abstract Machine Code. Source Code

Java Instrumentation for Dynamic Analysis

CSE P 501 Compilers. Java Implementation JVMs, JITs &c Hal Perkins Winter /11/ Hal Perkins & UW CSE V-1

Chapter 12 Exception Handling and Text IO. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

Space Exploration EECS /25

What is software testing? Software testing is designing, executing and evaluating test cases in order to detect faults.

A Quantitative Evaluation of the Contribution of Native Code to Java Workloads

Under the Hood: The Java Virtual Machine. Lecture 23 CS2110 Fall 2008

Implement detection of duplicate test coverage for Java applications

Agenda. CSE P 501 Compilers. Java Implementation Overview. JVM Architecture. JVM Runtime Data Areas (1) JVM Data Types. CSE P 501 Su04 T-1

Java Errors and Exceptions. Because Murphy s Law never fails

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong:

Programming with assertions Oracle guidelines

JVML Instruction Set. How to get more than 256 local variables! Method Calls. Example. Method Calls

Exception Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong:

CS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question)

Compiling Techniques

CS2110 Fall 2011 Lecture 25. Under the Hood: The Java Virtual Machine, Part II

301AA - Advanced Programming [AP-2017]

Motivations. Chapter 12 Exceptions and File Input/Output

Program Dynamic Analysis. Overview

3/15/18. Overview. Program Dynamic Analysis. What is dynamic analysis? [3] Why dynamic analysis? Why dynamic analysis? [3]

Exceptions. What exceptional things might our programs run in to?

Chapter 9. Exception Handling. Copyright 2016 Pearson Inc. All rights reserved.

Programming II (CS300)

1 Shyam sir JAVA Notes

Shared Mutable State SWEN-220

Dynamic Class Loading

COE318 Lecture Notes Week 10 (Nov 7, 2011)

Programming II (CS300)

Problem: Too Many Platforms!

Deriving Code Coverage Information from Profiling Data Recorded for a Trace-based Just-in-time Compiler

Chapter 3 Java Exception

Compiler construction 2009

Vendor: Oracle. Exam Code: 1Z Exam Name: Java Certified Programmer. Version: Demo

CS159. Nathan Sprague

Multitasking Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between: Process-based multit

Let s make some Marc R. Hoffmann Eclipse Summit Europe

Living in the Matrix with Bytecode Manipulation

Course Overview. PART I: overview material. PART II: inside a compiler. PART III: conclusion

Static Analysis of Dynamic Languages. Jennifer Strater

Improving Java Performance

Improving Java Code Performance. Make your Java/Dalvik VM happier

Code Profiling. CSE260, Computer Science B: Honors Stony Brook University

BBM 102 Introduction to Programming II Spring Exceptions

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Compilation 2012 Code Generation

JAVA MOCK TEST JAVA MOCK TEST III

SECTION-1 Q.1.Which two code fragments are most likely to cause a StackOverflowError? (Choose two.)

Getting started with Java

Inheritance. Notes Chapter 6 and AJ Chapters 7 and 8

Fundamentals of Object Oriented Programming

More on Exception Handling

CMSC 433 Section 0101 Fall 2012 Midterm Exam #1

CSCE 314 Programming Languages

CS 11 java track: lecture 1

More on Exception Handling

Advances in Programming Languages: Generics, interoperability and implementation

Lecture 28. Exceptions and Inner Classes. Goals. We are going to talk in more detail about two advanced Java features:

Selected Questions from by Nageshwara Rao

Introduction Basic elements of Java

GuideTorrent. The best excellent exam certification guide torrent and dumps torrent provider

CIS 120 Final Exam 15 December 2017

02 B The Java Virtual Machine

Assertions, pre/postconditions

Note: Answer any five questions. Sun micro system officially describes java with a list of buzz words

Nested Classes in Java. Slides by: Alon Mishne Edited by: Eran Gilad, Eyal Moscovici April 2013

Compiling for Different Platforms. Problem: Too Many Platforms! Dream: Platform Independence. Java Platform 5/3/2011

Review what constitutes a thread Creating threads general Creating threads Java What happens if synchronization is not used? Assignment.

Compiling Faster, Compiling Better with Falcon. Iván

Under the Hood: The Java Virtual Machine. Problem: Too Many Platforms! Compiling for Different Platforms. Compiling for Different Platforms

Nu: Towards a Flexible and Dynamic Aspect- Oriented Intermediate Language Model

Synchronization SPL/2010 SPL/20 1

Chapter 1: Introduction to Computers, Programs, and Java

Lecture 1: Overview of Java

Checking Current Code Coverage

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

Portable Resource Control in Java The J-SEAL2 Approach

S.E. Sem. III [CMPN] Object Oriented Programming Methodology

15CS45 : OBJECT ORIENTED CONCEPTS

Java language. Part 1. Java fundamentals. Yevhen Berkunskyi, NUoS

Exception-Handling Overview

Test-Driven Development (a.k.a. Design to Test) CSE260, Computer Science B: Honors Stony Brook University


Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

The Java Language Implementation

20 Most Important Java Programming Interview Questions. Powered by

CS11 Advanced Java. Winter Lecture 2

Just-In-Time Compilation

SOFTWARE ARCHITECTURE 7. JAVA VIRTUAL MACHINE

Java Class Loading and Bytecode Verification

Classes Classes 2 / 36

Java classes cannot extend multiple superclasses (unlike Python) but classes can implement multiple interfaces.

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

Transcription:

at by Evgeny Mandrikov Java Code Coverage Mechanics #DevoxxFR

Evgeny Mandrikov @_Godin_.com/Godin one of JaCoCo and Eclipse EclEmma Project Leads

Disclaimer /* TODO don't forget to add huge disclaimer that All opinions hereinbelow are my own and not my employers. They can only dream that they own them. */

Java Code Coverage Mechanics

Java Code Coverage Mechanics

Java Code Coverage Mechanics

Java Code Coverage Mechanics

Real Disclaimer Blood and guts of JVM Strong language - bytecode Intense violence for brain Implementation details!!!

EMMA 1. x EclEmma 1.x 2.x 3.x JaCoCo 2004 5 2005 2006 2007 6 2008 2009 2010 2011 7 2012 2013 2014 8 2015 2016 2017 9

Observer Effect In physics, the term observer effect refers to changes that the act of observation will make on a phenomenon being observed. This is often the result of instruments that, by necessity, alter the state of what they measure in some manner. Wikipedia

Code Coverage runtime profiling JVMPI instrumentation JVMTI source bytecode offline on-the-fly

JaCoCo works on class files only Instrumentation *.class Execution *.exec Analysis

As easy as setting an arg for the JVM java -javaagent:jacocoagent.jar[=options] Application class PreMain { public static void premain( String options, Instrumentation instrumentation ) throws Exception { instrumentation.addtransformer( );

JaCoCo Validation Test Suite

Tested on 5 major JDK versions

Not only issues in JaCoCo...

Probes

Probe Minimal runtime overhead No side effects on application code Thread safe Record execution Identification probes[id] = true; ALOADx probes xpush id ICONST_1 BASTORE

Bytecode of Assertions class Fun { void fun(boolean x) { assert x; // javap -c Fun L: getstatic $assertionsdisabled ifne L iload_1 ifne L new java/lang/assertionerror dup invokespecial <init>()v athrow return

Bytecode of Assertions class Fun { static final synthetic boolean $assertionsdisabled = Fun.class.desiredAssertionStatus(); void fun(boolean x) { if (! $assertionsdisabled) if (! x) throw new AssertionError();

Nice idea! class Fun { static final synthetic boolean[] $jacocodata = ; void fun() { boolean[] probes = $jacocodata; probes[0] = true; probes[ ] = true;

Bridge Methods class Outer { private int counter; class Inner { void inc() { counter++; // javap -v Outer synthetic static private int access$008(outer o) { return o.counter++; // javap -c Outer$Inner synthetic final Outer this$0; void inc() { Outer.access$008(this$0)

Methods in Enums enum Fun { C // javap -v Fun synthetic static Fun valueof(java.lang.string); synthetic static Fun[] values();

Lambdas class Fun { void exec(runnable task) { task.run(); void fun() { exec(() -> { ); // javap -c -p -l Fun private static synthetic lambda$fun$0() {

ASM // javac -version java version "9-ea" // javac Fun.java // javap -version 1.7.0_80 new ClassReader(classBytes) // IllegalArgumentException return downgrade(classbytes)? upgrade(transform(classbytes)) : transform(classbytes); // javap -v Fun major version: 53 // javap -c -XDdetails -cp bin:src Example

Bad Cycle class Child extends Base { void somemethod() { assert 1 == 2; class Base { static { new Child().someMethod(); public static void main(string[] args) { new Child();

Bad Cycle (problem) class Fun { static final synthetic boolean[] $jacocodata = ; void fun() { boolean[] probes = $jacocodata; probes[0] = true; // NullPointerException probes[ ] = true;

Bad Cycle (solution) class Fun { static final synthetic boolean[] $jacocodata; static synthetic boolean[] $jacocoinit() { if ($jacocodata == null) $jacocodata = ; return $jacocodata; void fun() { boolean[] probes = $jacocoinit();

Java Virtual Machine Specification 6.5. putstatic if the field is final, it must be declared in the current class, and the instruction must occur in the <clinit> method of the current class. Otherwise, an IllegalAccessError is thrown Checked in JDK 9 EA b127 for class files version 53.

Bad Cycle (correct solution) class Fun { static final synthetic boolean[] $jacocodata; static synthetic boolean[] $jacocoinit() { if ($jacocodata == null) $jacocodata = ; return $jacocodata; void fun() { boolean[] probes = $jacocoinit();

Interfaces interface Fun { static final Object field; static { field = ; interface Fun { default method() { // oups???

Java Language Specification 12.4.1. When Initialization Occurs A class or interface type T will be initialized immediately before the first occurrence of any one of the following: an instance of T is created static method declared by T is invoked When a class is initialized, its superclasses are initialized, as well as any superinterfaces that declare any default methods. Initialization of an interface does not, of itself, cause initialization of any of its superinterfaces.

Bad Cycle with Interfaces interface Base { Object o = new Child(){.someMethod(); default void base() { // JLS 12.4.1 interface Child extends Base { Object o = new Object() { { println( clinit ); ; default Object somemethod() { throw...; public static void main(string[] args) { new Child(){; // or Child.staticMethod();

Bad Cycle with Interfaces (problem) base clinit child method child clinit < JDK 8u40 <= class: child clinit base clinit child method + crash because of exception static: base clinit child method child clinit < JDK 8u152 EA <= child clinit base clinit child method

Bad Cycle with Interfaces (solution) interface Fun { static final synthetic boolean[] $jacocodata = ; static synthetic boolean[] $jacocoinit() { return $jacocodata == null? // slow path without assignment for JDK < 8u152 : $jacocodata ; default void fun() { boolean[] probes = $jacocoinit();

Class Identification Class c1 = ; Class c2 = ; ( c1.getname() ).equals( c2.getname ) is c1 the same as c2??? long classid = CRC64(classBytes);

Runtime Access class RestrictiveClassLoader extends ClassLoader { protected Class<?> loadclass(string name, boolean resolve) throws ClassNotFoundException { if (!name.startswith("java/") &&!name.startswith("org/sonarsource/")) throw new ClassNotFoundException(); return super.loadclass(name, resolve);

Runtime Access (Problem) boolean[] probes =??? ; // Oups // can use only classes // java/**

Runtime Access (Solution) Object access = java.util.uuid.$jacocoaccess; // created at agent startup Object[] args = new Object[] { classid, // Long classname, // String probescount // Integer ; access.equals(args); boolean[] probes = (boolean[]) args[0];

Get Involved and Have Fun https://jdk9.java.net/download/ https://groups.google.com/forum/#!forum/jacoco StackOverflow https://github.com/eclipse/eclemma https://github.com/jacoco/jacoco

Principles and Best Practices Don t care about percentage value, observe the amount of untested code Focus on coverage of modified and new code Make coverage analysis an inherent part of your build/test chain Make coverage reports available to everybody in the team But not the management! Always go for functional coverage when writing tests Just executing code will not improve its quality!

Common Pitfalls and how to avoid them Different Class Files runtime/analysis (recall class ids) different compiler implementations different compiler versions different compiler settings Pack200 Different version of the same class in same group Not graceful JVM termination Reflection (recall synthetic fields and methods) Pre-instrumentation requires direct dependency on the JaCoCo runtime Interoperability with PowerMock overrides JaCoCo init method might bypass agents, because reads class files as resources