SlideShare a Scribd company logo
1 of 64
Download to read offline
<Insert Picture Here>




Code coverage.
The pragmatic approach.
Александр Ильин
Java Quality architect
Oracle
What it is about?
Should the testing be stopped at 100% coverage?
Should 100% be the goal?
How (else) to use code coverage information?



 What it is not about?
Tools



                                                  2
<Insert Picture Here>



Preface
What is the code coverage data for

Measure to which extent source code is covered
during testing.
                               consequently …
 Code coverage is
A measure of how much source code is covered
during testing.
                               finally …
 Testing is
A set of activities aimed to prove that the system under
test behaves as expected.



                                                       4
CC – how to get

 • Create a template
Template is a collection of all the code there is to cover
 • “Instrument” the source/compiled code/bytecode
Insert instructions for dropping data into a file/network, etc.
 • Run testing, collect data
May need to change environment
 • Generate report
HTML, DB, etc



                                                             5
CC – kinds of

• Block / primitive block
• Line
• Condition/branch/predicate
• Entry/exit
• Method
• Path/sequence




                               6
CC – how to use
                           for testbase improvement

 • 1: Measure (prev. slide)
Performed repeatedly, so resource-efficiency is really important
 • Perform analysis
Find what code you need to cover.
Find what tests you need to develop.
 • Develop more tests

 • Find dead code

 • GOTO 1


                                                         7
<Insert Picture Here>



Mis-usages
CC – how not to use
                            mis-usages
 • Must get to 100%
May be not.
 • 100% means no more testing
No it does not.
 • CC does not mean a thing
It does mean a fair amount if it is used properly.
 • There is that tool which would generate tests
   for us and we're done
Nope.


                                                     9
<Insert Picture Here>



Mis-usages
Test generation
Test generation


“We present a new symbolic execution tool, ####,
capable of automatically generating tests that
achieve high coverage on a diverse set of complex
and environmentally-intensive programs.”
                           #### tool documentation
Test generation cont.


if ( b != 3 ) {
    double a = 1 / ( b – 2);
} else {
    …
}
Test generation cont.


if ( b != 3 ) {
    double a = 1 / ( b – 3);
} else {
    …
}


Reminder: testing is ...
A set of activities aimed to prove that the system under
test behaves as expected.
Test generation - conclusion

Generated tests could not test that the code work
as expected because they only know how the code
works and not how it is expected to. Because the
only thing they possess is the code which may
already be not working as expected. :)

Hence …

Generated tests code coverage should not be
mixed with regular functional tests code coverage.


                                                     14
Who watches the watchmen?


• Test logic gotta be right
• No way to verify the logic
   • No metrics
   • No approaches
   • No techniques
   • Code review – the only way
• Sole responsibility of test developer
<Insert Picture Here>



Mis-usages
What does 100% coverage mean?
100% block/line coverage

                           1




                           false
100% branch coverage

                       1      -1




                       true   false
100% domain coverage

                       0   .1   -.1




                       0   .1    Exception
100% sequence coverage




                   (-1,-1)




                             (1,1)
                                     (0,0)
            b




                    1         1        NaN
100% sequence coverage




                              (-1,-1)
                                        (-1,1)
                                                 (1,-1)
                                                          (1,1)
                                                                  (0,0)
                    b




                              1          -1       -1       1        NaN
But … isPositive(float) has a defect!
100% sequence coverage


• Has conceptual problems
   • Code semantics
   • Loops
• One of the two
  • Assume libraries has no errors
  • Done in depth – with the libraries
• Very expensive
   • A lot of sequences: 2# branches, generally speaking
   • Very hard to analyze data
100% coverage - conclusion

100% block/line/branch/path coverage, even if
reachable, does not prove much.

Hence …

No need to try to get there unless ...




                                                23
<Insert Picture Here>



Mis-usages
Target value
CC target value - cost
                                                                                                Test Dev. Effort by Code Block Coverage.
Industry data
indicates that effort                                                               90.00
increases
exponentially with                                                                  80.00
coverage.
                         Relative Test Dev. Effort (1 at 50% code block coverage)



                                                                                    70.00
We scale to make
effort relative to the
effort of getting 50%                                                               60.00
coverage.
                                                                                    50.00           f  x =k e r x
Intuition: the effort
needed to get more                                                                                  k =e−50r ⇒ f 50=1
                                                                                    40.00
coverage is
                                                                                                    df
proportional to the                                                                                    =r f  x 
                                                                                    30.00           dx
total effort needed to
get current coverage.
                                                                                    20.00
Model not reliable
below 50% coverage,                                                                 10.00
except maybe very big
projects.                                                                            0.00
                                                                                            0   5   10     15         20   25   30   35    40   45    50   55   60   65   70   75   80   85   90   95   100


                                                                                                                                          Code Block Coverage (%)
CC target value - effectiveness
                                                              Defect Coverage by Code Block Coverage

Defect coverage by                               120.00
code block coverage...

def ned in terms of
   i                                             100.00
effort per code coverage
and defect coverage by
effort.                                                                 H  x =h  f  x 
                                                 80.00
                                                                        f  x =k e r x
                            Defect Coverage(%)




Intuition: discovery rate                                                                 −
                                                                                              s
                                                                                                y
                                                                                              B
is proportional to the                                                  h  y = B1−e              
percentage of bugs                               60.00
remaining and the effort                                                dH        H  x  df
                                                                           =s 1−         x
needed to get current                                                   dx         B dx
coverage.                                        40.00


Model not reliable below
50% coverage except                              20.00
maybe very big projects.

                                                   0.00
                                                          0    5   10      15     20      25            30   35   40   45   50   55   60   65   70   75   80   85   90   95   100


                                                                                                             Code Block Coverage(%)
CC target value - ROI
                                                                                                                                                           Benef t(c) = DC(c) DD COD, where
                                                                                                                                                               i
                                                                                                                                                           DC(c): Defect Coverage
                                                                       Cost-Benefit Analysis                                                               DD: Defect Density. Example:
                                                                                                                                                           50bug/kloc
                                           1200.00                                                                                                         COD: Cost Of Defect. Example:
                                                                                                                                                           $20k/bug
                                           1000.00



                                            800.00
Benefit ($/size), Cost ($/size), ROI (%)




                                                                                                                                                              ROI = Benef t(c)/ Cost(c) - 1
                                                                                                                                                                        i
                                            600.00



                                            400.00



                                            200.00



                                              0.00
                                                                                                                                                              Cost(c) = F + V * RE(c), where
                                                                                                                                                              RE(c): Relative Effort, RE(50%) = 1
                                                                                                                                                              F: Fixed cost of test. Example:
                                           -200.00                                                                                                            $50k/kloc
                                                     0   5   10   15   20   25   30   35   40   45   50   55   60   65   70   75   80   85   90   95 100
                                                                                                                                                              V: Variable cost of test. Example:
                                                                                                                                                              $5k/kloc
                                                                                  Code Block Coverage (%)
100% coverage - conclusion

100% block/line/branch/path coverage, even if
reachable, does not prove much.

Hence …

No need to try to get there unless …
                            100% is the target value.

Which could happen if cost of a bug is really big
and/or the product is really small.


                                                    28
Target value - conclusion

True target value for block/line/branch/path comes
from ROI, which is really hard to calculate and
justify.




                                                     29
<Insert Picture Here>



Usages
CC – how to use

 • Test base improvement.
Right. How to select which tests to develop first
 • Dead code.
Barely an artifact
 • Metric
Better have a good metric.
 • Control over code development

 • Deep analysis



                                                    31
<Insert Picture Here>



CC as a metric
What makes a good metric

Simple to explain
So that you could explain your boss why is that important
to spend resources on
Simple to work towards
So that you know what to do to improve

Has a clear goal
So you could tell how far are you.
Is CC a good metric?

Simple to explain +
Is a metric of quality of testing.


Simple to work towards +
(Relatively) easy to map uncovered code to missed tests.


Has a clear goal -
Nope. ROI – too complicated.

Need to filter the CC data
so only that is left which must be covered
Public API*

Is a set of program elements suggested for usage by
public documentation.

For example: all functions and variables which are
described in documentation.

For a Java library: all public and protected methods and
fields mentioned in the library javadoc.

For Java SDK: … of all public classes in java and javax
packages.
                     (*) Only applicable for a library or a SDK
Public API
True Public API (c)

Is a set of program elements which could be accessed
directly by a library user

Public API
+
all extensions of public API in non-public classes
True public API example



   My code




                          ArrayList.java
True Public API how to get


• Get public API with interfaces
• Filter template so that it only contains implementations
  and extensions of the public API (*)
• Filter the data by template


(*) This assumes that you either
• Use a tool which allows such kind of filtering
or
• Have the data in a parse-able format and develop the
  filtering on your own
UI coverage

In a way, equivalent to public API but for a UI product

• %% of UI elements shown – display coverage
• %% user actions performed – action coverage



Only “action coverage” could be obtained from CC data (*).



(*) For UI toolkits which the presenter is familiar with.
Action coverage – how to get

• Collect CC
• Extract all implementations of
javax.swing.Action.actionPerformed(ActionEvent)
or
javafx.event.EventHandler.handle(Event)
• Inspect all the implementations
org.myorg.NodeAction.actionPerformed(ActionEvent)
• Add to the filter:
org.myorg.NodeAction.nodeActionPerformed(Node myNode)
• Extract, repeat
“Controller” code coverage


Model
Contains the domain logic
View
Implements user interaction
Controller
Maps the two. Only contains code which is called as a
result of view actions and model feedbacks.

Controller has very little boilerplate code. A good
candidate for 100% block coverage.
“Important” code


• Development/SQE marks class/method as important
   • We use an annotation @CriticalForCoverage
• List of methods is obtained which are marked as
 important
  • We do that by an annotation processor right while main
    compilation
• CC data is filtered by the method list
• Goal is 100%
Examples of non-generic metrics


• BPEL elements
• JavaFX properties
   • A property in JavaFX is something you could set, get and bind
• Insert your own.
CC as a metric - conclusion

There are multiple ways to filter CC data to a set of
code which needed to be covered in full.

There are generic metrics and there is a possibility
to introduce product specific metric.

Such metrics are easy to use, although not always
so straightforward to obtain.




                                                    45
<Insert Picture Here>


Test prioritization
Test prioritization

 100500 uncovered lines of code!

 “OMG! Where do I start?”


 Metric
   • Develop tests to close the metric
   • Pick another metric

“Metrics for managers. Me no manager! Me write code!”

 Consider mapping CC data to few other source code
 characteristics.
Age of the code


New code is better be tested before getting to customer.
Improves bug escape rate, BTW



Old code is more likely to be tested by users
or
Not used by users.
What's a bug escape metric?

Ratio of defects sneaked out unnoticed

                # defects not found before release
In theory:
                      # defects in the product


                   # defects found after release
Practical:
             # defects found after + # defects found before
Number of changes


More times a piece of code was changed, more atomic
improvements/bugfixes were implemented in it.

Hence …

Higher risk of introducing a regression.
Number of lines changed


More lines changed – more testing it needs.



Better all – number of uncovered lines which were
changed in the last release.
Bug density


Assuming all the pieces were tested equally well …

Many bugs means there are, probably, even more
  • Hidden behind the known ones
  • Fixing existing ones may introduce yet more as regressions
Code complexity


Assuming the same engineering talent and the same
technology …

More complex the code is – more bugs likely to be there.

Any complexity metric would work: from class size to
cyclomatic complexity
Putting it together


A formula
(1 – cc) * (a1*x1 + a2*x2 + a3*x3 + ...)
Where
cc – code coverage (0 - 1)
xi – a risk of bug discovery in a piece of code
ai – a coefficient
Putting it together


(1 – cc) * (a1*x1 + a2*x2 + a3*x3 + ...)
The ones with higher value are first to cover

• Fix the coefficients
• Develop tests
• Collect statistics on bug escape
• Fix the coefficient
• Continue
Test prioritization - conclusion

CC alone may not give enough information.

Need to accompany it with other characteristics of
test code to make a decision.

Could use a few of other characteristics
simultaneously.




                                                     56
<Insert Picture Here>


Test prioritization
Execution
Decrease test execution time


Exclude tests which do not add coverage (*).

But, be careful! Remember that CC is not all and even
100% coverage does not mean a lot.

While excluding tests get some orthogonal measurement
as well, such as specification coverage.

(*) Requires “test scales”
Deep analysis


Study the coverage report, see what test code exercises
which code. (*).

Recommended for developers.

(*) Also requires “test scales”
Controlled code changes


Do not allow commits unless all the new/changed code is
covered.

Requires simultaneous commits of tests and the
changes.
Code coverage - conclusion

100% CC does not guarantee that the code is working right

100% CC may not be needed

It is possible to build good metrics with CC

CC helps with prioritization of test development

Other source code characteristics could be used with CC


                                                   61
Coverage data is not free


• Do just as much as you can consume *
   • Requires infrastructure work
   • Requires some development
   • Requires some analysis




(*) The rule of thumb
Coverage data is not free


• Do just as much as you can consume
   • Requires infrastructure work
   • Requires some development
   • Requires some analysis
• Do just a little bit more than you can consume *
   • Otherwise how do you know how much you can consume?




(*) The rule of thumb
<Insert Picture Here>




Code coverage.
The pragmatic approach.
Александр Ильин
Java Quality architect
Oracle

More Related Content

Viewers also liked

Использование метрик в процессе обеспечения качества сложных систем
Использование метрик в процессе обеспечения качества сложных системИспользование метрик в процессе обеспечения качества сложных систем
Использование метрик в процессе обеспечения качества сложных системSQALab
 
Monthly Operations Review
Monthly Operations ReviewMonthly Operations Review
Monthly Operations ReviewSQALab
 
Метрики автоматизированного тестирования на пальцах
Метрики автоматизированного тестирования на пальцахМетрики автоматизированного тестирования на пальцах
Метрики автоматизированного тестирования на пальцахSQALab
 
Как оценить тестировщика
Как оценить тестировщикаКак оценить тестировщика
Как оценить тестировщикаSQALab
 
Когда стоит закончить автоматизировать?
Когда стоит закончить автоматизировать?Когда стоит закончить автоматизировать?
Когда стоит закончить автоматизировать?SQALab
 
От ручного тестирования к автоматическому: опыт внедрения в крупном проекте
От ручного тестирования к автоматическому: опыт внедрения в крупном проектеОт ручного тестирования к автоматическому: опыт внедрения в крупном проекте
От ручного тестирования к автоматическому: опыт внедрения в крупном проектеSQALab
 
Мини-школа тестировщиков, ориентированных на Web
Мини-школа тестировщиков, ориентированных на WebМини-школа тестировщиков, ориентированных на Web
Мини-школа тестировщиков, ориентированных на WebSQALab
 
Оптимизация процесса тестирования локализаций
Оптимизация процесса тестирования локализацийОптимизация процесса тестирования локализаций
Оптимизация процесса тестирования локализацийSQALab
 
Как эффективно организовать Автоматизацию, если у вас недостаточно времени, р...
Как эффективно организовать Автоматизацию, если у вас недостаточно времени, р...Как эффективно организовать Автоматизацию, если у вас недостаточно времени, р...
Как эффективно организовать Автоматизацию, если у вас недостаточно времени, р...SQALab
 
Как найти побольше багов? (Особенно, если времени нет)
Как найти побольше багов? (Особенно, если времени нет)Как найти побольше багов? (Особенно, если времени нет)
Как найти побольше багов? (Особенно, если времени нет)SQALab
 
Модель компетенций в оценке, обучении и развитии специалиста по тестированию
Модель компетенций в оценке, обучении и развитии специалиста по тестированиюМодель компетенций в оценке, обучении и развитии специалиста по тестированию
Модель компетенций в оценке, обучении и развитии специалиста по тестированиюSQALab
 
Путь к трассировке требований: от идеи к инструменту
Путь к трассировке требований: от идеи к инструментуПуть к трассировке требований: от идеи к инструменту
Путь к трассировке требований: от идеи к инструментуSQALab
 
Пример эффективного управления тест-кейсами при помощи Google docs
Пример эффективного управления тест-кейсами при помощи Google docsПример эффективного управления тест-кейсами при помощи Google docs
Пример эффективного управления тест-кейсами при помощи Google docsSQALab
 
Организация времени в тестировании
Организация времени в тестированииОрганизация времени в тестировании
Организация времени в тестированииSQALab
 
Keyword-driven framework
Keyword-driven frameworkKeyword-driven framework
Keyword-driven frameworkSQALab
 
Система генерации чек-листов для регрессионного тестирования на основе анализ...
Система генерации чек-листов для регрессионного тестирования на основе анализ...Система генерации чек-листов для регрессионного тестирования на основе анализ...
Система генерации чек-листов для регрессионного тестирования на основе анализ...SQALab
 
Использование Open Source инструментов для автоматизации тестирования
Использование Open Source инструментов для автоматизации тестированияИспользование Open Source инструментов для автоматизации тестирования
Использование Open Source инструментов для автоматизации тестированияSQALab
 
Не баг-трекер, а ...
Не баг-трекер, а ...Не баг-трекер, а ...
Не баг-трекер, а ...SQALab
 
Как принести пользу разработке и упростить себе жизнь?
Как принести пользу разработке и упростить себе жизнь?Как принести пользу разработке и упростить себе жизнь?
Как принести пользу разработке и упростить себе жизнь?SQALab
 

Viewers also liked (20)

Использование метрик в процессе обеспечения качества сложных систем
Использование метрик в процессе обеспечения качества сложных системИспользование метрик в процессе обеспечения качества сложных систем
Использование метрик в процессе обеспечения качества сложных систем
 
Monthly Operations Review
Monthly Operations ReviewMonthly Operations Review
Monthly Operations Review
 
Метрики автоматизированного тестирования на пальцах
Метрики автоматизированного тестирования на пальцахМетрики автоматизированного тестирования на пальцах
Метрики автоматизированного тестирования на пальцах
 
Как оценить тестировщика
Как оценить тестировщикаКак оценить тестировщика
Как оценить тестировщика
 
Когда стоит закончить автоматизировать?
Когда стоит закончить автоматизировать?Когда стоит закончить автоматизировать?
Когда стоит закончить автоматизировать?
 
От ручного тестирования к автоматическому: опыт внедрения в крупном проекте
От ручного тестирования к автоматическому: опыт внедрения в крупном проектеОт ручного тестирования к автоматическому: опыт внедрения в крупном проекте
От ручного тестирования к автоматическому: опыт внедрения в крупном проекте
 
Мини-школа тестировщиков, ориентированных на Web
Мини-школа тестировщиков, ориентированных на WebМини-школа тестировщиков, ориентированных на Web
Мини-школа тестировщиков, ориентированных на Web
 
Оптимизация процесса тестирования локализаций
Оптимизация процесса тестирования локализацийОптимизация процесса тестирования локализаций
Оптимизация процесса тестирования локализаций
 
Как эффективно организовать Автоматизацию, если у вас недостаточно времени, р...
Как эффективно организовать Автоматизацию, если у вас недостаточно времени, р...Как эффективно организовать Автоматизацию, если у вас недостаточно времени, р...
Как эффективно организовать Автоматизацию, если у вас недостаточно времени, р...
 
Как найти побольше багов? (Особенно, если времени нет)
Как найти побольше багов? (Особенно, если времени нет)Как найти побольше багов? (Особенно, если времени нет)
Как найти побольше багов? (Особенно, если времени нет)
 
Модель компетенций в оценке, обучении и развитии специалиста по тестированию
Модель компетенций в оценке, обучении и развитии специалиста по тестированиюМодель компетенций в оценке, обучении и развитии специалиста по тестированию
Модель компетенций в оценке, обучении и развитии специалиста по тестированию
 
Путь к трассировке требований: от идеи к инструменту
Путь к трассировке требований: от идеи к инструментуПуть к трассировке требований: от идеи к инструменту
Путь к трассировке требований: от идеи к инструменту
 
Пример эффективного управления тест-кейсами при помощи Google docs
Пример эффективного управления тест-кейсами при помощи Google docsПример эффективного управления тест-кейсами при помощи Google docs
Пример эффективного управления тест-кейсами при помощи Google docs
 
Организация времени в тестировании
Организация времени в тестированииОрганизация времени в тестировании
Организация времени в тестировании
 
Keyword-driven framework
Keyword-driven frameworkKeyword-driven framework
Keyword-driven framework
 
Система генерации чек-листов для регрессионного тестирования на основе анализ...
Система генерации чек-листов для регрессионного тестирования на основе анализ...Система генерации чек-листов для регрессионного тестирования на основе анализ...
Система генерации чек-листов для регрессионного тестирования на основе анализ...
 
Использование Open Source инструментов для автоматизации тестирования
Использование Open Source инструментов для автоматизации тестированияИспользование Open Source инструментов для автоматизации тестирования
Использование Open Source инструментов для автоматизации тестирования
 
Не баг-трекер, а ...
Не баг-трекер, а ...Не баг-трекер, а ...
Не баг-трекер, а ...
 
Automated UI Testing
Automated UI TestingAutomated UI Testing
Automated UI Testing
 
Как принести пользу разработке и упростить себе жизнь?
Как принести пользу разработке и упростить себе жизнь?Как принести пользу разработке и упростить себе жизнь?
Как принести пользу разработке и упростить себе жизнь?
 

Similar to Метрики покрытия. Прагматичный подход

深度學習在AOI的應用
深度學習在AOI的應用深度學習在AOI的應用
深度學習在AOI的應用CHENHuiMei
 
Introducing LCS to Digital Design Verification
Introducing LCS to Digital Design VerificationIntroducing LCS to Digital Design Verification
Introducing LCS to Digital Design VerificationDaniele Loiacono
 
How to Test Asynchronous Code (v2)
How to Test Asynchronous Code (v2)How to Test Asynchronous Code (v2)
How to Test Asynchronous Code (v2)Felix Geisendörfer
 
Mutation Testing - Ruby Edition
Mutation Testing - Ruby EditionMutation Testing - Ruby Edition
Mutation Testing - Ruby EditionChris Sinjakli
 
Functionality testing techniqu
Functionality testing techniquFunctionality testing techniqu
Functionality testing techniqugaoliang641
 
Soft quality & standards
Soft quality & standardsSoft quality & standards
Soft quality & standardsPrince Bhanwra
 
Soft quality & standards
Soft quality & standardsSoft quality & standards
Soft quality & standardsPrince Bhanwra
 
Automated Test Suite Generation for Time-Continuous Simulink Models
Automated Test Suite Generation for Time-Continuous Simulink ModelsAutomated Test Suite Generation for Time-Continuous Simulink Models
Automated Test Suite Generation for Time-Continuous Simulink ModelsLionel Briand
 
Rubinius For You - GoRuCo
Rubinius For You - GoRuCoRubinius For You - GoRuCo
Rubinius For You - GoRuCoevanphx
 
Introduction to Performance Testing Part 1
Introduction to Performance Testing Part 1Introduction to Performance Testing Part 1
Introduction to Performance Testing Part 1C.T.Co
 
Technical Tricks of Vowpal Wabbit
Technical Tricks of Vowpal WabbitTechnical Tricks of Vowpal Wabbit
Technical Tricks of Vowpal Wabbitjakehofman
 
Studying the impact of dependency network measures on software quality
Studying the impact of dependency network measures on software quality	Studying the impact of dependency network measures on software quality
Studying the impact of dependency network measures on software quality ICSM 2010
 
Huong dan cu the svm
Huong dan cu the svmHuong dan cu the svm
Huong dan cu the svmtaikhoan262
 

Similar to Метрики покрытия. Прагматичный подход (20)

Pragmatic Code Coverage
Pragmatic Code CoveragePragmatic Code Coverage
Pragmatic Code Coverage
 
深度學習在AOI的應用
深度學習在AOI的應用深度學習在AOI的應用
深度學習在AOI的應用
 
Introducing LCS to Digital Design Verification
Introducing LCS to Digital Design VerificationIntroducing LCS to Digital Design Verification
Introducing LCS to Digital Design Verification
 
How to Test Asynchronous Code (v2)
How to Test Asynchronous Code (v2)How to Test Asynchronous Code (v2)
How to Test Asynchronous Code (v2)
 
Mutation Testing - Ruby Edition
Mutation Testing - Ruby EditionMutation Testing - Ruby Edition
Mutation Testing - Ruby Edition
 
Functionality testing techniqu
Functionality testing techniquFunctionality testing techniqu
Functionality testing techniqu
 
MXNet Workshop
MXNet WorkshopMXNet Workshop
MXNet Workshop
 
Soft quality & standards
Soft quality & standardsSoft quality & standards
Soft quality & standards
 
Soft quality & standards
Soft quality & standardsSoft quality & standards
Soft quality & standards
 
Automated Test Suite Generation for Time-Continuous Simulink Models
Automated Test Suite Generation for Time-Continuous Simulink ModelsAutomated Test Suite Generation for Time-Continuous Simulink Models
Automated Test Suite Generation for Time-Continuous Simulink Models
 
DCT_TR802
DCT_TR802DCT_TR802
DCT_TR802
 
DCT_TR802
DCT_TR802DCT_TR802
DCT_TR802
 
DCT_TR802
DCT_TR802DCT_TR802
DCT_TR802
 
Rubinius For You - GoRuCo
Rubinius For You - GoRuCoRubinius For You - GoRuCo
Rubinius For You - GoRuCo
 
Introduction to Performance Testing Part 1
Introduction to Performance Testing Part 1Introduction to Performance Testing Part 1
Introduction to Performance Testing Part 1
 
Technical Tricks of Vowpal Wabbit
Technical Tricks of Vowpal WabbitTechnical Tricks of Vowpal Wabbit
Technical Tricks of Vowpal Wabbit
 
Lafauci dv club oct 2006
Lafauci dv club oct 2006Lafauci dv club oct 2006
Lafauci dv club oct 2006
 
Studying the impact of dependency network measures on software quality
Studying the impact of dependency network measures on software quality	Studying the impact of dependency network measures on software quality
Studying the impact of dependency network measures on software quality
 
Guide
GuideGuide
Guide
 
Huong dan cu the svm
Huong dan cu the svmHuong dan cu the svm
Huong dan cu the svm
 

More from SQALab

Готовим стажировку
Готовим стажировкуГотовим стажировку
Готовим стажировкуSQALab
 
Куда приводят мечты? или Искусство развития тестировщика
Куда приводят мечты? или Искусство развития тестировщикаКуда приводят мечты? или Искусство развития тестировщика
Куда приводят мечты? или Искусство развития тестировщикаSQALab
 
Оптимизация Selenium тестов и ускорение их поддержки
Оптимизация Selenium тестов и ускорение их поддержкиОптимизация Selenium тестов и ускорение их поддержки
Оптимизация Selenium тестов и ускорение их поддержкиSQALab
 
Автоматизация 0.0: 0 - бюджет, 0 - опыт программирования
Автоматизация 0.0: 0 - бюджет, 0 - опыт программированияАвтоматизация 0.0: 0 - бюджет, 0 - опыт программирования
Автоматизация 0.0: 0 - бюджет, 0 - опыт программированияSQALab
 
Нагрузочное тестирование нестандартных протоколов с использованием Citrix и J...
Нагрузочное тестирование нестандартных протоколов с использованием Citrix и J...Нагрузочное тестирование нестандартных протоколов с использованием Citrix и J...
Нагрузочное тестирование нестандартных протоколов с использованием Citrix и J...SQALab
 
Continuous performance testing
Continuous performance testingContinuous performance testing
Continuous performance testingSQALab
 
Конфиги вместо костылей. Pytestconfig и зачем он нужен
Конфиги вместо костылей. Pytestconfig и зачем он нуженКонфиги вместо костылей. Pytestconfig и зачем он нужен
Конфиги вместо костылей. Pytestconfig и зачем он нуженSQALab
 
Команда чемпионов в ИТ стихии
Команда чемпионов в ИТ стихииКоманда чемпионов в ИТ стихии
Команда чемпионов в ИТ стихииSQALab
 
API. Серебряная пуля в магазине советов
API. Серебряная пуля в магазине советовAPI. Серебряная пуля в магазине советов
API. Серебряная пуля в магазине советовSQALab
 
Добиваемся эффективности каждого из 9000+ UI-тестов
Добиваемся эффективности каждого из 9000+ UI-тестовДобиваемся эффективности каждого из 9000+ UI-тестов
Добиваемся эффективности каждого из 9000+ UI-тестовSQALab
 
Делаем автоматизацию проектных KPIs
Делаем автоматизацию проектных KPIsДелаем автоматизацию проектных KPIs
Делаем автоматизацию проектных KPIsSQALab
 
Вредные привычки в тест-менеджменте
Вредные привычки в тест-менеджментеВредные привычки в тест-менеджменте
Вредные привычки в тест-менеджментеSQALab
 
Мощь переполняет с JDI 2.0 - новая эра UI автоматизации
Мощь переполняет с JDI 2.0 - новая эра UI автоматизацииМощь переполняет с JDI 2.0 - новая эра UI автоматизации
Мощь переполняет с JDI 2.0 - новая эра UI автоматизацииSQALab
 
Как hh.ru дошли до 500 релизов в квартал без потери в качестве
Как hh.ru дошли до 500 релизов в квартал без потери в качествеКак hh.ru дошли до 500 релизов в квартал без потери в качестве
Как hh.ru дошли до 500 релизов в квартал без потери в качествеSQALab
 
Стили лидерства и тестирование
Стили лидерства и тестированиеСтили лидерства и тестирование
Стили лидерства и тестированиеSQALab
 
"Давайте не будем про качество"
"Давайте не будем про качество""Давайте не будем про качество"
"Давайте не будем про качество"SQALab
 
Apache.JMeter для .NET-проектов
Apache.JMeter для .NET-проектовApache.JMeter для .NET-проектов
Apache.JMeter для .NET-проектовSQALab
 
Тестирование геолокационных систем
Тестирование геолокационных системТестирование геолокационных систем
Тестирование геолокационных системSQALab
 
Лидер или босс? Вот в чем вопрос
Лидер или босс? Вот в чем вопросЛидер или босс? Вот в чем вопрос
Лидер или босс? Вот в чем вопросSQALab
 
От Зефира в коробке к Structure Zephyr или как тест-менеджеру перекроить внут...
От Зефира в коробке к Structure Zephyr или как тест-менеджеру перекроить внут...От Зефира в коробке к Structure Zephyr или как тест-менеджеру перекроить внут...
От Зефира в коробке к Structure Zephyr или как тест-менеджеру перекроить внут...SQALab
 

More from SQALab (20)

Готовим стажировку
Готовим стажировкуГотовим стажировку
Готовим стажировку
 
Куда приводят мечты? или Искусство развития тестировщика
Куда приводят мечты? или Искусство развития тестировщикаКуда приводят мечты? или Искусство развития тестировщика
Куда приводят мечты? или Искусство развития тестировщика
 
Оптимизация Selenium тестов и ускорение их поддержки
Оптимизация Selenium тестов и ускорение их поддержкиОптимизация Selenium тестов и ускорение их поддержки
Оптимизация Selenium тестов и ускорение их поддержки
 
Автоматизация 0.0: 0 - бюджет, 0 - опыт программирования
Автоматизация 0.0: 0 - бюджет, 0 - опыт программированияАвтоматизация 0.0: 0 - бюджет, 0 - опыт программирования
Автоматизация 0.0: 0 - бюджет, 0 - опыт программирования
 
Нагрузочное тестирование нестандартных протоколов с использованием Citrix и J...
Нагрузочное тестирование нестандартных протоколов с использованием Citrix и J...Нагрузочное тестирование нестандартных протоколов с использованием Citrix и J...
Нагрузочное тестирование нестандартных протоколов с использованием Citrix и J...
 
Continuous performance testing
Continuous performance testingContinuous performance testing
Continuous performance testing
 
Конфиги вместо костылей. Pytestconfig и зачем он нужен
Конфиги вместо костылей. Pytestconfig и зачем он нуженКонфиги вместо костылей. Pytestconfig и зачем он нужен
Конфиги вместо костылей. Pytestconfig и зачем он нужен
 
Команда чемпионов в ИТ стихии
Команда чемпионов в ИТ стихииКоманда чемпионов в ИТ стихии
Команда чемпионов в ИТ стихии
 
API. Серебряная пуля в магазине советов
API. Серебряная пуля в магазине советовAPI. Серебряная пуля в магазине советов
API. Серебряная пуля в магазине советов
 
Добиваемся эффективности каждого из 9000+ UI-тестов
Добиваемся эффективности каждого из 9000+ UI-тестовДобиваемся эффективности каждого из 9000+ UI-тестов
Добиваемся эффективности каждого из 9000+ UI-тестов
 
Делаем автоматизацию проектных KPIs
Делаем автоматизацию проектных KPIsДелаем автоматизацию проектных KPIs
Делаем автоматизацию проектных KPIs
 
Вредные привычки в тест-менеджменте
Вредные привычки в тест-менеджментеВредные привычки в тест-менеджменте
Вредные привычки в тест-менеджменте
 
Мощь переполняет с JDI 2.0 - новая эра UI автоматизации
Мощь переполняет с JDI 2.0 - новая эра UI автоматизацииМощь переполняет с JDI 2.0 - новая эра UI автоматизации
Мощь переполняет с JDI 2.0 - новая эра UI автоматизации
 
Как hh.ru дошли до 500 релизов в квартал без потери в качестве
Как hh.ru дошли до 500 релизов в квартал без потери в качествеКак hh.ru дошли до 500 релизов в квартал без потери в качестве
Как hh.ru дошли до 500 релизов в квартал без потери в качестве
 
Стили лидерства и тестирование
Стили лидерства и тестированиеСтили лидерства и тестирование
Стили лидерства и тестирование
 
"Давайте не будем про качество"
"Давайте не будем про качество""Давайте не будем про качество"
"Давайте не будем про качество"
 
Apache.JMeter для .NET-проектов
Apache.JMeter для .NET-проектовApache.JMeter для .NET-проектов
Apache.JMeter для .NET-проектов
 
Тестирование геолокационных систем
Тестирование геолокационных системТестирование геолокационных систем
Тестирование геолокационных систем
 
Лидер или босс? Вот в чем вопрос
Лидер или босс? Вот в чем вопросЛидер или босс? Вот в чем вопрос
Лидер или босс? Вот в чем вопрос
 
От Зефира в коробке к Structure Zephyr или как тест-менеджеру перекроить внут...
От Зефира в коробке к Structure Zephyr или как тест-менеджеру перекроить внут...От Зефира в коробке к Structure Zephyr или как тест-менеджеру перекроить внут...
От Зефира в коробке к Structure Zephyr или как тест-менеджеру перекроить внут...
 

Recently uploaded

Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxShobhayan Kirtania
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 

Recently uploaded (20)

Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptx
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 

Метрики покрытия. Прагматичный подход

  • 1. <Insert Picture Here> Code coverage. The pragmatic approach. Александр Ильин Java Quality architect Oracle
  • 2. What it is about? Should the testing be stopped at 100% coverage? Should 100% be the goal? How (else) to use code coverage information? What it is not about? Tools 2
  • 4. What is the code coverage data for Measure to which extent source code is covered during testing. consequently … Code coverage is A measure of how much source code is covered during testing. finally … Testing is A set of activities aimed to prove that the system under test behaves as expected. 4
  • 5. CC – how to get • Create a template Template is a collection of all the code there is to cover • “Instrument” the source/compiled code/bytecode Insert instructions for dropping data into a file/network, etc. • Run testing, collect data May need to change environment • Generate report HTML, DB, etc 5
  • 6. CC – kinds of • Block / primitive block • Line • Condition/branch/predicate • Entry/exit • Method • Path/sequence 6
  • 7. CC – how to use for testbase improvement • 1: Measure (prev. slide) Performed repeatedly, so resource-efficiency is really important • Perform analysis Find what code you need to cover. Find what tests you need to develop. • Develop more tests • Find dead code • GOTO 1 7
  • 9. CC – how not to use mis-usages • Must get to 100% May be not. • 100% means no more testing No it does not. • CC does not mean a thing It does mean a fair amount if it is used properly. • There is that tool which would generate tests for us and we're done Nope. 9
  • 11. Test generation “We present a new symbolic execution tool, ####, capable of automatically generating tests that achieve high coverage on a diverse set of complex and environmentally-intensive programs.” #### tool documentation
  • 12. Test generation cont. if ( b != 3 ) { double a = 1 / ( b – 2); } else { … }
  • 13. Test generation cont. if ( b != 3 ) { double a = 1 / ( b – 3); } else { … } Reminder: testing is ... A set of activities aimed to prove that the system under test behaves as expected.
  • 14. Test generation - conclusion Generated tests could not test that the code work as expected because they only know how the code works and not how it is expected to. Because the only thing they possess is the code which may already be not working as expected. :) Hence … Generated tests code coverage should not be mixed with regular functional tests code coverage. 14
  • 15. Who watches the watchmen? • Test logic gotta be right • No way to verify the logic • No metrics • No approaches • No techniques • Code review – the only way • Sole responsibility of test developer
  • 16. <Insert Picture Here> Mis-usages What does 100% coverage mean?
  • 18. 100% branch coverage 1 -1 true false
  • 19. 100% domain coverage 0 .1 -.1 0 .1 Exception
  • 20. 100% sequence coverage (-1,-1) (1,1) (0,0) b 1 1 NaN
  • 21. 100% sequence coverage (-1,-1) (-1,1) (1,-1) (1,1) (0,0) b 1 -1 -1 1 NaN But … isPositive(float) has a defect!
  • 22. 100% sequence coverage • Has conceptual problems • Code semantics • Loops • One of the two • Assume libraries has no errors • Done in depth – with the libraries • Very expensive • A lot of sequences: 2# branches, generally speaking • Very hard to analyze data
  • 23. 100% coverage - conclusion 100% block/line/branch/path coverage, even if reachable, does not prove much. Hence … No need to try to get there unless ... 23
  • 25. CC target value - cost Test Dev. Effort by Code Block Coverage. Industry data indicates that effort 90.00 increases exponentially with 80.00 coverage. Relative Test Dev. Effort (1 at 50% code block coverage) 70.00 We scale to make effort relative to the effort of getting 50% 60.00 coverage. 50.00 f  x =k e r x Intuition: the effort needed to get more k =e−50r ⇒ f 50=1 40.00 coverage is df proportional to the =r f  x  30.00 dx total effort needed to get current coverage. 20.00 Model not reliable below 50% coverage, 10.00 except maybe very big projects. 0.00 0 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100 Code Block Coverage (%)
  • 26. CC target value - effectiveness Defect Coverage by Code Block Coverage Defect coverage by 120.00 code block coverage... def ned in terms of i 100.00 effort per code coverage and defect coverage by effort. H  x =h  f  x  80.00 f  x =k e r x Defect Coverage(%) Intuition: discovery rate − s y B is proportional to the h  y = B1−e  percentage of bugs 60.00 remaining and the effort dH H  x  df =s 1−  x needed to get current dx B dx coverage. 40.00 Model not reliable below 50% coverage except 20.00 maybe very big projects. 0.00 0 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100 Code Block Coverage(%)
  • 27. CC target value - ROI Benef t(c) = DC(c) DD COD, where i DC(c): Defect Coverage Cost-Benefit Analysis DD: Defect Density. Example: 50bug/kloc 1200.00 COD: Cost Of Defect. Example: $20k/bug 1000.00 800.00 Benefit ($/size), Cost ($/size), ROI (%) ROI = Benef t(c)/ Cost(c) - 1 i 600.00 400.00 200.00 0.00 Cost(c) = F + V * RE(c), where RE(c): Relative Effort, RE(50%) = 1 F: Fixed cost of test. Example: -200.00 $50k/kloc 0 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100 V: Variable cost of test. Example: $5k/kloc Code Block Coverage (%)
  • 28. 100% coverage - conclusion 100% block/line/branch/path coverage, even if reachable, does not prove much. Hence … No need to try to get there unless … 100% is the target value. Which could happen if cost of a bug is really big and/or the product is really small. 28
  • 29. Target value - conclusion True target value for block/line/branch/path comes from ROI, which is really hard to calculate and justify. 29
  • 31. CC – how to use • Test base improvement. Right. How to select which tests to develop first • Dead code. Barely an artifact • Metric Better have a good metric. • Control over code development • Deep analysis 31
  • 33. What makes a good metric Simple to explain So that you could explain your boss why is that important to spend resources on Simple to work towards So that you know what to do to improve Has a clear goal So you could tell how far are you.
  • 34. Is CC a good metric? Simple to explain + Is a metric of quality of testing. Simple to work towards + (Relatively) easy to map uncovered code to missed tests. Has a clear goal - Nope. ROI – too complicated. Need to filter the CC data so only that is left which must be covered
  • 35. Public API* Is a set of program elements suggested for usage by public documentation. For example: all functions and variables which are described in documentation. For a Java library: all public and protected methods and fields mentioned in the library javadoc. For Java SDK: … of all public classes in java and javax packages. (*) Only applicable for a library or a SDK
  • 37. True Public API (c) Is a set of program elements which could be accessed directly by a library user Public API + all extensions of public API in non-public classes
  • 38. True public API example My code ArrayList.java
  • 39. True Public API how to get • Get public API with interfaces • Filter template so that it only contains implementations and extensions of the public API (*) • Filter the data by template (*) This assumes that you either • Use a tool which allows such kind of filtering or • Have the data in a parse-able format and develop the filtering on your own
  • 40. UI coverage In a way, equivalent to public API but for a UI product • %% of UI elements shown – display coverage • %% user actions performed – action coverage Only “action coverage” could be obtained from CC data (*). (*) For UI toolkits which the presenter is familiar with.
  • 41. Action coverage – how to get • Collect CC • Extract all implementations of javax.swing.Action.actionPerformed(ActionEvent) or javafx.event.EventHandler.handle(Event) • Inspect all the implementations org.myorg.NodeAction.actionPerformed(ActionEvent) • Add to the filter: org.myorg.NodeAction.nodeActionPerformed(Node myNode) • Extract, repeat
  • 42. “Controller” code coverage Model Contains the domain logic View Implements user interaction Controller Maps the two. Only contains code which is called as a result of view actions and model feedbacks. Controller has very little boilerplate code. A good candidate for 100% block coverage.
  • 43. “Important” code • Development/SQE marks class/method as important • We use an annotation @CriticalForCoverage • List of methods is obtained which are marked as important • We do that by an annotation processor right while main compilation • CC data is filtered by the method list • Goal is 100%
  • 44. Examples of non-generic metrics • BPEL elements • JavaFX properties • A property in JavaFX is something you could set, get and bind • Insert your own.
  • 45. CC as a metric - conclusion There are multiple ways to filter CC data to a set of code which needed to be covered in full. There are generic metrics and there is a possibility to introduce product specific metric. Such metrics are easy to use, although not always so straightforward to obtain. 45
  • 46. <Insert Picture Here> Test prioritization
  • 47. Test prioritization 100500 uncovered lines of code! “OMG! Where do I start?” Metric • Develop tests to close the metric • Pick another metric “Metrics for managers. Me no manager! Me write code!” Consider mapping CC data to few other source code characteristics.
  • 48. Age of the code New code is better be tested before getting to customer. Improves bug escape rate, BTW Old code is more likely to be tested by users or Not used by users.
  • 49. What's a bug escape metric? Ratio of defects sneaked out unnoticed # defects not found before release In theory: # defects in the product # defects found after release Practical: # defects found after + # defects found before
  • 50. Number of changes More times a piece of code was changed, more atomic improvements/bugfixes were implemented in it. Hence … Higher risk of introducing a regression.
  • 51. Number of lines changed More lines changed – more testing it needs. Better all – number of uncovered lines which were changed in the last release.
  • 52. Bug density Assuming all the pieces were tested equally well … Many bugs means there are, probably, even more • Hidden behind the known ones • Fixing existing ones may introduce yet more as regressions
  • 53. Code complexity Assuming the same engineering talent and the same technology … More complex the code is – more bugs likely to be there. Any complexity metric would work: from class size to cyclomatic complexity
  • 54. Putting it together A formula (1 – cc) * (a1*x1 + a2*x2 + a3*x3 + ...) Where cc – code coverage (0 - 1) xi – a risk of bug discovery in a piece of code ai – a coefficient
  • 55. Putting it together (1 – cc) * (a1*x1 + a2*x2 + a3*x3 + ...) The ones with higher value are first to cover • Fix the coefficients • Develop tests • Collect statistics on bug escape • Fix the coefficient • Continue
  • 56. Test prioritization - conclusion CC alone may not give enough information. Need to accompany it with other characteristics of test code to make a decision. Could use a few of other characteristics simultaneously. 56
  • 57. <Insert Picture Here> Test prioritization Execution
  • 58. Decrease test execution time Exclude tests which do not add coverage (*). But, be careful! Remember that CC is not all and even 100% coverage does not mean a lot. While excluding tests get some orthogonal measurement as well, such as specification coverage. (*) Requires “test scales”
  • 59. Deep analysis Study the coverage report, see what test code exercises which code. (*). Recommended for developers. (*) Also requires “test scales”
  • 60. Controlled code changes Do not allow commits unless all the new/changed code is covered. Requires simultaneous commits of tests and the changes.
  • 61. Code coverage - conclusion 100% CC does not guarantee that the code is working right 100% CC may not be needed It is possible to build good metrics with CC CC helps with prioritization of test development Other source code characteristics could be used with CC 61
  • 62. Coverage data is not free • Do just as much as you can consume * • Requires infrastructure work • Requires some development • Requires some analysis (*) The rule of thumb
  • 63. Coverage data is not free • Do just as much as you can consume • Requires infrastructure work • Requires some development • Requires some analysis • Do just a little bit more than you can consume * • Otherwise how do you know how much you can consume? (*) The rule of thumb
  • 64. <Insert Picture Here> Code coverage. The pragmatic approach. Александр Ильин Java Quality architect Oracle