SlideShare a Scribd company logo
1 of 14
Download to read offline
Testing ORM base code
Viktor Turskyi
CTO at WebbyLab




Kiev 2012
Bad News

ORM-based code is database
dependent code

ORM framework is a blackbox
Good news

ORM is about objects and classes

We can do testing without object
persistency
Rule 1: No tests for simple classes
package Language;
use base qw(Rose::DB::Object);
__PACKAGE__->meta->setup(
     table    => 'languages',
     columns => [
          language_id => { type => 'varchar', length => 3, not_null => 1 },
          name       => { type => 'varchar', length => 64, not_null => 1 },
     ],
     primary_key_columns => [ 'language_id' ],
);




We do not test ORM framework - it has own
tests.
Rule 2: Try inject dependencies
package VAT;
use base qw(Rose::DB::Object);
__PACKAGE__->meta->setup(
     table => 'vats',
     columns => [
          vat_id => { type => 'varchar', length => 16, not_null => 1 },
          rate   => { type => 'integer', not_null => 1 },
     ],
     primary_key_columns => ['vat_id'],
);




sub netto2vat { ... }
sub brutto2vat { ... }
Real life VS tests
# In real life
my $vat = VAT->new(vat_id => 'VAT_20')->load();
my $vat_amount     = $vat->netto2vat(102.51);
...




# In tests
my $vat_obj =VAT->new( rate => 20 );




is( $vat_obj->brutto2vat(123.01), '20.50', 'Checking brutto2vat calculations' );
is( $vat_obj->brutto2vat(456.00), '76.00', 'Checking brutto2vat calculations' );




is( $vat_obj->netto2vat(102.51), '20.50', 'Checking netto2vat calculations' );
is( $vat_obj->netto2vat(380.00), '76.00', 'Checking netto2vat calculations' );
Real life VS tests (complex)
# In real life
my $fin_event = FinEvent->new(
     amount     => 102.22,
     # vat_object => ???
)->load();
my $amount = $fin_event->calculate_vat_amount();




# In tests
my $fin_event = FinEvent->new(
     vat_object => VAT->new( rate=>20 ),
     amount     => 102.22
);
is( $fin_event->calculate_vat_amount(), 20.44, 'VAT calculation' );
But still a lot of logic requires DB
So, bad news again:

In complex operation injection is not always
suitable due to complex dependencies

Using of DBI mock objects is not a good way
due to blackbox nature of the ORM framework

One Data Base for whole Model
Simple solution
Just to use the same predefined set of data for
all test
countries, users, companies, banks, materials, products, customers, partners,
vats, stocks, languages, currencies,currency rates, units... and a lot more



Shared set of predefined data worked until we
started work on aggregated reports. Every
report require a new set of test data which
breaks other tests data.
Rule 3: Individual test environment
for each tests set
Recreate database for each tests set?
=> It takes too much time :(


Use embedded DB like SQLite (you can copy file)?
=> It requires support of two database schemas :(


Manually delete data after each test?
=> It requires additional cleanup procedures :(
What we do?
Just revert transaction after test :)



use Test::More;




my $db = Rose::DB->new_or_cached();
$db->begin_work();




prepare_test_data();
do_testing();




$db->rollback();
Conclusions
Rule 1: No tests for simple classes

Rule 2: Try inject dependencies

Rule 3: Individual test environment for each test
Take a look at our tests
my $t = Test::Project->new(); # starts new transaction
$t->standard_setup()
    ->add_material_from_partner( 1200 )
    ->add_service_from_partner( 600, {date=>'2011-10-11'} )
    ->add_material_sale(60, {currency_rate=>800, currency_id=>'USD'})
;




iterate_test_data( 'report_a', sub {
     my $data = shift;
     my $report = Report::A->new(%{ $data->{input} });
     $t->test_correct_report($report, $data);
});




# on $t->DESTROY() - will revert transaction
Viktor Turskyi
viktor@webbylab.com

   http://koorchik.blogspot.com
 http://search.cpan.org/~koorchik/
   https://github.com/koorchik




           WebbyLab
       http://webbylab.com

More Related Content

What's hot

JavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and LodashJavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and LodashBret Little
 
Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracleyazidds2
 
Chaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscoreChaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscoreNicolas Carlo
 
PHP Traits
PHP TraitsPHP Traits
PHP Traitsmattbuzz
 
Better Together: Microsoft Azure Virtual Machines & PowerShell Desired State ...
Better Together: Microsoft Azure Virtual Machines & PowerShell Desired State ...Better Together: Microsoft Azure Virtual Machines & PowerShell Desired State ...
Better Together: Microsoft Azure Virtual Machines & PowerShell Desired State ...Oleg Chorny
 
Python 3.x Dictionaries and Sets Cheatsheet
Python 3.x Dictionaries and Sets CheatsheetPython 3.x Dictionaries and Sets Cheatsheet
Python 3.x Dictionaries and Sets CheatsheetIsham Rashik
 
Ian 2014.10.24 weekly report
Ian 2014.10.24 weekly reportIan 2014.10.24 weekly report
Ian 2014.10.24 weekly reportLearningTech
 
Micro(Lightweight) Django
Micro(Lightweight) DjangoMicro(Lightweight) Django
Micro(Lightweight) DjangoGrigory Petrov
 
Александр Терещук - Memory Analyzer Tool and memory optimization tips in Android
Александр Терещук - Memory Analyzer Tool and memory optimization tips in AndroidАлександр Терещук - Memory Analyzer Tool and memory optimization tips in Android
Александр Терещук - Memory Analyzer Tool and memory optimization tips in AndroidUA Mobile
 
Working With JQuery Part1
Working With JQuery Part1Working With JQuery Part1
Working With JQuery Part1saydin_soft
 
‎Unit tests automation for legacy code‎ at YAPC::NA 2016
‎Unit tests automation for legacy code‎ at YAPC::NA 2016‎Unit tests automation for legacy code‎ at YAPC::NA 2016
‎Unit tests automation for legacy code‎ at YAPC::NA 2016Denis Shirokov
 

What's hot (20)

JavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and LodashJavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and Lodash
 
Drools Ecosystem
Drools EcosystemDrools Ecosystem
Drools Ecosystem
 
Drupal 8 database api
Drupal 8 database apiDrupal 8 database api
Drupal 8 database api
 
Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracle
 
Lodash js
Lodash jsLodash js
Lodash js
 
Drools
DroolsDrools
Drools
 
Chaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscoreChaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscore
 
Lesson3
Lesson3Lesson3
Lesson3
 
Presentation cs313 (1)
Presentation cs313 (1)Presentation cs313 (1)
Presentation cs313 (1)
 
PHP Traits
PHP TraitsPHP Traits
PHP Traits
 
Django
Django Django
Django
 
Better Together: Microsoft Azure Virtual Machines & PowerShell Desired State ...
Better Together: Microsoft Azure Virtual Machines & PowerShell Desired State ...Better Together: Microsoft Azure Virtual Machines & PowerShell Desired State ...
Better Together: Microsoft Azure Virtual Machines & PowerShell Desired State ...
 
Python 3.x Dictionaries and Sets Cheatsheet
Python 3.x Dictionaries and Sets CheatsheetPython 3.x Dictionaries and Sets Cheatsheet
Python 3.x Dictionaries and Sets Cheatsheet
 
Bootstrap
BootstrapBootstrap
Bootstrap
 
Ian 2014.10.24 weekly report
Ian 2014.10.24 weekly reportIan 2014.10.24 weekly report
Ian 2014.10.24 weekly report
 
Micro(Lightweight) Django
Micro(Lightweight) DjangoMicro(Lightweight) Django
Micro(Lightweight) Django
 
Александр Терещук - Memory Analyzer Tool and memory optimization tips in Android
Александр Терещук - Memory Analyzer Tool and memory optimization tips in AndroidАлександр Терещук - Memory Analyzer Tool and memory optimization tips in Android
Александр Терещук - Memory Analyzer Tool and memory optimization tips in Android
 
Working With JQuery Part1
Working With JQuery Part1Working With JQuery Part1
Working With JQuery Part1
 
Road to react hooks
Road to react hooksRoad to react hooks
Road to react hooks
 
‎Unit tests automation for legacy code‎ at YAPC::NA 2016
‎Unit tests automation for legacy code‎ at YAPC::NA 2016‎Unit tests automation for legacy code‎ at YAPC::NA 2016
‎Unit tests automation for legacy code‎ at YAPC::NA 2016
 

Viewers also liked

Maybe you do not know that ...
Maybe you do not know that ...Maybe you do not know that ...
Maybe you do not know that ...Viktor Turskyi
 
JS Lab 2016 - Frontend trends 2015 - 2016
JS Lab 2016 - Frontend trends 2015 - 2016JS Lab 2016 - Frontend trends 2015 - 2016
JS Lab 2016 - Frontend trends 2015 - 2016Viktor Turskyi
 
Language Independent Validation Rules (LIVR)
Language Independent Validation Rules (LIVR)Language Independent Validation Rules (LIVR)
Language Independent Validation Rules (LIVR)Viktor Turskyi
 
Kharkiv JS 2015 - Creating isomorphic applications in React (en)
Kharkiv JS  2015 - Creating isomorphic applications in React (en)Kharkiv JS  2015 - Creating isomorphic applications in React (en)
Kharkiv JS 2015 - Creating isomorphic applications in React (en)Viktor Turskyi
 
It's Quiz - Cloud testing platform
It's Quiz - Cloud testing platformIt's Quiz - Cloud testing platform
It's Quiz - Cloud testing platformViktor Turskyi
 

Viewers also liked (7)

Hadoop webcamp 2015
Hadoop webcamp 2015 Hadoop webcamp 2015
Hadoop webcamp 2015
 
Maybe you do not know that ...
Maybe you do not know that ...Maybe you do not know that ...
Maybe you do not know that ...
 
JS Lab 2016 - Frontend trends 2015 - 2016
JS Lab 2016 - Frontend trends 2015 - 2016JS Lab 2016 - Frontend trends 2015 - 2016
JS Lab 2016 - Frontend trends 2015 - 2016
 
Excel in Javascript
Excel in JavascriptExcel in Javascript
Excel in Javascript
 
Language Independent Validation Rules (LIVR)
Language Independent Validation Rules (LIVR)Language Independent Validation Rules (LIVR)
Language Independent Validation Rules (LIVR)
 
Kharkiv JS 2015 - Creating isomorphic applications in React (en)
Kharkiv JS  2015 - Creating isomorphic applications in React (en)Kharkiv JS  2015 - Creating isomorphic applications in React (en)
Kharkiv JS 2015 - Creating isomorphic applications in React (en)
 
It's Quiz - Cloud testing platform
It's Quiz - Cloud testing platformIt's Quiz - Cloud testing platform
It's Quiz - Cloud testing platform
 

Similar to Testing orm based code

MT_01_unittest_python.pdf
MT_01_unittest_python.pdfMT_01_unittest_python.pdf
MT_01_unittest_python.pdfHans Jones
 
Php Unit With Zend Framework Zendcon09
Php Unit With Zend Framework   Zendcon09Php Unit With Zend Framework   Zendcon09
Php Unit With Zend Framework Zendcon09Michelangelo van Dam
 
Meet Magento Belarus debug Pavel Novitsky (eng)
Meet Magento Belarus debug Pavel Novitsky (eng)Meet Magento Belarus debug Pavel Novitsky (eng)
Meet Magento Belarus debug Pavel Novitsky (eng)Pavel Novitsky
 
Testing in Laravel
Testing in LaravelTesting in Laravel
Testing in LaravelAhmed Yahia
 
Modernising Legacy Code
Modernising Legacy CodeModernising Legacy Code
Modernising Legacy CodeSamThePHPDev
 
EVERYTHING ABOUT STATIC CODE ANALYSIS FOR A JAVA PROGRAMMER
EVERYTHING ABOUT STATIC CODE ANALYSIS FOR A JAVA PROGRAMMEREVERYTHING ABOUT STATIC CODE ANALYSIS FOR A JAVA PROGRAMMER
EVERYTHING ABOUT STATIC CODE ANALYSIS FOR A JAVA PROGRAMMERAndrey Karpov
 
Introduction to Unit Testing with PHPUnit
Introduction to Unit Testing with PHPUnitIntroduction to Unit Testing with PHPUnit
Introduction to Unit Testing with PHPUnitMichelangelo van Dam
 
Intro to Testing in Zope, Plone
Intro to Testing in Zope, PloneIntro to Testing in Zope, Plone
Intro to Testing in Zope, PloneQuintagroup
 
Test in action week 3
Test in action   week 3Test in action   week 3
Test in action week 3Yi-Huan Chan
 
Effective Unit Test Style Guide
Effective Unit Test Style GuideEffective Unit Test Style Guide
Effective Unit Test Style GuideJacky Lai
 
Building Better Applications with Data::Manager
Building Better Applications with Data::ManagerBuilding Better Applications with Data::Manager
Building Better Applications with Data::ManagerJay Shirley
 
Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Michelangelo van Dam
 
Structured Testing Framework
Structured Testing FrameworkStructured Testing Framework
Structured Testing Frameworkserzar
 
Testing Code and Assuring Quality
Testing Code and Assuring QualityTesting Code and Assuring Quality
Testing Code and Assuring QualityKent Cowgill
 
Unit test candidate solutions
Unit test candidate solutionsUnit test candidate solutions
Unit test candidate solutionsbenewu
 

Similar to Testing orm based code (20)

Test driven development_for_php
Test driven development_for_phpTest driven development_for_php
Test driven development_for_php
 
MT_01_unittest_python.pdf
MT_01_unittest_python.pdfMT_01_unittest_python.pdf
MT_01_unittest_python.pdf
 
Php Unit With Zend Framework Zendcon09
Php Unit With Zend Framework   Zendcon09Php Unit With Zend Framework   Zendcon09
Php Unit With Zend Framework Zendcon09
 
Meet Magento Belarus debug Pavel Novitsky (eng)
Meet Magento Belarus debug Pavel Novitsky (eng)Meet Magento Belarus debug Pavel Novitsky (eng)
Meet Magento Belarus debug Pavel Novitsky (eng)
 
Testing in Laravel
Testing in LaravelTesting in Laravel
Testing in Laravel
 
Php tests tips
Php tests tipsPhp tests tips
Php tests tips
 
Modernising Legacy Code
Modernising Legacy CodeModernising Legacy Code
Modernising Legacy Code
 
Unit testing zend framework apps
Unit testing zend framework appsUnit testing zend framework apps
Unit testing zend framework apps
 
EVERYTHING ABOUT STATIC CODE ANALYSIS FOR A JAVA PROGRAMMER
EVERYTHING ABOUT STATIC CODE ANALYSIS FOR A JAVA PROGRAMMEREVERYTHING ABOUT STATIC CODE ANALYSIS FOR A JAVA PROGRAMMER
EVERYTHING ABOUT STATIC CODE ANALYSIS FOR A JAVA PROGRAMMER
 
PHPUnit testing to Zend_Test
PHPUnit testing to Zend_TestPHPUnit testing to Zend_Test
PHPUnit testing to Zend_Test
 
Introduction to Unit Testing with PHPUnit
Introduction to Unit Testing with PHPUnitIntroduction to Unit Testing with PHPUnit
Introduction to Unit Testing with PHPUnit
 
Intro to Testing in Zope, Plone
Intro to Testing in Zope, PloneIntro to Testing in Zope, Plone
Intro to Testing in Zope, Plone
 
Test in action week 3
Test in action   week 3Test in action   week 3
Test in action week 3
 
Effective Unit Test Style Guide
Effective Unit Test Style GuideEffective Unit Test Style Guide
Effective Unit Test Style Guide
 
Building Better Applications with Data::Manager
Building Better Applications with Data::ManagerBuilding Better Applications with Data::Manager
Building Better Applications with Data::Manager
 
Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12
 
Structured Testing Framework
Structured Testing FrameworkStructured Testing Framework
Structured Testing Framework
 
Testing Code and Assuring Quality
Testing Code and Assuring QualityTesting Code and Assuring Quality
Testing Code and Assuring Quality
 
Test driven development
Test driven developmentTest driven development
Test driven development
 
Unit test candidate solutions
Unit test candidate solutionsUnit test candidate solutions
Unit test candidate solutions
 

More from Viktor Turskyi

How to create a high performance excel engine in java script
How to create a high performance excel engine in java scriptHow to create a high performance excel engine in java script
How to create a high performance excel engine in java scriptViktor Turskyi
 
Livr 2.0 in JS - Vinnytsia.JS 2019
Livr 2.0 in JS - Vinnytsia.JS 2019Livr 2.0 in JS - Vinnytsia.JS 2019
Livr 2.0 in JS - Vinnytsia.JS 2019Viktor Turskyi
 
The working architecture of node js applications open tech week javascript ...
The working architecture of node js applications   open tech week javascript ...The working architecture of node js applications   open tech week javascript ...
The working architecture of node js applications open tech week javascript ...Viktor Turskyi
 
Yet another json rpc library (mole rpc)
Yet another json rpc library (mole rpc)Yet another json rpc library (mole rpc)
Yet another json rpc library (mole rpc)Viktor Turskyi
 
KharkivJS 2018 Information Security Practice
KharkivJS 2018 Information Security PracticeKharkivJS 2018 Information Security Practice
KharkivJS 2018 Information Security PracticeViktor Turskyi
 
"Offline mode for a mobile application, redux on server and a little bit abou...
"Offline mode for a mobile application, redux on server and a little bit abou..."Offline mode for a mobile application, redux on server and a little bit abou...
"Offline mode for a mobile application, redux on server and a little bit abou...Viktor Turskyi
 
The working architecture of NodeJs applications
The working architecture of NodeJs applicationsThe working architecture of NodeJs applications
The working architecture of NodeJs applicationsViktor Turskyi
 
Language Independent Validation Rules 2.0, Viktor Turskyi, talk at OSDN 2017
Language Independent Validation Rules 2.0, Viktor Turskyi, talk at OSDN 2017Language Independent Validation Rules 2.0, Viktor Turskyi, talk at OSDN 2017
Language Independent Validation Rules 2.0, Viktor Turskyi, talk at OSDN 2017Viktor Turskyi
 
How to extract information from text with Semgrex
How to extract information from text with SemgrexHow to extract information from text with Semgrex
How to extract information from text with SemgrexViktor Turskyi
 
How to translate your Single Page Application - Webcamp 2016 (en)
How to translate your Single Page Application - Webcamp 2016 (en)How to translate your Single Page Application - Webcamp 2016 (en)
How to translate your Single Page Application - Webcamp 2016 (en)Viktor Turskyi
 
Kharkiv JS 2015: Боль и радость создания изоморфных приложений на ReactJS (RU)
Kharkiv JS  2015: Боль и радость создания изоморфных приложений на ReactJS (RU)Kharkiv JS  2015: Боль и радость создания изоморфных приложений на ReactJS (RU)
Kharkiv JS 2015: Боль и радость создания изоморфных приложений на ReactJS (RU)Viktor Turskyi
 
Mapreduce in JavaScript
Mapreduce in JavaScriptMapreduce in JavaScript
Mapreduce in JavaScriptViktor Turskyi
 

More from Viktor Turskyi (12)

How to create a high performance excel engine in java script
How to create a high performance excel engine in java scriptHow to create a high performance excel engine in java script
How to create a high performance excel engine in java script
 
Livr 2.0 in JS - Vinnytsia.JS 2019
Livr 2.0 in JS - Vinnytsia.JS 2019Livr 2.0 in JS - Vinnytsia.JS 2019
Livr 2.0 in JS - Vinnytsia.JS 2019
 
The working architecture of node js applications open tech week javascript ...
The working architecture of node js applications   open tech week javascript ...The working architecture of node js applications   open tech week javascript ...
The working architecture of node js applications open tech week javascript ...
 
Yet another json rpc library (mole rpc)
Yet another json rpc library (mole rpc)Yet another json rpc library (mole rpc)
Yet another json rpc library (mole rpc)
 
KharkivJS 2018 Information Security Practice
KharkivJS 2018 Information Security PracticeKharkivJS 2018 Information Security Practice
KharkivJS 2018 Information Security Practice
 
"Offline mode for a mobile application, redux on server and a little bit abou...
"Offline mode for a mobile application, redux on server and a little bit abou..."Offline mode for a mobile application, redux on server and a little bit abou...
"Offline mode for a mobile application, redux on server and a little bit abou...
 
The working architecture of NodeJs applications
The working architecture of NodeJs applicationsThe working architecture of NodeJs applications
The working architecture of NodeJs applications
 
Language Independent Validation Rules 2.0, Viktor Turskyi, talk at OSDN 2017
Language Independent Validation Rules 2.0, Viktor Turskyi, talk at OSDN 2017Language Independent Validation Rules 2.0, Viktor Turskyi, talk at OSDN 2017
Language Independent Validation Rules 2.0, Viktor Turskyi, talk at OSDN 2017
 
How to extract information from text with Semgrex
How to extract information from text with SemgrexHow to extract information from text with Semgrex
How to extract information from text with Semgrex
 
How to translate your Single Page Application - Webcamp 2016 (en)
How to translate your Single Page Application - Webcamp 2016 (en)How to translate your Single Page Application - Webcamp 2016 (en)
How to translate your Single Page Application - Webcamp 2016 (en)
 
Kharkiv JS 2015: Боль и радость создания изоморфных приложений на ReactJS (RU)
Kharkiv JS  2015: Боль и радость создания изоморфных приложений на ReactJS (RU)Kharkiv JS  2015: Боль и радость создания изоморфных приложений на ReactJS (RU)
Kharkiv JS 2015: Боль и радость создания изоморфных приложений на ReactJS (RU)
 
Mapreduce in JavaScript
Mapreduce in JavaScriptMapreduce in JavaScript
Mapreduce in JavaScript
 

Recently uploaded

Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Neo4j
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsAndrey Dotsenko
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 

Recently uploaded (20)

Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 

Testing orm based code

  • 1. Testing ORM base code Viktor Turskyi CTO at WebbyLab Kiev 2012
  • 2. Bad News ORM-based code is database dependent code ORM framework is a blackbox
  • 3. Good news ORM is about objects and classes We can do testing without object persistency
  • 4. Rule 1: No tests for simple classes package Language; use base qw(Rose::DB::Object); __PACKAGE__->meta->setup( table => 'languages', columns => [ language_id => { type => 'varchar', length => 3, not_null => 1 }, name => { type => 'varchar', length => 64, not_null => 1 }, ], primary_key_columns => [ 'language_id' ], ); We do not test ORM framework - it has own tests.
  • 5. Rule 2: Try inject dependencies package VAT; use base qw(Rose::DB::Object); __PACKAGE__->meta->setup( table => 'vats', columns => [ vat_id => { type => 'varchar', length => 16, not_null => 1 }, rate => { type => 'integer', not_null => 1 }, ], primary_key_columns => ['vat_id'], ); sub netto2vat { ... } sub brutto2vat { ... }
  • 6. Real life VS tests # In real life my $vat = VAT->new(vat_id => 'VAT_20')->load(); my $vat_amount = $vat->netto2vat(102.51); ... # In tests my $vat_obj =VAT->new( rate => 20 ); is( $vat_obj->brutto2vat(123.01), '20.50', 'Checking brutto2vat calculations' ); is( $vat_obj->brutto2vat(456.00), '76.00', 'Checking brutto2vat calculations' ); is( $vat_obj->netto2vat(102.51), '20.50', 'Checking netto2vat calculations' ); is( $vat_obj->netto2vat(380.00), '76.00', 'Checking netto2vat calculations' );
  • 7. Real life VS tests (complex) # In real life my $fin_event = FinEvent->new( amount => 102.22, # vat_object => ??? )->load(); my $amount = $fin_event->calculate_vat_amount(); # In tests my $fin_event = FinEvent->new( vat_object => VAT->new( rate=>20 ), amount => 102.22 ); is( $fin_event->calculate_vat_amount(), 20.44, 'VAT calculation' );
  • 8. But still a lot of logic requires DB So, bad news again: In complex operation injection is not always suitable due to complex dependencies Using of DBI mock objects is not a good way due to blackbox nature of the ORM framework One Data Base for whole Model
  • 9. Simple solution Just to use the same predefined set of data for all test countries, users, companies, banks, materials, products, customers, partners, vats, stocks, languages, currencies,currency rates, units... and a lot more Shared set of predefined data worked until we started work on aggregated reports. Every report require a new set of test data which breaks other tests data.
  • 10. Rule 3: Individual test environment for each tests set Recreate database for each tests set? => It takes too much time :( Use embedded DB like SQLite (you can copy file)? => It requires support of two database schemas :( Manually delete data after each test? => It requires additional cleanup procedures :(
  • 11. What we do? Just revert transaction after test :) use Test::More; my $db = Rose::DB->new_or_cached(); $db->begin_work(); prepare_test_data(); do_testing(); $db->rollback();
  • 12. Conclusions Rule 1: No tests for simple classes Rule 2: Try inject dependencies Rule 3: Individual test environment for each test
  • 13. Take a look at our tests my $t = Test::Project->new(); # starts new transaction $t->standard_setup() ->add_material_from_partner( 1200 ) ->add_service_from_partner( 600, {date=>'2011-10-11'} ) ->add_material_sale(60, {currency_rate=>800, currency_id=>'USD'}) ; iterate_test_data( 'report_a', sub { my $data = shift; my $report = Report::A->new(%{ $data->{input} }); $t->test_correct_report($report, $data); }); # on $t->DESTROY() - will revert transaction
  • 14. Viktor Turskyi viktor@webbylab.com http://koorchik.blogspot.com http://search.cpan.org/~koorchik/ https://github.com/koorchik WebbyLab http://webbylab.com