The document discusses various bad practices for unit testing code. It begins with background about the author and importance of test quality. It then covers specific test smells like code duplication, assertion roulette, eager tests, fragile tests, and tests with obscure or unclear purpose. Examples are provided from testing Zend Framework and Doctrine code. The author advocates for well-structured tests that isolate dependencies and clearly validate single behaviors or scenarios.
Slides from my presentation at DunDDD, 17th Nov 2012.
Most of this session was spent discussing unit test examples harvested from github. If anyone would like to see them, just ask.
Adding Dependency Injection to Legacy ApplicationsSam Hennessy
Dependency Injection (DI) is a fantastic technique, but what if you what to use dependency injection in your legacy application. Fear not! As someone who as done this very thing, I will show how you can successful and incrementally add DI to any application. I will present a number of recipes and solutions to common problems and give a tour of the various PHP DI projects and how they can help.
In 2010, I told everyone how to start unit testing Zend Framework applications. In 2011, let’s take this a step further by testing services, work flows and performance. Looking to raise the bar on quality? Let this talk be the push you need to improve your Zend Framework projects.
From typing the test to testing the typeWim Godden
PHP unit testing + new PHPUnit patch for type testing functionality
Seems bullet points are not working and some of the slides are not so clear because of Slideshare conversion.
Presentation given at phpBenelux meeting August 25, 2010
Slides from my presentation at DunDDD, 17th Nov 2012.
Most of this session was spent discussing unit test examples harvested from github. If anyone would like to see them, just ask.
Adding Dependency Injection to Legacy ApplicationsSam Hennessy
Dependency Injection (DI) is a fantastic technique, but what if you what to use dependency injection in your legacy application. Fear not! As someone who as done this very thing, I will show how you can successful and incrementally add DI to any application. I will present a number of recipes and solutions to common problems and give a tour of the various PHP DI projects and how they can help.
In 2010, I told everyone how to start unit testing Zend Framework applications. In 2011, let’s take this a step further by testing services, work flows and performance. Looking to raise the bar on quality? Let this talk be the push you need to improve your Zend Framework projects.
From typing the test to testing the typeWim Godden
PHP unit testing + new PHPUnit patch for type testing functionality
Seems bullet points are not working and some of the slides are not so clear because of Slideshare conversion.
Presentation given at phpBenelux meeting August 25, 2010
Abstract: Oracle released a feature in 10g Release 2 they thought worthy of facilitating in previous versions via patch sets - so I thought it was worthy enough for a closer look.
Conditional compilation isn't a foreign concept in the programming world, and for the developer aficionado it's a wonderful paradigm to explore.
Conditional compilation was designed with the main intention of being able to create database version specific code. With the recent advent of 11g, developers can actually start adding 11g features to their 10g code today!
However it provides the savvy PL/SQL developer to enhance their code in more ways than just gearing up for the next release… Dust of your software engineering hats and discover how to utilise conditional compilation to explore concepts such as latent self tracing code; latent assertions; and enhanced prototyping for your unit tests.
This seminar will illustrate several examples of conditional compilation that will open your mind; ultimately benefit your users; and can be implemented as far back as 9.2!
When it comes to writing tests we often live in the here-and-now and consequently end up producing "write-only" tests. This session looks at what we need to consider if we want to create tests that our future selves and teammates will find valuable instead of becoming another burden on top of delivering the feature itself.
If there is one place that we find it easy to take shortcuts it's when writing tests. Whether we're under the cosh or have an overly-optimistic view of our ability to write self-documenting code, instead of creating tests that support the production code and development process we can find ourselves producing WTFs (Weak Test Functions). The net effect is often a viscous cycle that disparages, instead of encourages us.
In the past I've tried many different ways to try and short-circuit the test writing process, but have only come-up short every time. This session takes a look at why skimping on elements of the test structure, such as organisation, naming and scope only leads to pain and hardship in the long run. Along the way we'll uncover the truth behind common folklore, such as only having one assertion per test.
사내 기술 세미나를 다시 시작한다. 나는 그 첫번째 주제로 `Object-oriented Javascript`를 택했다.
예전에 학습했던 [Tuts+ 강의](https://code.tutsplus.com/courses/object-oriented-javascript)를 다시 정리하는 계기가 되었다.
Software development is riddled with explicit and implicit costs. Every decision you make has a cost attached to it. When you're writing code, you're making an investment, the size of which will for a long time define the costs of your future growth. Making right decision about these investments is very tricky and the cost of wrong decisions might be crippling for both business and teams that support it.
Extreme Programming and Test Driven Development in particular are practices that are aiming at supporting development effort by making it easier to introduce change. That said, sometimes those tools can become a problem of its own when applied in the wrong way or for the wrong context. Understanding software cost forces is a very important skill of successful teams and something that helps understand how to apply XP and TDD in different contexts.
Testing, Performance Analysis, and jQuery 1.4jeresig
This is the talk that I gave at JSConf.eu 2009, then modified slightly and given again at the December Bayjax meetup (the parts on jQuery and HTML 5 in IE were added).
Software development is riddled with explicit and implicit costs. Every decision you make has a cost attached to it. When you're writing code, you're making an investment, the size of which will for a long time define the costs of your future growth. In this talk you will learn how to see, understand and game some of these forces in your favour.
Est-ce que nous allons parler de gestion des ressources humaines au PHP tour ? Non, je vous vais vous parler des modèles anémiques et des modèles riches. Depuis des années frameworks et ORM nous conditionnent à utiliser des modèles anémiques, une classe avec de simples setters et getters. A travers l’histoire d’Estelle, une RH, qui veut une application pour gérer ses salariés, je vais vous montrer comment changer nos vieilles habitudes afin de nous focaliser sur le métier que nous implémentons. Nous verrons ensemble quels outils utiliser, comme par exemple, le design pattern command bus, l’opérateur NEW de doctrine pour vos Data Transfert Object dans une application Symfony.
Example de code : https://github.com/arnolanglade/code-me-hr
The slides of my talk "Mockist vs. Classicists TDD" at the Softwerkskammer Berlin Meetup http://www.meetup.com/de-DE/Software-Craftsmanship-Berlin/events/227959647/.
Abstract:
There are two different schools of TDD: the proponents of "London School TDD" ("Mockists") drive their design "outside-in" top-down starting with end-to-end acceptance tests. They focus on the interaction between objects, isolate them with interfaces between them and mock them out in their tests. On the contrary the advocates of "Detroit School TDD" ("Classicists") work bottom-up and try to avoid mocks if possible.
In a live coding session I will demonstrate both approaches and discuss their strengths and weaknesses with you.
Abstract: Oracle released a feature in 10g Release 2 they thought worthy of facilitating in previous versions via patch sets - so I thought it was worthy enough for a closer look.
Conditional compilation isn't a foreign concept in the programming world, and for the developer aficionado it's a wonderful paradigm to explore.
Conditional compilation was designed with the main intention of being able to create database version specific code. With the recent advent of 11g, developers can actually start adding 11g features to their 10g code today!
However it provides the savvy PL/SQL developer to enhance their code in more ways than just gearing up for the next release… Dust of your software engineering hats and discover how to utilise conditional compilation to explore concepts such as latent self tracing code; latent assertions; and enhanced prototyping for your unit tests.
This seminar will illustrate several examples of conditional compilation that will open your mind; ultimately benefit your users; and can be implemented as far back as 9.2!
When it comes to writing tests we often live in the here-and-now and consequently end up producing "write-only" tests. This session looks at what we need to consider if we want to create tests that our future selves and teammates will find valuable instead of becoming another burden on top of delivering the feature itself.
If there is one place that we find it easy to take shortcuts it's when writing tests. Whether we're under the cosh or have an overly-optimistic view of our ability to write self-documenting code, instead of creating tests that support the production code and development process we can find ourselves producing WTFs (Weak Test Functions). The net effect is often a viscous cycle that disparages, instead of encourages us.
In the past I've tried many different ways to try and short-circuit the test writing process, but have only come-up short every time. This session takes a look at why skimping on elements of the test structure, such as organisation, naming and scope only leads to pain and hardship in the long run. Along the way we'll uncover the truth behind common folklore, such as only having one assertion per test.
사내 기술 세미나를 다시 시작한다. 나는 그 첫번째 주제로 `Object-oriented Javascript`를 택했다.
예전에 학습했던 [Tuts+ 강의](https://code.tutsplus.com/courses/object-oriented-javascript)를 다시 정리하는 계기가 되었다.
Software development is riddled with explicit and implicit costs. Every decision you make has a cost attached to it. When you're writing code, you're making an investment, the size of which will for a long time define the costs of your future growth. Making right decision about these investments is very tricky and the cost of wrong decisions might be crippling for both business and teams that support it.
Extreme Programming and Test Driven Development in particular are practices that are aiming at supporting development effort by making it easier to introduce change. That said, sometimes those tools can become a problem of its own when applied in the wrong way or for the wrong context. Understanding software cost forces is a very important skill of successful teams and something that helps understand how to apply XP and TDD in different contexts.
Testing, Performance Analysis, and jQuery 1.4jeresig
This is the talk that I gave at JSConf.eu 2009, then modified slightly and given again at the December Bayjax meetup (the parts on jQuery and HTML 5 in IE were added).
Software development is riddled with explicit and implicit costs. Every decision you make has a cost attached to it. When you're writing code, you're making an investment, the size of which will for a long time define the costs of your future growth. In this talk you will learn how to see, understand and game some of these forces in your favour.
Est-ce que nous allons parler de gestion des ressources humaines au PHP tour ? Non, je vous vais vous parler des modèles anémiques et des modèles riches. Depuis des années frameworks et ORM nous conditionnent à utiliser des modèles anémiques, une classe avec de simples setters et getters. A travers l’histoire d’Estelle, une RH, qui veut une application pour gérer ses salariés, je vais vous montrer comment changer nos vieilles habitudes afin de nous focaliser sur le métier que nous implémentons. Nous verrons ensemble quels outils utiliser, comme par exemple, le design pattern command bus, l’opérateur NEW de doctrine pour vos Data Transfert Object dans une application Symfony.
Example de code : https://github.com/arnolanglade/code-me-hr
The slides of my talk "Mockist vs. Classicists TDD" at the Softwerkskammer Berlin Meetup http://www.meetup.com/de-DE/Software-Craftsmanship-Berlin/events/227959647/.
Abstract:
There are two different schools of TDD: the proponents of "London School TDD" ("Mockists") drive their design "outside-in" top-down starting with end-to-end acceptance tests. They focus on the interaction between objects, isolate them with interfaces between them and mock them out in their tests. On the contrary the advocates of "Detroit School TDD" ("Classicists") work bottom-up and try to avoid mocks if possible.
In a live coding session I will demonstrate both approaches and discuss their strengths and weaknesses with you.
Василий Сорокин, “Google C++ Mocking and Test Frameworks”Platonov Sergey
В докладе рассказано как использовать Google Test Framework в своем проекте для организации юнит-тестирования. Показаны способы создания тестов, параметризованных тестов. Также рассмотрен Google Mocking Framework, рассказано, что это такое, и показаны некоторые приемы работы с ним. Несколько слов об особенностях использования этих фреймворков в Qt проектах.
В докладе рассказывается об опыте применения «инверсия управления» (Inversion of Control) при разработке новой версии KES. Этот подход заключается в том, что более высокоуровневый код не зависит напрямую от конкретной реализации нижележащего слоя. Вместо этого он зависит от абстрактного протокола (интерфейса), конкретный же компонент подставляется конфигурационным кодом-клиентом. Эта практика позволяет понизить loose coupling программных модулей и применяется практически в любых крупных проектах.
При разработке новой версии KES было принято решение изменить подход к реализации инверсии управления. Было решено отказаться от централизованного обобщенного реестра доступных компонентов (шаблон (паттерн) Service Locator) в пользу явной передачи зависимостей конфигуратором (ручная инъекция зависимостей (manual Dependency Injection)). При это возникли проблемы с использованием готовых библиотек Dependency Injection Frameworks. Применение подобных библиотек стало стандартом в мире разработки Java/C# за последние 10-15 лет, но в мире C++ они пока не получили подобного распространения. В докладе делается обзор и сравнение актуальных DI-Framework’ов на C++, анализируется их применимость к практическим задачам ЛК. Анализируется, что могут привнести стандарты C++11/14 для упрощения решения таких задач.
В докладе рассказывается об особенностях подхода к dependence injections в C++. Посмотрим какие подходы, в чем их плюсы и минусы. Также затрагивается тема Inversion of Control контейнеров.
Юнит-тестирование и Google Mock. Влад Лосев, Googleyaevents
Владимир Лосев, Google
Закончил математико-механический факультет Санкт-Петербургского государственного университета в 1995 году. Работал в компаниях Motоrola, Fair Isaac и Yahoo. С 2008 года работает в Google, в группе, занимающейся вопросами повышения производительности инженеров.
Тема доклада
Юнит-тестирование и Google Mock.
Тезисы
В модульных (юнит) тестах каждый элемент программы тестируется по отдельности, в изоляции от других. Такие тесты исполняются очень быстро, поэтому их можно запускать когда угодно, что позволяет отлавливать дефекты на самых ранних стадиях разработки. Однако для тестирования объекта в изоляции от других необходимо имитировать поведение связанных с ним объектов, что на C++ довольно утомительное занятие. Разработанная в Googlе библиотека для создания и использования mock-объектов — Google Mock — позволяет существенно упростить этот процесс и ускорить написание тестов. В докладе пойдет речь о принципах и возможностях библиотеки, примерах её использования и её внутреннем устройстве.
Павел Филонов, Разделяй и управляй вместе с Conan.ioSergey Platonov
Несмотря на солидный возраст С++, одной из больших проблем, возникающих при разработке с его использованием, до сих пор является управление зависимостям. Особенно остро этот вопрос возникает при наличии нескольких различных целевых платформ. В докладе будет рассмотрено, как менеджер пакетов Conan.io позволяет решить проблему управления зависимостями и, как следствие, значительно улучшить скорость разработки на C++ и повысить модульность разрабатываемых систем.
В данном докладе мы рассмотрим пять основных принципов дизайна классов в объектно-ориентированном проектировании, которые известны, как принципы SOLID. А также как обеспечить достаточный уровень гибкости, связанности, управляемости, стабильности и понятности кода.
Automated Testing for Embedded Software in C or C++Lars Thorup
When software developers write automated tests for their software, the quality increases, the design improves and the project becomes more manageable. The development also becomes more fun!
In this presentation you will learn how to write automated tests for embedded software. You will see a live demonstration of writing an automated test for a feedback control algorithm in C. I will also talk about the benefits of writing tests and why it can actually improve your design and save you time.
When having a large set of automated tests it becomes valuable to run all tests automatically every time the code is changed. I will touch upon what is the best continuous integration setup for embedded software projects.
Sample code can be downloaded from http://www.zealake.com/public/embedded-autotest.zip
So you are thinking of unit-testing the applications you work on a daily basis or already started to do so? Congratulations, but the really hard part is maintaining your test quality on such a high level so that you don't give up on testing down the road. In this talk I discuss unit-testing bad practices and test-smells, how to avoid them and show examples from open-source projects.
A lot of people using PHPunit for testing their source code. While I was observing my team I recognized most of them are only using the standard assertions like 'assertEquals()' and are complaining about how hard it is to test the code even when the tests are written first. This talk is about all the stuff not used on a daily basis and it digs deep into uncommon features of PHPUnit.
Refactoring, Agile Entwicklung, Continuous Integration – all diese für nachhaltigen Erfolg wichtigen Vorgehensweisen setzen Erfahrung mit Unit Testing voraus. Abseits von den üblichen "Bowling"-Beispielen möchten wir gerne einen Crashkurs inkl. Best Practices für das erfolgreiche Unit Testing durchführen. Anhand eines Beispielprojekts auf Basis des Zend Frameworks werden wir nach der Installation von PHPUnit auf allen Notebooks gemeinsam eine kleine Applikation aufbauen, die durchgehend Test-driven entwickelt wird.
A lot of people using PHPunit for testing their source code. While I was observing my team
I recognized most of them are only using the standard assertions like 'assertEquals()' or 'assertTrue()' and are complaining about how hard it is to test the code even when the tests are written first. This talk is about all the stuff not used on a daily basis. It shows you some nice features of PHPUnit and how to use them for your benefit.
You must’ve heard of Unit testing… If not, then this talk is definitely for you! If you do know Unit testing, you probably ran at some point into a hurdle: “Where do I start?” And despite your best efforts, you end up not having enough tests for your application – Then that change request comes in, requiring you to change that very same complex piece of code for which you are lacking tests! How do you going refactor while maintaining all those ‘undocumented’ business rules? This talk will show how Codeception can be leveraged to refactor the visuals aspects of an application, maintaining backwards compatibility on API changes and even assist in moving to a whole different server infrastructure.
Watch Erik's presentation on PHP Unit Testing to gain familiarity with unit tests and unit testing here at Tagged, with the testing framework currently in place and also learn how to write (better) unit tests. Download his slides here or email him at ejohannessen@tagged.com.
n 2010, I told everyone how to start unit testing Zend Framework applications. In 2011, let’s take this a step further by testing services, work flows and performance. Looking to raise the bar on quality? Let this talk be the push you need to improve your Zend Framework projects.
In this session the current automated testing infrastructure of the Joomla CMS is explained:
theory of system- & unit-tests
Joomla's unit testing setup
setting up your machine
how to execute the test suite
how to write a test
Joomla's system testing setup
setting up your machine
how to execute the test suite
how Joomla automates the automated tests
Feature Flags Are Flawed: Let's Make Them BetterStephen Young
An introduction to Feature Flags, canary deployments and finally, Swivel: A PHP library that will manage cohorts and features automatically for the developer.
Talk given in French at ConFoo 2015
Le TDD (Test Driven Development) gagne en popularité dans la communauté PHP. C’est maintenant une pratique accepté. Mais commencer peut sembler difficile.
Dans cette session, nous allons voir ce qu’est le TDD. Nous allons commencer par voir les principes. Puis les outils utilisés, et comment s’en servir au quotidien. Nous allons aussi voir les difficultés souvent rencontrées et comment les contourner.
If you don’t test it, how do you know it works? Over the past few years, we have been compelled to write unit and integration tests for our applications--code that validates code--and it is these tests that change a one-off tool into a well-architected, robust, business-ready application. Yet, every new framework requires a new testing framework, so in this session, we will discuss testing frameworks for node.js. You will walk away with a solid understanding of how to write tests against your node.js applications and modules, leading to confidence that your work is business-ready.
Replacing dependents with doubles is a central part of testing that every developer has to master. This talk goes over the different types of doubles and explains their place in testing, how to implement them in a mainstream mocking framework, and which strategies or doubles to use in different message exchange scenarios between objects. After this talk you will have moved a step forward in your understanding of testing in the context of object oriented programming.
A lot of people using PHPunit for testing their source code. While I was observing my team
I recognized most of them are only using the standard ssertions like 'assertEquals()' or
'assertTrue()' and are complaining about how hard it is to test the code even when the tests are written first. This talk is about all the stuff not used on a daily basis. It shows you some nice features of PHPUnit and how to use them for your benefit.
Similar to Unit-Testing Bad-Practices by Example (20)
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
Neuro-symbolic is not enough, we need neuro-*semantic*Frank van Harmelen
Neuro-symbolic (NeSy) AI is on the rise. However, simply machine learning on just any symbolic structure is not sufficient to really harvest the gains of NeSy. These will only be gained when the symbolic structures have an actual semantics. I give an operational definition of semantics as “predictable inference”.
All of this illustrated with link prediction over knowledge graphs, but the argument is general.
GraphRAG is All You need? LLM & Knowledge GraphGuy Korland
Guy Korland, CEO and Co-founder of FalkorDB, will review two articles on the integration of language models with knowledge graphs.
1. Unifying Large Language Models and Knowledge Graphs: A Roadmap.
https://arxiv.org/abs/2306.08302
2. Microsoft Research's GraphRAG paper and a review paper on various uses of knowledge graphs:
https://www.microsoft.com/en-us/research/blog/graphrag-unlocking-llm-discovery-on-narrative-private-data/
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
The publishing industry has been selling digital audiobooks and ebooks for over a decade and has found its groove. What’s changed? What has stayed the same? Where do we go from here? Join a group of leading sales peers from across the industry for a conversation about the lessons learned since the popularization of digital books, best practices, digital book supply chain management, and more.
Link to video recording: https://bnctechforum.ca/sessions/selling-digital-books-in-2024-insights-from-industry-leaders/
Presented by BookNet Canada on May 28, 2024, with support from the Department of Canadian Heritage.
Essentials of Automations: Optimizing FME Workflows with ParametersSafe Software
Are you looking to streamline your workflows and boost your projects’ efficiency? Do you find yourself searching for ways to add flexibility and control over your FME workflows? If so, you’re in the right place.
Join us for an insightful dive into the world of FME parameters, a critical element in optimizing workflow efficiency. This webinar marks the beginning of our three-part “Essentials of Automation” series. This first webinar is designed to equip you with the knowledge and skills to utilize parameters effectively: enhancing the flexibility, maintainability, and user control of your FME projects.
Here’s what you’ll gain:
- Essentials of FME Parameters: Understand the pivotal role of parameters, including Reader/Writer, Transformer, User, and FME Flow categories. Discover how they are the key to unlocking automation and optimization within your workflows.
- Practical Applications in FME Form: Delve into key user parameter types including choice, connections, and file URLs. Allow users to control how a workflow runs, making your workflows more reusable. Learn to import values and deliver the best user experience for your workflows while enhancing accuracy.
- Optimization Strategies in FME Flow: Explore the creation and strategic deployment of parameters in FME Flow, including the use of deployment and geometry parameters, to maximize workflow efficiency.
- Pro Tips for Success: Gain insights on parameterizing connections and leveraging new features like Conditional Visibility for clarity and simplicity.
We’ll wrap up with a glimpse into future webinars, followed by a Q&A session to address your specific questions surrounding this topic.
Don’t miss this opportunity to elevate your FME expertise and drive your projects to new heights of efficiency.
Securing your Kubernetes cluster_ a step-by-step guide to success !KatiaHIMEUR1
Today, after several years of existence, an extremely active community and an ultra-dynamic ecosystem, Kubernetes has established itself as the de facto standard in container orchestration. Thanks to a wide range of managed services, it has never been so easy to set up a ready-to-use Kubernetes cluster.
However, this ease of use means that the subject of security in Kubernetes is often left for later, or even neglected. This exposes companies to significant risks.
In this talk, I'll show you step-by-step how to secure your Kubernetes cluster for greater peace of mind and reliability.
UiPath Test Automation using UiPath Test Suite series, part 3DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 3. In this session, we will cover desktop automation along with UI automation.
Topics covered:
UI automation Introduction,
UI automation Sample
Desktop automation flow
Pradeep Chinnala, Senior Consultant Automation Developer @WonderBotz and UiPath MVP
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Ramesh Iyer
In today's fast-changing business world, Companies that adapt and embrace new ideas often need help to keep up with the competition. However, fostering a culture of innovation takes much work. It takes vision, leadership and willingness to take risks in the right proportion. Sachin Dev Duggal, co-founder of Builder.ai, has perfected the art of this balance, creating a company culture where creativity and growth are nurtured at each stage.
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Tobias Schneck
As AI technology is pushing into IT I was wondering myself, as an “infrastructure container kubernetes guy”, how get this fancy AI technology get managed from an infrastructure operational view? Is it possible to apply our lovely cloud native principals as well? What benefit’s both technologies could bring to each other?
Let me take this questions and provide you a short journey through existing deployment models and use cases for AI software. On practical examples, we discuss what cloud/on-premise strategy we may need for applying it to our own infrastructure to get it to work from an enterprise perspective. I want to give an overview about infrastructure requirements and technologies, what could be beneficial or limiting your AI use cases in an enterprise environment. An interactive Demo will give you some insides, what approaches I got already working for real.
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Albert Hoitingh
In this session I delve into the encryption technology used in Microsoft 365 and Microsoft Purview. Including the concepts of Customer Key and Double Key Encryption.
How world-class product teams are winning in the AI era by CEO and Founder, P...
Unit-Testing Bad-Practices by Example
1. Unit-Testing Bad-Practices
by Example
Benjamin Eberlei
direkt effekt GmbH
August 2009
Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices August 2009 1 / 49
2. About Me
Benjamin Eberlei
direkt effekt GmBH (digital marketing)
Zend Framework contributor
Test-Driven-Development, Legacy Testing
Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices August 2009 2 / 49
4. Why Test Quality Matters
Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices August 2009 4 / 49
5. “We spent 90% of the time
modifying existing tests to
acommodate for a relatively
minor change.“
(G. Meszaros, xUnit Test Patterns)
Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices August 2009 5 / 49
6. “Walking on water and
developing software from a
specification are easy if both
are frozen.”
(Edward V. Berard)
Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices August 2009 6 / 49
7. Safety Net vs Dead Weight
Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices August 2009 7 / 49
8. Test Smells
“Smell you later!”
(Nelson, The Simpsons)
Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices August 2009 8 / 49
10. ZF Controller Action
public function testInitView ()
{
Zen d_ C o n t r o l l e r _ Front :: getInstance () ->
s e t C o n t r o l l er Dir ec to ry ( ’/ _files ’) ;
require_once ’/ _files / ViewController . php ’;
$controller = new ViewController (
new Z e n d _ C o n t r o l l e r _ R e q u e s t _ H t t p () ,
new Z e n d _ C o n t r o l l e r _ R e s p o n s e _ C l i ()
);
$view = $controller - > initView () ;
$this - > assertTrue ( $view instanceof Zend_View ) ;
$scriptPath = $view - > getScriptPaths () ;
$this - > assertTrue ( is_array ( $scriptPath ) ) ;
$this - > assertEquals ( ’/ views / scripts / ’ , $scriptPath [0])
;
}
Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices August 2009 10 / 49
11. ZF Controller Action 2
public function testRenderByName ()
{
$request = new Z e n d _ C o n t r o l l e r _ R e q u e s t _ H t t p () ;
$request - > set ControllerName ( ’ view ’)
-> setActionName ( ’ test ’) ;
$response = new Z e n d _ C o n t r o l l e r _ R e s p o n s e _ C l i () ;
Zen d_ C o n t r o l l e r _ Front :: getInstance () ->
s e t C o n t r o l l er Dir ec to ry ( ’/ _files ’) ;
require_once ’/ _files / ViewController . php ’;
$controller = new ViewController ( $request , $response ) ;
$controller - > testAction () ;
$this - > assertContains ( ’ In the index action view ’ ,
$response - > getBody () ) ;
}
Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices August 2009 11 / 49
12. ZF Controller Refactoring
Extract Test Utility Method:
public function c r e ateViewController ( $controllerName = null ,
$actionName = null )
{
$request = new Z e n d _ C o n t r o l l e r _ R e q u e s t _ H t t p () ;
if ( $controllerName !== null ) {
$request - > setControllerName ( $controllerName ) ;
}
if ( $actionName !== null ) {
$request - > setActionName ( $actionName ) ;
}
$response = new Z e n d _ C o n t r o l l e r _ R e s p o n s e _ C l i () ;
Zen d_ C o n t r o l l e r _ Front :: getInstance ()
-> s e t C o n t r o l le rD ire ct or y ( ’/ _files ’) ;
require_once ’/ _files / ViewController . php ’;
return new ViewController ( $request , $response ) ;
}
Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices August 2009 12 / 49
13. ZF Controller Refactoring 2
public function t e s tI nit Vi ew Ref ac to red ()
{
// fixture setup
$controller = $this - > createViewController () ;
// execution
$view = $controller - > initView () ;
$scriptPath = $view - > getScriptPaths () ;
// assertions
$this - > assertTrue ( $view instanceof Zend_View ) ;
$this - > assertTrue ( is_array ( $scriptPath ) ) ;
$this - > assertEquals (
’/ views / scripts / ’ , $scriptPath [0]
);
}
Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices August 2009 13 / 49
14. ZF Controller Refactoring 3
public function t e s t R e n d e r B y N a m e R e f a c t o r e d ()
{
// fixture setup
$controller =
$this - > c r e a teViewController ( ’ view ’ , ’ test ’) ;
// execution
$controller - > testAction () ;
// assertions
$this - > assertContains (
’ In the index action view ’ ,
$response - > getBody ()
);
}
Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices August 2009 14 / 49
16. Doctrine ResultSetMapping
public function t e s t B a s i c Re s u l t S e t M a p p i n g ()
{
// Fixture Setup
$rsm = new ResultSetMapping () ;
$rsm - > addEntityResult (
’ Doctrine Tests Models CMS CmsUser ’ ,
’u ’
);
$rsm - > addFieldResult ( ’u ’ , ’ id ’ , ’ id ’) ;
$rsm - > addFieldResult ( ’u ’ , ’ status ’ , ’ status ’) ;
$rsm - > addFieldResult ( ’u ’ , ’ user ’ , ’ user ’) ;
$rsm - > addFieldResult ( ’u ’ , ’ name ’ , ’ name ’) ;
// [..]
}
Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices August 2009 16 / 49
17. Doctrine ResultSetMapping 2
public function t e s t B a s i c Re s u l t S e t M a p p i n g ()
{
// [..]
$this - > assertFalse ( $rsm - > isScalarResult ( ’ id ’) ) ;
$this - > assertFalse ( $rsm - > isScalarResult ( ’ status ’) ) ;
$this - > assertFalse ( $rsm - > isScalarResult ( ’ user ’) ) ;
$this - > assertFalse ( $rsm - > isScalarResult ( ’ name ’) ) ;
$this - > assertTrue (
$rsm - > getClass ( ’u ’) ==
’ Doctrine Tests Models CMS CmsUser ’
);
$class = $rsm - > getOwningClass ( ’ id ’) ;
$this - > assertTrue (
$class == ’ Doctrine Tests Models CMS CmsUser ’
);
}
Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices August 2009 17 / 49
18. Doctrine ResultSetMapping 3
public function t e s t B a s i c Re s u l t S e t M a p p i n g ()
{
// [..]
$this - > assertEquals ( ’u ’ , $rsm - > getAlias ( ’ id ’) ) ;
$this - > assertEquals ( ’u ’ , $rsm - > getAlias ( ’ status ’) ) ;
$this - > assertEquals ( ’u ’ , $rsm - > getAlias ( ’ user ’) ) ;
$this - > assertEquals ( ’u ’ , $rsm - > getAlias ( ’ name ’) ) ;
$this - > assertEquals ( ’ id ’ , $rsm - > getField ( ’ id ’) ) ;
$this - > assertEquals ( ’ status ’ , $rsm - > getField ( ’ status ’) ) ;
$this - > assertEquals ( ’ username ’ , $rsm - > getField ( ’ user ’) ) ;
$this - > assertEquals ( ’ name ’ , $rsm - > getField ( ’ name ’) ) ;
}
Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices August 2009 18 / 49
20. ezcUrl Test
public function t e s t R e m o v e O r d e r e d P a r a m e t e r ()
{
$urlCfg = new e zcUrlConfiguration () ;
$urlCfg - > a d dO r d eredParameter ( ’ section ’ ) ;
$urlCfg - > a d dO r d eredParameter ( ’ module ’ ) ;
$urlCfg - > a d dO r d eredParameter ( ’ view ’ ) ;
$u = ’ http :// www . example . com / doc / components ’;
$url = new ezcUrl ( $u , $urlCfg ) ;
// [..]
}
Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices August 2009 20 / 49
21. ezcUrl Test 2
public function t e s t R e m o v e O r d e r e d P a r a m e t e r ()
{
// [..]
// functionality tested in other tests before
$this - > assertEquals (
array ( ’ section ’ = > 0 , ’ module ’ = > 1 , ’ view ’ = > 2) ,
$url - > configuration - > orderedParameters
);
$this - > assertEquals ( ’ doc ’ , $url - > getParam ( ’ section ’) ) ;
$this - > assertEquals (
’ components ’ , $url - > getParam ( ’ module ’)
);
// [..]
}
Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices August 2009 21 / 49
22. ezcUrl Test 3
public function t e s t R e m o v e O r d e r e d P a r a m e t e r ()
{
// [..]
// Primary Assertion according to test method name
$url - > configuration - > r em ove Or de re dPa ra me ter ( ’ view ’) ;
$this - > assertEquals (
array ( ’ section ’ = > 0 , ’ module ’ = > 1 ) ,
$url - > configuration - > orderedParameters
);
// [..]?
}
Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices August 2009 22 / 49
23. ezcUrl Test 4
public function t e s t R e m o v e O r d e r e d P a r a m e t e r ()
{
// [..]
try
{
$this - > assertEquals ( null , $url - > getParam ( ’ view ’) ) ;
$this - > fail ( ’ Expected exception was not thrown . ’) ;
} catch ( e z c U r l I n v a l i d P a r a m e t e r E x c e p t i o n $e ) {
$expected = " ... " ;
$this - > assertEquals ( $expected , $e - > getMessage () ) ;
}
// [..]?
}
Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices August 2009 23 / 49
24. ezcUrl Test 5
public function t e s t R e m o v e O r d e r e d P a r a m e t e r ()
{
// [..]
// try removing again - nothing bad should happen
$url - > configuration - > r em ove Or de re dPa ra me ter ( ’ view ’) ;
try
{
$this - > assertEquals ( null , $url - > getParam ( ’ view ’) ) ;
$this - > fail ( ’ Expected exception was not thrown . ’) ;
} catch ( e z c U r l I n v a l i d P a r a m e t e r E x c e p t i o n $e ) {
$expected = " ... " ;
$this - > assertEquals ( $expected , $e - > getMessage () ) ;
}
}
Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices August 2009 24 / 49
28. Global State: Zend Framework
// Z e n d _ C o n t r o l l e r _ A c t i o n _ H e l p e r _ V i e w R e n d e r e r T e s t
protected function setUp ()
{
$this - > request = new Z e n d _ C o n t r o l l e r _ R e q u e s t _ H t t p () ;
$this - > response = new Z e n d _ C o n t r o l l e r _ R e s p o n s e _ H t t p () ;
$this - > front = Ze nd_C ontro ller _Fron t :: getInstance ()
;
$this - > front - > resetInstance () ;
$this - > front - > a ddModuleDirectory ( ’/ _files / modules ’)
-> setRequest ( $this - > request )
-> setResponse ( $this - > response ) ;
$this - > helper = new
Z e n d _ C o n t r o l l e r _ A c t i o n _ H e l p e r _ V i e w R e n d e r e r () ;
Z e n d _ C o n t r o l l e r _ A c t i o n _ H e l p e r B r o k e r :: addHelper (
$this - > helper
);
}
Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices August 2009 28 / 49
29. Indirect Tests: ezcMvc
function t e s t I n t e r n alRedirect () {
$config = new s impleConfiguration () ;
$config - > route = ’ IRController ’;
$dispatcher = new e z c M v c C o n f i g u r a b l e D i s p a t c h e r (
$config ) ;
$dispatcher - > run () ;
self :: assertEquals ( " BODY : Name : name , " .
" Vars : array ([ CR ] ’ nonRedirVar ’ = > 4 , " .
" [ CR ] ’ ReqRedirVar ’ = > 4 ,[ CR ]) " , $config - > store ) ;
}
function t e s t E x t e r n alRedirect () {
$config = new s impleConfiguration () ;
$config - > route = ’ IRController ’;
$dispatcher = new e z c M v c C o n f i g u r a b l e D i s p a t c h e r (
$config ) ;
$dispatcher - > run () ;
self :: assertEquals ( " BODY : Name : name , " .
" Vars : array ([ CR ] ’ nonRedirVar ’ = > 4 , " .
" [ CR ] ’ ReqRedirVar ’ = > 4 ,[ CR ]) " , $config - > store ) ;
}
Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices August 2009 29 / 49
32. Zend Service Amazon
public function setUp ()
{
$this - > _amazon = new Zend_Service_Amazon () ;
$this - > _query = new Z e n d _ S e r v i ce _ A m a z o n _ Q u e r y ()
$this - > _httpClient =
new Z e n d _ H t t p _ C l i e n t _ A d a p t e r _ S o c k e t () ;
$this - > _amazon - > getRestClient ()
-> getHttpClient ()
-> setAdapter ( $this - > _httpClient ) ;
// terms of use compliance :
// no more than one query per second
sleep (1) ;
}
Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices August 2009 32 / 49
33. Zend Service Amazon 2
public function t e s t I t e m S ea r c h M u s i c M o z a r t ()
{
$resultSet = $this - > _amazon - > itemSearch ( array (
’ SearchIndex ’ = > ’ Music ’ ,
’ Keywords ’ = > ’ Mozart ’ ,
’ ResponseGroup ’ = > ’ Small , Tracks , Offers ’
));
foreach ( $resultSet as $item ) {
$this - > assertTrue (
$item instanceof Z e n d_ S e r vi c e _ Am a z o n_ I t e m
);
}
}
Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices August 2009 33 / 49
34. Zend Amazon Refactored
public function setUpRefactored ()
{
$this - > _amazon = new Zend_Service_Amazon () ;
$this - > _httpClient =
new Z e n d _ H t t p _ C l i e n t _ A d a p t e r _ T e s t () ;
$this - > _amazon - > getRestClient ()
-> getHttpClient ()
-> setAdapter ( $this - > _httpClient ) ;
}
Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices August 2009 34 / 49
35. Zend Amazon Refactored 2
public function t e s t I t e m S e a r c h M u s i c M o z a r t R e f a c t o r e d ()
{
$this - > _httpClient - > setResponse (
fil e_get_ contents ( " ExpectedTestResponse . txt " )
);
$resultSet = $this - > _amazon - > itemSearch ( array (
’ SearchIndex ’ = > ’ Music ’ ,
’ Keywords ’ = > ’ Mozart ’ ,
’ ResponseGroup ’ = > ’ Small , Tracks , Offers ’
));
foreach ( $resultSet as $item ) {
$this - > assertTrue (
$item instanceof Z e n d_ S e r vi c e _ Am a z o n_ I t e m
);
// Assert some relevant stuff now !
}
}
Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices August 2009 35 / 49
36. Conditional Logic
“Everyone knows that debugging is
twice as hard as writing a program in
the first place. So if you’re as clever as
you can be when you write it, how will
you ever debug it?” (Brian Kernighan)
Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices August 2009 36 / 49
37. FLOW3 Cache Frontend
public function t h e C o n s t r u c t o r A c c e p t s V a l i d I d e n t i f i e r s () {
$mockBackend = $this - > createMockBackend () ;
$identifiers = array (
’x ’ , ’ someValue ’ , ’ 123 fivesixseveneight ’ ,
’ some & ’ , ’ ab_cd % ’ ,
rawurlencode ( ’ package :// some / $ &% sadf ’) ,
str_repeat ( ’x ’ , 250)
);
foreach ( $identifiers as $identifier ) {
$abstractCache = $this - > getMock (
’ F3 FLOW3 Cache Frontend StringFrontend ’ ,
array () ,
array ( $identifier , $mockBackend )
);
}
}
Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices August 2009 37 / 49
38. FLOW3 Cache Refactored
/* *
* @dataProvider d a t a A c c e p t V a l i d I d e n t i f ie r
*/
public function c o n s t r u c t o r A c c e p t s V a l i d I d e n t i f i e r ( $id ) {
$mockBackend = $this - > createMockBackend () ;
$abstractCache = $this - > getMock (
’ F3 FLOW3 Cache Frontend StringFrontend ’ ,
array () ,
array ( $id , $mockBackend )
);
}
static public function d a t a A c c e p tV a l i d I d e n t i f i e r () {
return array (
array ( ’x ’) , array ( ’ someValue ’) ,
array ( ’ 123 fivesixseveneight ’) ,
array ( ’ some & ’) , array ( ’ ab_cd % ’) ,
array (
rawurlencode ( ’ package :// some / $ &% sadf ’)
),
array ( str_repeat ( ’x ’ , 250) )
);
}
Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices August 2009 38 / 49
39. Zend Server ReflectionClass
public function testGetMethods ()
{
$r = new Z e n d _ S e r v e r _ R e f l e c t i o n _ C l a s s (
new ReflectionClass ( ’ Ze nd_ Se rv er_ Re fl ect io n ’)
);
$methods = $r - > getMethods () ;
$this - > assertTrue ( is_array ( $methods ) ) ;
foreach ( $methods as $m ) {
$this - > assertTrue (
$m instanceof Z e n d _ S e r v e r _ R e f l e c t i o n _ M e t h o d
);
}
}
Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices August 2009 39 / 49
40. A working implementation
class Z e n d _ S e r v e r _ R e f l e c t i o n _ C l a s s ()
{
public function getMethods ()
{
return array () ;
}
}
Great, all tests pass!
Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices August 2009 40 / 49
41. Zend Server ReflectionClass
Test Refactoring
public function t e s t G e tM e t ho d s R ef a c t or e d ()
{
$r = new Z e n d _ S e r v e r _ R e f l e c t i o n _ C l a s s (
new ReflectionClass ( ’ Ze nd_ Se rv er_ Re fl ect io n ’)
);
$methods = $r - > getMethods () ;
$this - > assertTrue ( is_array ( $methods ) ) ;
$this - > assertEquals (3 , count ( $methods ) ) ; // (!!)
foreach ( $methods as $m ) {
$this - > assertTrue (
$m instanceof Z e n d _ S e r v e r _ R e f l e c t i o n _ M e t h o d
);
}
}
Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices August 2009 41 / 49
42. Zend Server ReflectionClass
Test Refactoring 2
public function ass ertReflMethods ( $methods , $expected )
{
$this - > assertTye ( ’ array ’ , $methods ) ;
$this - > assertEquals ( $expected , count ( $methods ) ) ;
foreach ( $methods as $m ) {
$this - > assertTrue (
$m instanceof Z e n d _ S e r v e r _ R e f l e c t i o n _ M e t h o d
);
}
}
public function t e s t G e tM e t ho d s R ef a c t or e d ()
{
$r = new Z e n d _ S e r v e r _ R e f l e c t i o n _ C l a s s (
new ReflectionClass ( ’ Ze nd_ Se rv er_ Re fl ect io n ’)
);
$this - > as sertRe flMethods ( $r - > getMethods () , 3) ;
}
Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices August 2009 42 / 49
47. Conclusion
Don’t use global state (Singleton
Anti-Pattern)
Use utility methods for Assertions, Object
and Mock Creation
Use Mocks (but not exclusively)
Give meaningful test-names
Dont test through the UI
Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices August 2009 47 / 49
48. Further Readings
xUnit Test Patterns
Book by Gerald Meszaros, http://xunitpatterns.com/Test%20Smells.html
TDD Anti Patterns
http://blog.james-carr.org/2006/11/03/tdd-anti-patterns/
Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices August 2009 48 / 49