SlideShare una empresa de Scribd logo
1 de 75
Descargar para leer sin conexión
<Insert Picture Here>




Полезные метрики покрытия
Практический опыт и немного теории
Александр (Шура) Ильин
JavaSE quality architect
What's this NOT about?

• Not about a particular code coverage tool
   • Different tools for different needs
• Not about hoe to write tests to reach higher code
 coverage
  • There are different techniques
• No data for the projects I am working on
   • Sorry.
What's this about?

• Personal experience
   • My
   • Yours (depends on speaker abilities to speak fast)
• Using coverage as a metric
• What metrics to select
Disclaimer


• The views expressed on this presentation belong to
  the presenter and do not necessarily reflect the views
  of Oracle
• Докладчик работает в “продуктовой лавке” :)
• Ideas, approaches and conclusions described are
  coming from experience of the presenter
What's a metric

• A type of measurement user to gauge some
 quantifiable components.
What's a metric

• A type of measurement user to gauge some
  quantifiable components.
• Metrics also used to track progress toward a goal.
What's a metric

• A type of measurement user to gauge some
  quantifiable components.
• Metrics also used to track progress toward a goal.
• A goal must be SMART
  • Simple (who, what, where, when, which, why)
  • Measurable (has a metric)
  • Attainable (the metric has a target value)
  • Realistic (willing and able to work towards)
  • Timely (results arrive on time to be used)
How do you test the application?
How do you test the application?

By tests
How do you test the application?

By tests


 Metrics

• Number of tests
• Passrate
• Number of bugs
• Etc, etc, etc
How do you test the tests?
How do you test the tests?




Hm ….
How do you test the tests?




By … application?
What's the goal of testing?

• Prove the system working properly
Practically impossible
• Prove the system not working properly
Never ending process
• Verify conformance to requirements
Too generic
What's the goal of testing?

• Prove the system working properly
Practically impossible
• Prove the system not working properly
Never ending process
• Verify conformance to requirements
Too generic
• Money (not to loose money on poor quality)
Yep. I need my bills to be paid.
• Report quality
On time and accurately. Still, too abstract.
What's a quality?



       Separate presentation.

         No holy war today.
Two goals. *

• Defect escape reduction
• Test coverage (different kinds off)


• All the rest is bullshit *
   • Misleading
   • Not to the point
   • No target




(*) Honest opinion of the presenter
Two goals. *

• Defect escape reduction
• Test coverage (different kinds off)


• All the rest is rubbish *
   • Misleading
   • Not to the point
   • No target




(*) Honest opinion of the presenter
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
What's a bug escape metric?

Ratio of defects sneaked out unnoticed

                    # defects found after release
             # defects found after + # defects found before


Perfect! Direct metric of quality of testing
What's a bug escape metric?

Ratio of defects sneaked out unnoticed

                    # defects found after release
             # defects found after + # defects found before


Perfect! Direct metric of quality of testing


Problem: coming too late!
Is defect escape a good metric?


• Simple (+.)
• Measurable (+)
• Attainable (?)
• Realistic
• Timely (-!)
What's test coverage?
A ratio of some numerable items “covered” in testing.
                  # tested / # existing
 Implementation coverage              Specification coverage
• Code coverage                   •   Requirement
  •   Line, block                 •   Assertion
  •   Entry/exit                  •   API
  •   Branch/predicate
  •
                                  •   UI
      Path/sequence
• Race coverage
                                  •   Data coverage
• Data coverage


               Assumes test logic is right
Code coverage
Shows to what extent source code is covered

• Class
• Method (function)
• Block
• Line
• Branch (condition)/predicate
• Path (sequence)
• Entry/exit
Code coverage analysis – what for?

A) Improve test base      B) Find dead code
  1.Measure coverage        1.Find something uncovered
  2.Find uncovered code     2.Try to develop tests
  3.Develop more tests      3.Fail
  4.Goto 1.                 4.Go to developers
                            5.Argue
                            6.Argue
                            7.Argue
                            8.Create a bug
                            9.Dead code removed
C) Use as a metric
Is code coverage a good metric?
so far ...


• Simple (+)
• Measurable (+)
• Attainable (?)
• Realistic
• Timely (+!)
Block code coverage – what's the target?


100%? Unrealistic.

80%? Why not 78?

50%? What does it guarantee?
100% block/line coverage

• Does it mean that all bugs found?
Nope.
100% block/line coverage

• Does it mean that all bugs found?
Nope.

• Does it mean that all scenarios tested?
Nope.
100% block/line coverage

• Does it mean that all bugs found?
Nope.

• Does it mean that all scenarios tested?
Nope.

• What does it mean, then?
Nothing, really.
100% block/line coverage
Branch coverage helps?
Data coverage?
Block code coverage – what's the target?
... target comes from ROI
Is block/line coverage a good metric?



• Simple (+)
• Measurable (+)
• Attainable (-)
• Realistic
• Timely (+!)
Code coverage is very useful.
• Tie CC data to
   • Code complexity
      • More complicated code is – more thorough testing it needs
   • Code stability
      • Recently changed code needs to be tested better
   • Bug density
      • Is there a correlation
   • Static analysis tools
      • To filter the false positives
• Use CC as
   • Check-in criteria
      • Commit only if tested
   • Test selection
      • Run only tests for changed code
   • Hot spot detection
      • Usually coverage also shows hit counts
What about 100% sequence coverage?


Does it guarantee full testing?
100% sequence coverage
100% sequence coverage




             b
What about sequence coverage?

• 100% sequence coverage does not prove a code to
 be fully tested
  • Libraries may have defects
100% sequence coverage
What about sequence coverage?

• 100% sequence coverage does not prove a code to
 be fully tested
  • Libraries may have defects
  • Branches could be incorrect
• 100% sequence + 100% predicate + 100% data
 +100% XYZ?
  • No idea
  • Have not seen a mathematical proof yet
  • Does not matter
What else wrong with sequence coverage?

• Tools availability
   • None for Java
• Expensive
   • Execution
   • Analysis
• Complicated
   • Not all paths are valid
   • Loops
• 100% likely not attainable
   • number of paths is exponential to the number of branches
Is sequence coverage a good metric?



• Simple (+.)
• Measurable (+)
• Attainable (-.)
• Realistic
• Timely (+)
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
So, is there a good coverage metric, then?

Attainability seems to be the most trouble so far

• Manageable amount of work
  • Obtain
  • Analyze
  • Improve
• Clear target
   • Explainable
   • Verifiable
Specification coverage


• Requirements


• Assertions


• Public API


• UI


• Custom coverage metrics
Assertions
public final void wait(long timeout, int nanos)
  throws InterruptedException

  Causes current thread to wait until another
thread invokes the notify() method or the
notifyAll() method for this object, or some
other thread interrupts the current thread, or a
certain amount of real time has elapsed.
Assertions
• Mark all the assertions with ID
  • Mark up the specification itself
  • Create a separate storage
• Develop tests
   • An assertion deserves a few
   • A test could cover a few
• Mark tests by assertion IDs
• When next specification version is released
  • Compare assertions with a previous version
  • Verify all tests for changes assertions
  • Scan for new assertions
  • Develop new tests
Requirements


Same as assertions
• Number the requirements
• Mark the tests
• Validate all tests when requirements change
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


• Is obtainable from code coverage
• May require some work on top of existing CC tools



  True Public API


• Does require some work on top of an existing CC tools
• Emma, JCov
UI coverage


• % dialogs inspected
• % menus pushed
• % buttons pushed
• % text fields was entered a value in
• etc.
UI coverage


• In some cases obtainable from code coverage (works
 well for factory methods)
  • Action coverage: javax.swing.Action implementations
• If not
   • “Instrument” the application
      • Adding test hooks
      • Using event queue
   • Obtain a “template” somehow else
Are these metrics attainable?


May be not in the beginning
Are these metrics attainable?


For every product to be claimed to be tested well, the
target value is ...
Are these metrics attainable?


For every product to be claimed to be tested well, the
target value is ...




                  100%
Why 100%?

• Every requirement must be tested by at least one test
• Every statement in spec must be exercised at least
  once
• Every method in public API must be called at least
  once
• Every button in a UI needs to be pushed at least once




For exceptions there are exclude lists.
So, are these metrics good?



• Simple (+)
• Measurable (+)
• Attainable (+)
• Realistic
• Timely (+)
But wait … what is the point?
• What does 100% public API coverage means?


• UI coverage?


• Specification coverage?


• Requirements coverage?
But wait … what is the point?
• What does 100% public API coverage means?
Nothing.
• UI coverage?


• Specification coverage?


• Requirements coverage?
But wait … what is the point?
• What does 100% public API coverage means?
Nothing.
• UI coverage?
Not that we are done with testing.
• Specification coverage?


• Requirements coverage?
But wait … what is the point?
• What does 100% public API coverage means?
Nothing.
• UI coverage?
Not that we are done with testing.
• Specification coverage?
Not anywhere near with been done.
• Requirements coverage?
But wait … what is the point?
• What does 100% public API coverage means?
Nothing.
• UI coverage?
Not that we are done with testing.
• Specification coverage?
Not anywhere near with been done.
• Requirements coverage?
Well … at least we touched each and every of'm
But wait … what is the point?
• What does 100% public API coverage means?
Nothing.
• UI coverage?
Not that we are done with testing.
• Specification coverage?
Not anywhere near with been done.
• Requirements coverage?
Well … at least we touched each and every of'm

These metrics are required but not sufficient.
More such metrics


• Property coverage
   • Property is a field with a setter and getter
• UML element coverage
   • In UML diagram
• Language element coverage
   • Expression Language


• Make your own.
Summary

No perfect coverage metric

• Implementation based
   • target value comes from ROI
   • too heavy
   • yet do not prove anything
• Specification based
   • Are not thorough enough
Summary

On the bright side, any of them could be useful

• Test base improvement
• Finding
   • Dead code
   • Untestable assertions
   • Unreachable UI
   • Etc.
Comments?
Alexandre (Shura) Iline

Oracle

Quality architect

Java SE SQE group

alexandre.iline@oracle.com

Más contenido relacionado

La actualidad más candente

La actualidad más candente (19)

Agile Testing
Agile Testing Agile Testing
Agile Testing
 
Test Estimation
Test Estimation Test Estimation
Test Estimation
 
Agile Testing
Agile TestingAgile Testing
Agile Testing
 
Exploratory testing using heuristics
Exploratory testing using heuristicsExploratory testing using heuristics
Exploratory testing using heuristics
 
How to Test the Internet of Everything
How to Test the Internet of EverythingHow to Test the Internet of Everything
How to Test the Internet of Everything
 
Software Testing As a Career Path
Software Testing As a Career PathSoftware Testing As a Career Path
Software Testing As a Career Path
 
Agile Testing Analytics
Agile Testing AnalyticsAgile Testing Analytics
Agile Testing Analytics
 
Examples how to move towards Zero Defects
Examples how to move towards Zero DefectsExamples how to move towards Zero Defects
Examples how to move towards Zero Defects
 
Design for Testability in Practice
Design for Testability in PracticeDesign for Testability in Practice
Design for Testability in Practice
 
Istqb intro with question answer for exam preparation
Istqb intro with question answer for exam preparationIstqb intro with question answer for exam preparation
Istqb intro with question answer for exam preparation
 
QA Interview Questions With Answers
QA Interview Questions With AnswersQA Interview Questions With Answers
QA Interview Questions With Answers
 
Vipul Kocher - Software Testing, A Framework Based Approach
Vipul Kocher - Software Testing, A Framework Based ApproachVipul Kocher - Software Testing, A Framework Based Approach
Vipul Kocher - Software Testing, A Framework Based Approach
 
Bart Knaack - The Truth About Model-Based Quality Improvements
Bart Knaack - The Truth About Model-Based Quality ImprovementsBart Knaack - The Truth About Model-Based Quality Improvements
Bart Knaack - The Truth About Model-Based Quality Improvements
 
Vladimir Primakov - Qa management in big agile teams
Vladimir Primakov - Qa management in big agile teamsVladimir Primakov - Qa management in big agile teams
Vladimir Primakov - Qa management in big agile teams
 
DevOps! let's change QA! DevOps Pro Lithuania
DevOps! let's change QA! DevOps Pro LithuaniaDevOps! let's change QA! DevOps Pro Lithuania
DevOps! let's change QA! DevOps Pro Lithuania
 
The Role of Testing in DevOps
The Role of Testing in DevOpsThe Role of Testing in DevOps
The Role of Testing in DevOps
 
Test Cases - are they dead?
Test Cases - are they dead?Test Cases - are they dead?
Test Cases - are they dead?
 
Christian Bk Hansen - Agile on Huge Banking Mainframe Legacy Systems - EuroST...
Christian Bk Hansen - Agile on Huge Banking Mainframe Legacy Systems - EuroST...Christian Bk Hansen - Agile on Huge Banking Mainframe Legacy Systems - EuroST...
Christian Bk Hansen - Agile on Huge Banking Mainframe Legacy Systems - EuroST...
 
How to use selenium successfully
How to use selenium successfullyHow to use selenium successfully
How to use selenium successfully
 

Destacado

Глеб Рыбалко - Цена качества. Как объяснить заказчику, сколько стоит качество
Глеб Рыбалко - Цена качества. Как объяснить заказчику, сколько стоит качествоГлеб Рыбалко - Цена качества. Как объяснить заказчику, сколько стоит качество
Глеб Рыбалко - Цена качества. Как объяснить заказчику, сколько стоит качество
SQALab
 
Тестирование в среде заказчика (Live Environment). Зачем мы это делаем?
Тестирование в среде заказчика (Live Environment). Зачем мы это делаем?Тестирование в среде заказчика (Live Environment). Зачем мы это делаем?
Тестирование в среде заказчика (Live Environment). Зачем мы это делаем?
SQALab
 

Destacado (20)

Метрики покрытия. Прагматичный подход
Метрики покрытия. Прагматичный подходМетрики покрытия. Прагматичный подход
Метрики покрытия. Прагматичный подход
 
Waterfall revisited: практические метрики тестирования
Waterfall revisited: практические метрики тестированияWaterfall revisited: практические метрики тестирования
Waterfall revisited: практические метрики тестирования
 
Оценки тестирования - полезные и условные метрики
Оценки тестирования - полезные и условные метрикиОценки тестирования - полезные и условные метрики
Оценки тестирования - полезные и условные метрики
 
Как оценить тестировщика
Как оценить тестировщикаКак оценить тестировщика
Как оценить тестировщика
 
Глеб Рыбалко - Цена качества. Как объяснить заказчику, сколько стоит качество
Глеб Рыбалко - Цена качества. Как объяснить заказчику, сколько стоит качествоГлеб Рыбалко - Цена качества. Как объяснить заказчику, сколько стоит качество
Глеб Рыбалко - Цена качества. Как объяснить заказчику, сколько стоит качество
 
Особенности процесса тестирования при внедрении Continuous Delivery на пример...
Особенности процесса тестирования при внедрении Continuous Delivery на пример...Особенности процесса тестирования при внедрении Continuous Delivery на пример...
Особенности процесса тестирования при внедрении Continuous Delivery на пример...
 
Использование метрик в процессе обеспечения качества сложных систем
Использование метрик в процессе обеспечения качества сложных системИспользование метрик в процессе обеспечения качества сложных систем
Использование метрик в процессе обеспечения качества сложных систем
 
Грамотная работа с дефект-трекером -- путь к успеху!
Грамотная работа с дефект-трекером -- путь к успеху!Грамотная работа с дефект-трекером -- путь к успеху!
Грамотная работа с дефект-трекером -- путь к успеху!
 
Полезные "фишки" для построения успешного процесса тестирования
Полезные "фишки" для построения успешного процесса тестированияПолезные "фишки" для построения успешного процесса тестирования
Полезные "фишки" для построения успешного процесса тестирования
 
Monthly Operations Review
Monthly Operations ReviewMonthly Operations Review
Monthly Operations Review
 
Метрики автоматизированного тестирования на пальцах
Метрики автоматизированного тестирования на пальцахМетрики автоматизированного тестирования на пальцах
Метрики автоматизированного тестирования на пальцах
 
Когда стоит закончить автоматизировать?
Когда стоит закончить автоматизировать?Когда стоит закончить автоматизировать?
Когда стоит закончить автоматизировать?
 
Полезное покрытие кода
Полезное покрытие кодаПолезное покрытие кода
Полезное покрытие кода
 
Методика проведения независимой оценки процесса тестирования в проектах
Методика проведения независимой оценки процесса тестирования в проектахМетодика проведения независимой оценки процесса тестирования в проектах
Методика проведения независимой оценки процесса тестирования в проектах
 
Выбор и внедрение инструмента - с чего начать?
Выбор и внедрение инструмента - с чего начать?Выбор и внедрение инструмента - с чего начать?
Выбор и внедрение инструмента - с чего начать?
 
Жизненный цикл коммуникативных дефектов
Жизненный цикл коммуникативных дефектовЖизненный цикл коммуникативных дефектов
Жизненный цикл коммуникативных дефектов
 
Качество отсутствует, коль баги присутствуют
Качество отсутствует, коль баги присутствуютКачество отсутствует, коль баги присутствуют
Качество отсутствует, коль баги присутствуют
 
Тестирование в среде заказчика (Live Environment). Зачем мы это делаем?
Тестирование в среде заказчика (Live Environment). Зачем мы это делаем?Тестирование в среде заказчика (Live Environment). Зачем мы это делаем?
Тестирование в среде заказчика (Live Environment). Зачем мы это делаем?
 
Эволюция средств тестирования от HP
Эволюция средств тестирования от HPЭволюция средств тестирования от HP
Эволюция средств тестирования от HP
 
Становление программы внутренних аудитов: от требований сертификации до обесп...
Становление программы внутренних аудитов: от требований сертификации до обесп...Становление программы внутренних аудитов: от требований сертификации до обесп...
Становление программы внутренних аудитов: от требований сертификации до обесп...
 

Similar a Полезные метрики покрытия. Практический опыт и немного теории

CodeChecker Overview Nov 2019
CodeChecker Overview Nov 2019CodeChecker Overview Nov 2019
CodeChecker Overview Nov 2019
Olivera Milenkovic
 
Quality metrics and angular js applications
Quality metrics and angular js applicationsQuality metrics and angular js applications
Quality metrics and angular js applications
nadeembtech
 
Test-Driven Development
Test-Driven DevelopmentTest-Driven Development
Test-Driven Development
Meilan Ou
 
Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Into...
Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Into...Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Into...
Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Into...
Ortus Solutions, Corp
 

Similar a Полезные метрики покрытия. Практический опыт и немного теории (20)

Getting Ahead of Delivery Issues with Deep SDLC Analysis by Donald Belcham
Getting Ahead of Delivery Issues with Deep SDLC Analysis by Donald BelchamGetting Ahead of Delivery Issues with Deep SDLC Analysis by Donald Belcham
Getting Ahead of Delivery Issues with Deep SDLC Analysis by Donald Belcham
 
Pragmatic Code Coverage
Pragmatic Code CoveragePragmatic Code Coverage
Pragmatic Code Coverage
 
CBDW2014 - Behavior Driven Development with TestBox
CBDW2014 - Behavior Driven Development with TestBoxCBDW2014 - Behavior Driven Development with TestBox
CBDW2014 - Behavior Driven Development with TestBox
 
CodeChecker Overview Nov 2019
CodeChecker Overview Nov 2019CodeChecker Overview Nov 2019
CodeChecker Overview Nov 2019
 
Code Quality - Security
Code Quality - SecurityCode Quality - Security
Code Quality - Security
 
Quality metrics and angular js applications
Quality metrics and angular js applicationsQuality metrics and angular js applications
Quality metrics and angular js applications
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing Software
 
Every code coverage tool is measuring the wrong thing (on purpose)
Every code coverage tool is measuring the wrong thing (on purpose)Every code coverage tool is measuring the wrong thing (on purpose)
Every code coverage tool is measuring the wrong thing (on purpose)
 
Sustainable agile testing
Sustainable agile testingSustainable agile testing
Sustainable agile testing
 
Improving the Quality of Existing Software - DevIntersection April 2016
Improving the Quality of Existing Software - DevIntersection April 2016Improving the Quality of Existing Software - DevIntersection April 2016
Improving the Quality of Existing Software - DevIntersection April 2016
 
Unit Testing and Tools
Unit Testing and ToolsUnit Testing and Tools
Unit Testing and Tools
 
Test box bdd
Test box bddTest box bdd
Test box bdd
 
GNAT Pro User Day: Latest Advances in AdaCore Static Analysis Tools
GNAT Pro User Day: Latest Advances in AdaCore Static Analysis ToolsGNAT Pro User Day: Latest Advances in AdaCore Static Analysis Tools
GNAT Pro User Day: Latest Advances in AdaCore Static Analysis Tools
 
Test-Driven Development
Test-Driven DevelopmentTest-Driven Development
Test-Driven Development
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing Software
 
Awesome Test Automation Made Simple w/ Dave Haeffner
Awesome Test Automation Made Simple w/ Dave HaeffnerAwesome Test Automation Made Simple w/ Dave Haeffner
Awesome Test Automation Made Simple w/ Dave Haeffner
 
Code coverage
Code coverageCode coverage
Code coverage
 
Battle for Code Quality - A Story of One Java Project
Battle for Code Quality - A Story of One Java ProjectBattle for Code Quality - A Story of One Java Project
Battle for Code Quality - A Story of One Java Project
 
Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Adob...
Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Adob...Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Adob...
Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Adob...
 
Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Into...
Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Into...Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Into...
Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Into...
 

Más de SQALab

Más de 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 или как тест-менеджеру перекроить внут...
 

Último

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Último (20)

ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 

Полезные метрики покрытия. Практический опыт и немного теории

  • 1. <Insert Picture Here> Полезные метрики покрытия Практический опыт и немного теории Александр (Шура) Ильин JavaSE quality architect
  • 2. What's this NOT about? • Not about a particular code coverage tool • Different tools for different needs • Not about hoe to write tests to reach higher code coverage • There are different techniques • No data for the projects I am working on • Sorry.
  • 3. What's this about? • Personal experience • My • Yours (depends on speaker abilities to speak fast) • Using coverage as a metric • What metrics to select
  • 4. Disclaimer • The views expressed on this presentation belong to the presenter and do not necessarily reflect the views of Oracle • Докладчик работает в “продуктовой лавке” :) • Ideas, approaches and conclusions described are coming from experience of the presenter
  • 5. What's a metric • A type of measurement user to gauge some quantifiable components.
  • 6. What's a metric • A type of measurement user to gauge some quantifiable components. • Metrics also used to track progress toward a goal.
  • 7. What's a metric • A type of measurement user to gauge some quantifiable components. • Metrics also used to track progress toward a goal. • A goal must be SMART • Simple (who, what, where, when, which, why) • Measurable (has a metric) • Attainable (the metric has a target value) • Realistic (willing and able to work towards) • Timely (results arrive on time to be used)
  • 8. How do you test the application?
  • 9. How do you test the application? By tests
  • 10. How do you test the application? By tests Metrics • Number of tests • Passrate • Number of bugs • Etc, etc, etc
  • 11. How do you test the tests?
  • 12. How do you test the tests? Hm ….
  • 13. How do you test the tests? By … application?
  • 14. What's the goal of testing? • Prove the system working properly Practically impossible • Prove the system not working properly Never ending process • Verify conformance to requirements Too generic
  • 15. What's the goal of testing? • Prove the system working properly Practically impossible • Prove the system not working properly Never ending process • Verify conformance to requirements Too generic • Money (not to loose money on poor quality) Yep. I need my bills to be paid. • Report quality On time and accurately. Still, too abstract.
  • 16. What's a quality? Separate presentation. No holy war today.
  • 17. Two goals. * • Defect escape reduction • Test coverage (different kinds off) • All the rest is bullshit * • Misleading • Not to the point • No target (*) Honest opinion of the presenter
  • 18. Two goals. * • Defect escape reduction • Test coverage (different kinds off) • All the rest is rubbish * • Misleading • Not to the point • No target (*) Honest opinion of the presenter
  • 19. 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
  • 20. What's a bug escape metric? Ratio of defects sneaked out unnoticed # defects found after release # defects found after + # defects found before Perfect! Direct metric of quality of testing
  • 21. What's a bug escape metric? Ratio of defects sneaked out unnoticed # defects found after release # defects found after + # defects found before Perfect! Direct metric of quality of testing Problem: coming too late!
  • 22. Is defect escape a good metric? • Simple (+.) • Measurable (+) • Attainable (?) • Realistic • Timely (-!)
  • 23. What's test coverage? A ratio of some numerable items “covered” in testing. # tested / # existing Implementation coverage Specification coverage • Code coverage • Requirement • Line, block • Assertion • Entry/exit • API • Branch/predicate • • UI Path/sequence • Race coverage • Data coverage • Data coverage Assumes test logic is right
  • 24. Code coverage Shows to what extent source code is covered • Class • Method (function) • Block • Line • Branch (condition)/predicate • Path (sequence) • Entry/exit
  • 25. Code coverage analysis – what for? A) Improve test base B) Find dead code 1.Measure coverage 1.Find something uncovered 2.Find uncovered code 2.Try to develop tests 3.Develop more tests 3.Fail 4.Goto 1. 4.Go to developers 5.Argue 6.Argue 7.Argue 8.Create a bug 9.Dead code removed C) Use as a metric
  • 26. Is code coverage a good metric? so far ... • Simple (+) • Measurable (+) • Attainable (?) • Realistic • Timely (+!)
  • 27. Block code coverage – what's the target? 100%? Unrealistic. 80%? Why not 78? 50%? What does it guarantee?
  • 28. 100% block/line coverage • Does it mean that all bugs found? Nope.
  • 29. 100% block/line coverage • Does it mean that all bugs found? Nope. • Does it mean that all scenarios tested? Nope.
  • 30. 100% block/line coverage • Does it mean that all bugs found? Nope. • Does it mean that all scenarios tested? Nope. • What does it mean, then? Nothing, really.
  • 34. Block code coverage – what's the target?
  • 35. ... target comes from ROI
  • 36. Is block/line coverage a good metric? • Simple (+) • Measurable (+) • Attainable (-) • Realistic • Timely (+!)
  • 37. Code coverage is very useful. • Tie CC data to • Code complexity • More complicated code is – more thorough testing it needs • Code stability • Recently changed code needs to be tested better • Bug density • Is there a correlation • Static analysis tools • To filter the false positives • Use CC as • Check-in criteria • Commit only if tested • Test selection • Run only tests for changed code • Hot spot detection • Usually coverage also shows hit counts
  • 38. What about 100% sequence coverage? Does it guarantee full testing?
  • 41. What about sequence coverage? • 100% sequence coverage does not prove a code to be fully tested • Libraries may have defects
  • 43. What about sequence coverage? • 100% sequence coverage does not prove a code to be fully tested • Libraries may have defects • Branches could be incorrect • 100% sequence + 100% predicate + 100% data +100% XYZ? • No idea • Have not seen a mathematical proof yet • Does not matter
  • 44. What else wrong with sequence coverage? • Tools availability • None for Java • Expensive • Execution • Analysis • Complicated • Not all paths are valid • Loops • 100% likely not attainable • number of paths is exponential to the number of branches
  • 45. Is sequence coverage a good metric? • Simple (+.) • Measurable (+) • Attainable (-.) • Realistic • Timely (+)
  • 46. 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
  • 47. 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
  • 48. So, is there a good coverage metric, then? Attainability seems to be the most trouble so far • Manageable amount of work • Obtain • Analyze • Improve • Clear target • Explainable • Verifiable
  • 49. Specification coverage • Requirements • Assertions • Public API • UI • Custom coverage metrics
  • 50. Assertions public final void wait(long timeout, int nanos) throws InterruptedException Causes current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object, or some other thread interrupts the current thread, or a certain amount of real time has elapsed.
  • 51. Assertions • Mark all the assertions with ID • Mark up the specification itself • Create a separate storage • Develop tests • An assertion deserves a few • A test could cover a few • Mark tests by assertion IDs • When next specification version is released • Compare assertions with a previous version • Verify all tests for changes assertions • Scan for new assertions • Develop new tests
  • 52. Requirements Same as assertions • Number the requirements • Mark the tests • Validate all tests when requirements change
  • 53. 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
  • 55. 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
  • 56. True public API example My code ArrayList.java
  • 57. (True) Public API • Is obtainable from code coverage • May require some work on top of existing CC tools True Public API • Does require some work on top of an existing CC tools • Emma, JCov
  • 58. UI coverage • % dialogs inspected • % menus pushed • % buttons pushed • % text fields was entered a value in • etc.
  • 59. UI coverage • In some cases obtainable from code coverage (works well for factory methods) • Action coverage: javax.swing.Action implementations • If not • “Instrument” the application • Adding test hooks • Using event queue • Obtain a “template” somehow else
  • 60. Are these metrics attainable? May be not in the beginning
  • 61. Are these metrics attainable? For every product to be claimed to be tested well, the target value is ...
  • 62. Are these metrics attainable? For every product to be claimed to be tested well, the target value is ... 100%
  • 63. Why 100%? • Every requirement must be tested by at least one test • Every statement in spec must be exercised at least once • Every method in public API must be called at least once • Every button in a UI needs to be pushed at least once For exceptions there are exclude lists.
  • 64. So, are these metrics good? • Simple (+) • Measurable (+) • Attainable (+) • Realistic • Timely (+)
  • 65. But wait … what is the point? • What does 100% public API coverage means? • UI coverage? • Specification coverage? • Requirements coverage?
  • 66. But wait … what is the point? • What does 100% public API coverage means? Nothing. • UI coverage? • Specification coverage? • Requirements coverage?
  • 67. But wait … what is the point? • What does 100% public API coverage means? Nothing. • UI coverage? Not that we are done with testing. • Specification coverage? • Requirements coverage?
  • 68. But wait … what is the point? • What does 100% public API coverage means? Nothing. • UI coverage? Not that we are done with testing. • Specification coverage? Not anywhere near with been done. • Requirements coverage?
  • 69. But wait … what is the point? • What does 100% public API coverage means? Nothing. • UI coverage? Not that we are done with testing. • Specification coverage? Not anywhere near with been done. • Requirements coverage? Well … at least we touched each and every of'm
  • 70. But wait … what is the point? • What does 100% public API coverage means? Nothing. • UI coverage? Not that we are done with testing. • Specification coverage? Not anywhere near with been done. • Requirements coverage? Well … at least we touched each and every of'm These metrics are required but not sufficient.
  • 71. More such metrics • Property coverage • Property is a field with a setter and getter • UML element coverage • In UML diagram • Language element coverage • Expression Language • Make your own.
  • 72. Summary No perfect coverage metric • Implementation based • target value comes from ROI • too heavy • yet do not prove anything • Specification based • Are not thorough enough
  • 73. Summary On the bright side, any of them could be useful • Test base improvement • Finding • Dead code • Untestable assertions • Unreachable UI • Etc.
  • 75. Alexandre (Shura) Iline Oracle Quality architect Java SE SQE group alexandre.iline@oracle.com