This document provides a beginner's guide to unit testing and mocking in Python. It discusses:
1) Using the Mock class to create basic mocks and set mock attributes and return values.
2) Using patch to mock imports when mocks cannot be passed directly. Patch is used to mock methods like requests.post.
3) Best practices for mocking like using spec or spec_set to define the mock's interface and make invalid attribute access raise AttributeError.
4) Common mock assertions like assert_called_once_with to validate mocks are used as expected.
5) Examples patching requests.post to mock network requests and control return values and exceptions.
phpunit is testing framework for php testing.
A browser is able to give the syntax error but what if in case of some logical error.
Phpunit testing enables you to check your logic.
It is fully object oriented framework.
It also can be enabled in Netbeans.
you can find the option of phpunit testing in Netbeans
Когда тестировать, что тестировать, как тестировать, Как ускорить тесты и упростить их написание. Отказываемся от классических фикстур в пользу динамически создаваемых моделей.
phpunit is testing framework for php testing.
A browser is able to give the syntax error but what if in case of some logical error.
Phpunit testing enables you to check your logic.
It is fully object oriented framework.
It also can be enabled in Netbeans.
you can find the option of phpunit testing in Netbeans
Когда тестировать, что тестировать, как тестировать, Как ускорить тесты и упростить их написание. Отказываемся от классических фикстур в пользу динамически создаваемых моделей.
Unit testing, everyone talks about it and wants to do it but never gets around to actually start testing. Complex spaghetti code and time / budget pressures are often the reasons why nobody dives in and gets started with testing. But when the application breaks, and people loose money or worse it's often too late.
In this talk I will take you on a journey with real examples that will show you how you can set up your tests, how to test complex situations with legacy spaghetti code, test web services, database interactions and how to gradually build a solid foundation to safeguard the core code base and everything around it.
Don't you want to be confident when you walk out the office?
This presentation would help learn how to install, integrate, write automated test script with PHPUnit.Would also involve looking into different example and execute them.
Slides da palestra sobre py.test apresentada no TDC 2015 na trilha de Python
Slides of my talk about py.test presented at TDC 2015 in the Python track.
http://github.com/erickwilder/pytest-talk
Unit testing with PHPUnit - there's life outside of TDDPaweł Michalik
Basics of PHPUnit and why is it even more relevant in legacy code. Key points of the framework are explained, along with mocking objects, test organisation, creating documentations with tests and accessing non-public objects (where applicable).
Live version with additional notes available at: http://pawelmichalik.net/presentations/unit-testing-with-phpunit?showNotes=true
Prezentacja dostępna także w języku polskim: http://pawelmichalik.net/prezentacje/testy-jednostkowe-w-phpunit?showNotes=true
Test your code like a pro - PHPUnit in practiceSebastian Marek
The day you realised that you can’t really tell what your code does is the day you stop being an amateur programmer and you turn into a professional developer. During this workshop you will learn about the most famous unit testing framework – PHPUnit, how it can help you gain confidence in your code and what to do (and what to avoid) to make your code testable. We will discuss unit testing best practices and talk about tools that can help you automate the whole process, so it becomes more of a habit then a necessity.
EuroPython 2017 - How to make money with your Python open-source projectMax Tepkeev
Developers create new open-source projects every day. As the project becomes popular they have to invest more and more time into it’s development and of course at some point a question arises: “How can I make some money with my project ?”
In this talk we will try to answer this question. We will talk about different models of making money, their pros and cons. We will concentrate on Python Open-Source projects mostly and try to answer the following questions:
What to sell ?
Where to sell ?
How to distribute ?
How to license ?
After this talk you will have a clear understanding of how you can make money with your project. What your next steps should be and how you can get the actual profit while still continuing making your customers happy.
Unit testing, everyone talks about it and wants to do it but never gets around to actually start testing. Complex spaghetti code and time / budget pressures are often the reasons why nobody dives in and gets started with testing. But when the application breaks, and people loose money or worse it's often too late.
In this talk I will take you on a journey with real examples that will show you how you can set up your tests, how to test complex situations with legacy spaghetti code, test web services, database interactions and how to gradually build a solid foundation to safeguard the core code base and everything around it.
Don't you want to be confident when you walk out the office?
This presentation would help learn how to install, integrate, write automated test script with PHPUnit.Would also involve looking into different example and execute them.
Slides da palestra sobre py.test apresentada no TDC 2015 na trilha de Python
Slides of my talk about py.test presented at TDC 2015 in the Python track.
http://github.com/erickwilder/pytest-talk
Unit testing with PHPUnit - there's life outside of TDDPaweł Michalik
Basics of PHPUnit and why is it even more relevant in legacy code. Key points of the framework are explained, along with mocking objects, test organisation, creating documentations with tests and accessing non-public objects (where applicable).
Live version with additional notes available at: http://pawelmichalik.net/presentations/unit-testing-with-phpunit?showNotes=true
Prezentacja dostępna także w języku polskim: http://pawelmichalik.net/prezentacje/testy-jednostkowe-w-phpunit?showNotes=true
Test your code like a pro - PHPUnit in practiceSebastian Marek
The day you realised that you can’t really tell what your code does is the day you stop being an amateur programmer and you turn into a professional developer. During this workshop you will learn about the most famous unit testing framework – PHPUnit, how it can help you gain confidence in your code and what to do (and what to avoid) to make your code testable. We will discuss unit testing best practices and talk about tools that can help you automate the whole process, so it becomes more of a habit then a necessity.
EuroPython 2017 - How to make money with your Python open-source projectMax Tepkeev
Developers create new open-source projects every day. As the project becomes popular they have to invest more and more time into it’s development and of course at some point a question arises: “How can I make some money with my project ?”
In this talk we will try to answer this question. We will talk about different models of making money, their pros and cons. We will concentrate on Python Open-Source projects mostly and try to answer the following questions:
What to sell ?
Where to sell ?
How to distribute ?
How to license ?
After this talk you will have a clear understanding of how you can make money with your project. What your next steps should be and how you can get the actual profit while still continuing making your customers happy.
EuroPython 2017 - PyData - Deep Learning your Broadband Network @ HOMEHONGJOO LEE
45 min talk about collecting home network performance measures, analyzing and forecasting time series data, and building anomaly detection system.
In this talk, we will go through the whole process of data mining and knowledge discovery. Firstly we write a script to run speed test periodically and log the metric. Then we parse the log data and convert them into a time series and visualize the data for a certain period.
Next we conduct some data analysis; finding trends, forecasting, and detecting anomalous data. There will be several statistic or deep learning techniques used for the analysis; ARIMA (Autoregressive Integrated Moving Average), LSTM (Long Short Term Memory).
From Europython 2016
Mocking is a valuable technique for writing tests but mocking effectively is often a stumbling block for many developers and can raise questions about its overall value as a technique.
The audience will have some familiarity with unit testing and may have tried mocking before, but some introduction will be provided for those who haven’t. We will look at some features and techniques of Python’s unittest.mock library and cover some useful tips and common scenarios, so this will be useful to those who have some experience mocking but would like to do so more effectively.
Video: https://www.youtube.com/watch?v=Ahnw72diels
Aiming at complete code coverage by unit tests tends to be cumbersome, especially for cases where external API calls a part of the code base. For these reasons, Python comes with the unittest.mock library, appearing to be a powerful companion in replacing parts of the system under test.
Spock the enterprise ready specifiation framework - Ted VinkeTed Vinke
Spock is a testing and specification framework for Java and Groovy applications. What makes it stand out from the crowd is its beautiful and highly expressive specification language. Thanks to its JUnit runner, Spock is compatible with most IDEs, build tools, and continuous integration servers. Spock is inspired from JUnit, jMock, RSpec, Groovy, Scala, Vulcans, and other fascinating life forms.
This presentation is an overview of the Spock 1.1 documentation available at http://docs.spockframework.org/
Inheritance and Polymorphism in Python. Inheritance is a mechanism which allows us to create a new class – known as child class – that is based upon an existing class – the parent class, by adding new attributes and methods on top of the existing class.
Having a reliable test suite is incredibly useful when making changes to an existing codebase, both big and small. Mutation testing frameworks run tests against slightly-changed source code in order to detect whether the tests are actually checking the different paths of logic through the application. The aim is to improve the robustness of your test suite, and give you confidence that you aren't introducing any unintended changes.
This presentation gives an overview of mutation testing, along with worked examples in JavaScript of how it catches gaps and improves test coverage.
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAMaulik Borsaniya
Classes and Object-oriented Programming:
Classes: Creating a Class, The Self Variable, Constructor, Types of Variables, Namespaces, Types of Methods (Instance Methods, Class Methods, Static Methods), Passing Members of One Class to Another Class, Inner Classes
Inheritance and Polymorphism: Constructors in Inheritance, Overriding Super Class Constructors and Methods, The super() Method, Types of Inheritance, Single Inheritance, Multiple Inheritance, Method Resolution Order (MRO), Polymorphism, Duck Typing Philosophy of Python, Operator Overloading, Method Overloading, Method Overriding
Abstract Classes and Interfaces: Abstract Method and Abstract Class, Interfaces in Python, Abstract Classes vs. Interfaces,
A definitive guide to why as a tester you need to get involved with unit testing and a guide to the details of unit testing and how to improve unit testing coverage in your organisation.
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.
Similar to Mock it right! A beginner’s guide to world of tests and mocks, Maciej Polańczyk (20)
Short-range wireless communication technologies such as Bluetooth or ZigBee represent an important part of the Internet of Things ecosystem.
By design, this category of smart devices has physically limited reachability inside their Wireless Personal Area Network (WPAN) and are not directly compatible with the TCP/IP stack.
However, users may need to access them from anywhere at any moment.
To address this problem, we design a new application-agnostic approach called RCM (Remote Connection Manager) enabling transparent communication between an application and out-of-range devices.
It creates new IoT use cases by seamlessly mixing remote and local devices.
We implemented an open-source prototype for Bluetooth Low Energy (BLE) technology on top of Linux and Android BLE stacks and demonstrated its efficiency through experiments performed on real devices.
SAFC est un nouveau framework d’ordonnancement des conteneurs dans le cloud basé sur un modèle économique. La nouveauté de SAFC est qu’il permet de décider automatiquement quel est le nombre de ressources allouées pour chaque conteneur.
On parle d’observabilité des services lorsque ceux-ci exposent des états et métriques internes pour améliorer la disponibilité globale.
Qu’en est-il de l’observabilité des infrastructures sur lesquelles ils sont déployés, configurés et maintenus ?
Les différents logs (centralisés, agrégés) permettent un bon début d’analyse mais il faut aussi observer les systèmes au fil de l’eau pour tracer chaque changement et les corréler avec le monitoring. Aujourd’hui, ces étapes de configuration IT devraient être prises en charge par les outils de gestion de configuration, qui deviennent la passerelle vers l’observabilité des opérations.
Nous montrerons l'intérêt de cette approche pour la gestion IT moderne avec un retour d’expérience sur les challenges de leur mise en place dans Rudder, notre solution libre d’audit et de gestion de configuration en continu.
My research is in virtualized infrastructure domain. I aim at minimizing electricity consumption while improving application performance. To achieve the first goal, I work both at the entire datacenter level (by providing better VM placement strategies) and at the physical machine level (by providing better power management policies). Concerning the second goal, I work both at the VM monitor level (for minimizing its overhead) and at the VM's operating system (OS) level (for making it aware of the fact that it is virtualized).
In this talk I present two contributions of my research team, one for each objective.
The first contribution presents Drowsy-DC, a novel way to reduce data center power consumption inspired by smartphones.
The second contribution presents XPV (eXtended Para-Virtualization), a new principle for well virtualizing NUMA machines.
L'expérience du développement de CRESON, support pour des objets distants fortement cohérents dans Infinispan, par Etienne Riviere (UCLouvain).
Cet exposé présentera des résultats obtenus dans le cadre du projet européen LEADS que j'ai coordonné et où l'entreprise Red Hat était partenaire. Le code produit a été intégré dans le “staging" de la base de données NoSQL Infinispan, et évalué avec un équivalent open source de Dropbox développé par CloudSpaces, un autre projet européen.
L'approche de virtualisation en micro-services entraine des difficultés natives dans le capacity planning. La consommation de ressources des services déployés étant élastique et fonction du volume de requêtes / appels reçus par ce service.
The conference will describe the main concepts of security for embedded and IoT solutions : security vs safety, IT vs OT, main standards, level of security of available operating systems (Linux, Android, etc.), examples of attacks and secure solutions.
Pointers are a notorious "defect attractor", in particular when dynamic memory management is involved. Ada mitigates these issues by having much less need for pointers overall (thanks to first-class arrays, parameter modes, generics) and stricter rules for pointer manipulations that limit access to dangling memory. Still, dynamic memory management in Ada may lead to use-after-free, double-free and memory leaks, and dangling memory issues may lead to runtime exceptions.
The SPARK subset of Ada is focused on making it possible to guarantee properties of the program statically, in particular the absence of programming language errors, with a mostly automatic analysis. For that reason, and because static analysis of pointers is notoriously hard to automate, pointers have been forbidden in SPARK until now. We are working at AdaCore since 2017 on including pointer support in SPARK by restricting the use of pointers in programs so that they respect "ownership" constraints, like what is found in Rust.
In this talk, I will present the current state of the ownership rules for pointer support in SPARK, and the current state of the implementation in the GNAT compiler and GNATprove prover, as well as our roadmap for the future.
Durant ce talk Laurent Chemla revient sur l'expérience au niveau du projet Open Source Caliopen pour la création d'un commun et la mise en place d'une communauté.
Il abordera plusieurs questions essentielles dans la vie un projet Open Source tel que:
- Qu'est-ce qu'un commun et comment il naît?
- Qui vient en premier le commun ou la communauté qui soutient ce commun?
La virtualisation est une technologie mature dont le surcoût est aujourd’hui marginal sur les machines grand public. Néamoins, ce surcoût augmente radicalement pour les machines reposant sur une architecture Non Uniform Memory Access (NUMA), omniprésentes dans les data centers. Les techniques de virtualisation actuelles exploitent mal cette architecture et causent une dégradation des performances des applications allant jusqu’à 700%. Cette présentation détaille les causes de telles dégradations et propose une méthode qui permet la virtualisation efficace d’architectures NUMA. Une évaluation de cette méthode montre qu’il est possible de multiplier par 2 ou plus la performance de 9 des 29 applications testées.
Nous présentons une solution Open Source de stockage et d’archivage distribué des données dont l’objectif est la pérennité des données. Il est basé sur le protocole BitTorrent et intègre un haut niveau de redondance, ainsi que d’un mécanisme de régénération automatique des données. Il peut être déployé à grande échelle en LAN et en WAN. Les agents sont compatibles avec des serveurs et postes clients Linux, Window ou Mac OS.
Le logiciel est au cœur de notre société numérique et le code source des logiciels contient une part croissante de nos connaissances scientifiques, techniques et organisationnelles, au point d'être devenu désormais une partie intégrante du patrimoine de l'Humanité.
La mission de «Software Heritage» est de veiller à ce que cette précieuse masse des connaissances soit collectée, préservée, organisée et mise à la disposition de tous.
Construire une telle infrastructure pose des défis importants, à la fois techniques et stratégiques, et nous pouvons tous contribuer à les résoudre.
Dans cet exposé, on présentera OMicroB, une machine virtuelle OCaml pour microcontrôleurs à faibles ressources, inspirée des travaux précédents sur le projet OCaPIC. Cette machine virtuelle, destinée à être exécutée sur diverses architectures matérielles (AVR, PIC, ARM, ...) permet ainsi de factoriser le développement d’applications, mais aussi de généraliser l’analyse et le débogage du bytecode associé, tout en permettant un usage précautionneux de la mémoire. On cible alors des programmes ludiques ou de domotiques destinés à être exécutés sur des microcontrôleurs à faibles ressources, en insistant sur les particularités inhérentes à la programmation de systèmes embarqués.
La société Farjump propose une solution simple, innovante et bon marché pour la mise au point des systèmes embarqués utilisés dans l'IoT. La solution est basé sur la mise en place d'agents GDB sur la cible.
Le principe est d’appliquer des mécanismes de contrôle dynamiques et fins sur les communications des objets (entre eux ou bien vers le cloud) sous le contrôle des utilisateurs.
The programming language Ada offers unique features to safely program a micro-controller. From the start, Ada was designed to make it difficult to introduce errors, and to make it easy to discover errors that were introduced. For example, language rules enforced at compile time make it possible to have safe concurrency by design. And run-time checking allows immediate detection of what would be "undefined behavior" in C/C++. In the first part of this presentation, we will present the benefits of using Ada for micro-controller programming, including support for debugging on a board. In the second part of this presentation, we will present how the Ada language and its subset SPARK provide a strong foundation for static analyzers, that make it possible to detect errors and provide guarantees on embedded software in Ada/SPARK.
Nous présenterons le système d'exploitation RTEMS, ses applications passées et actuelles ainsi que les travaux en cours pour son utilisation dans l'IoT professionnel.
Connector Corner: Automate dynamic content and events by pushing a buttonDianaGray10
Here is something new! In our next Connector Corner webinar, we will demonstrate how you can use a single workflow to:
Create a campaign using Mailchimp with merge tags/fields
Send an interactive Slack channel message (using buttons)
Have the message received by managers and peers along with a test email for review
But there’s more:
In a second workflow supporting the same use case, you’ll see:
Your campaign sent to target colleagues for approval
If the “Approve” button is clicked, a Jira/Zendesk ticket is created for the marketing design team
But—if the “Reject” button is pushed, colleagues will be alerted via Slack message
Join us to learn more about this new, human-in-the-loop capability, brought to you by Integration Service connectors.
And...
Speakers:
Akshay Agnihotri, Product Manager
Charlie Greenberg, Host
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.
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.
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualityInflectra
In this insightful webinar, Inflectra explores how artificial intelligence (AI) is transforming software development and testing. Discover how AI-powered tools are revolutionizing every stage of the software development lifecycle (SDLC), from design and prototyping to testing, deployment, and monitoring.
Learn about:
• The Future of Testing: How AI is shifting testing towards verification, analysis, and higher-level skills, while reducing repetitive tasks.
• Test Automation: How AI-powered test case generation, optimization, and self-healing tests are making testing more efficient and effective.
• Visual Testing: Explore the emerging capabilities of AI in visual testing and how it's set to revolutionize UI verification.
• Inflectra's AI Solutions: See demonstrations of Inflectra's cutting-edge AI tools like the ChatGPT plugin and Azure Open AI platform, designed to streamline your testing process.
Whether you're a developer, tester, or QA professional, this webinar will give you valuable insights into how AI is shaping the future of software delivery.
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Jeffrey Haguewood
Sidekick Solutions uses Bonterra Impact Management (fka Social Solutions Apricot) and automation solutions to integrate data for business workflows.
We believe integration and automation are essential to user experience and the promise of efficient work through technology. Automation is the critical ingredient to realizing that full vision. We develop integration products and services for Bonterra Case Management software to support the deployment of automations for a variety of use cases.
This video focuses on the notifications, alerts, and approval requests using Slack for Bonterra Impact Management. The solutions covered in this webinar can also be deployed for Microsoft Teams.
Interested in deploying notification automations for Bonterra Impact Management? Contact us at sales@sidekicksolutionsllc.com to discuss next steps.
JMeter webinar - integration with InfluxDB and GrafanaRTTS
Watch this recorded webinar about real-time monitoring of application performance. See how to integrate Apache JMeter, the open-source leader in performance testing, with InfluxDB, the open-source time-series database, and Grafana, the open-source analytics and visualization application.
In this webinar, we will review the benefits of leveraging InfluxDB and Grafana when executing load tests and demonstrate how these tools are used to visualize performance metrics.
Length: 30 minutes
Session Overview
-------------------------------------------
During this webinar, we will cover the following topics while demonstrating the integrations of JMeter, InfluxDB and Grafana:
- What out-of-the-box solutions are available for real-time monitoring JMeter tests?
- What are the benefits of integrating InfluxDB and Grafana into the load testing stack?
- Which features are provided by Grafana?
- Demonstration of InfluxDB and Grafana using a practice web application
To view the webinar recording, go to:
https://www.rttsweb.com/jmeter-integration-webinar
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.
Search and Society: Reimagining Information Access for Radical FuturesBhaskar Mitra
The field of Information retrieval (IR) is currently undergoing a transformative shift, at least partly due to the emerging applications of generative AI to information access. In this talk, we will deliberate on the sociotechnical implications of generative AI for information access. We will argue that there is both a critical necessity and an exciting opportunity for the IR community to re-center our research agendas on societal needs while dismantling the artificial separation between the work on fairness, accountability, transparency, and ethics in IR and the rest of IR research. Instead of adopting a reactionary strategy of trying to mitigate potential social harms from emerging technologies, the community should aim to proactively set the research agenda for the kinds of systems we should build inspired by diverse explicitly stated sociotechnical imaginaries. The sociotechnical imaginaries that underpin the design and development of information access technologies needs to be explicitly articulated, and we need to develop theories of change in context of these diverse perspectives. Our guiding future imaginaries must be informed by other academic fields, such as democratic theory and critical theory, and should be co-developed with social science scholars, legal scholars, civil rights and social justice activists, and artists, among others.
Search and Society: Reimagining Information Access for Radical Futures
Mock it right! A beginner’s guide to world of tests and mocks, Maciej Polańczyk
1. Mock it right! A beginner’s guide to world
of tests and mocks.
Maciej Polańczyk
maciej.polanczyk@stxnext.pl
Mock, Patch
2. Schedule
- Class to be tested
- Basic test
- Mock
- Not the best mock
- The best mock - spec_set
- Good mock - spec
- Mock requests.post
- Patch
- Patch.object
- Patch & import
- Patch - raise Exception
- Patch - different return_value
- Patch - method instead of return_value
- Patch - nesting patches
- Patch - TestCase
- Patch - in setUp
- Patch - environment variables
https://docs.python.org/3/library/unittest.mock.html
3. Class to be tested
import requests
class MessageSender:
_max_attempts = 3
def send(self, message):
data = {
'from': message.sender,
'to': message.receiver,
'subject': message.subject,
}
for attempt in range(self._max_attempts):
response = requests.post(url='http://example.com/email', data=data)
if response.status_code == requests.codes.created:
return True
return False
4. Basic test
from message_sender import MessageSender
class MessageSenderTests(unittest.TestCase):
def test_should_send_message():
# GIVEN
message_sender = MessageSender()
message_to_be_sent = self._get_mocked_message()
# WHEN
result = message_sender.send(message_to_be_sent)
# THEN
self.assertTrue(result)
# assert correct arguments were passed to request.post
6. Mock - creation
from unittest.mock import Mock
# mock and attributes
mock = Mock()
print(mock.not_existing_field)
<Mock name='mock.not_existing_field' id='4327526528'>
from unittest.mock import Mock
# mock and methods
mock = Mock()
print(mock.not_existing_method())
<Mock name='mock.not_existing_method()' id='4372615856'>
7. Mock - creation
from unittest.mock import Mock
# mock and attributes
mock = Mock()
mock.existing_field = 5
print(mock.existing_field)
5
from unittest.mock import Mock
# mock and methods
mock = Mock()
mock.existing_method.return_value = 5
print(mock.existing_method())
5
8. Mock - creation
from unittest.mock import Mock
# mock and attributes
mock = Mock(existing_field=5)
print(mock.existing_field)
5
from unittest.mock import Mock
# mock and methods
mock = Mock(existing_method=Mock(return_value=5))
print(mock.existing_method())
5
9. Mock - assertions
from unittest.mock import Mock
# in test method:
mock = Mock()
mock.existing_method.return_value = 5
# in source code:
mock.existing_method()
# in test method:
mock.existing_method.assert_called_once_with()
10. Mock - assertions
from unittest.mock import Mock
# in test method:
mock = Mock()
mock.existing_method.return_value = 5
# in source code:
mock.existing_method(1)
# in test method:
mock.existing_method.assert_called_once_with(1)
11. Mock - assertions
from unittest.mock import Mock
# in test method:
mock = Mock()
mock.existing_method.return_value = 5
# in source code:
mock.existing_method(1)
mock.existing_method(2)
# in test method:
mock.existing_method.assert_any_call(1)
12. Mock - assertions
from unittest.mock import Mock
# in test method:
mock = Mock()
mock.existing_method.return_value = 5
# in source code:
mock(3)
mock.existing_method(1)
mock.existing_method(2)
print(mock.call_args_list)
output from print: [call(3)]
13. Mock - assertions
from unittest.mock import Mock
# in test method:
mock = Mock()
mock.existing_method.return_value = 5
# in source code:
mock(3)
mock.existing_method(1)
mock.existing_method(2)
print(mock.method_calls)
output from print: [call.existing_method(1), call.existing_method(2)]
14. Mock - assertions
from unittest.mock import Mock
# in test method:
mock = Mock()
mock.existing_method.return_value = 5
# in source code:
mock(3)
mock.existing_method(1)
mock.existing_method(2)
print(mock.mock_calls)
output from print: [call(3), call.existing_method(1), call.existing_method(2)]
15. Mock - assertions
from unittest.mock import Mock, call
# in test method:
mock = Mock()
mock.existing_method.return_value = 5
# in source code:
mock(3)
mock.existing_method(1)
mock.existing_method(2)
# in test method:
self.assertEqual(mock.mock_calls, [call(3), call.existing_method(1), call.existing_method(2)])
self.assertEqual(mock.existing_method.mock_calls, [call(1), call(2)])
16. Not the best mock
from unittest.mock import Mock
@staticmethod
def _get_mocked_message():
message_mock = Mock(
receiver='maciej.polanczyk@stxnext.pl',
sender='maciej.polanczyk@test.com',
subject='testing sending message'
)
return message_mock
17. The best mock - spec_set
from unittest.mock import Mock
from message import Message
@staticmethod
def _get_mocked_message():
message_mock = Mock(
spec_set=Message,
receiver='maciej.polanczyk@stxnext.pl',
sender='maciej.polanczyk@test.com',
subject='testing sending message'
)
return message_mock
22. Basic test
from message_sender import MessageSender
class MessageSenderTests(unittest.TestCase):
def test_should_send_message():
# GIVEN
message_sender = MessageSender()
message_to_be_sent = self._get_mocked_message()
# WHEN
result = message_sender.send(message_to_be_sent)
# THEN
self.assertTrue(result)
# assert correct arguments were passed to request.post
23. Mock request.post
import requests
class MessageSender:
_max_attempts = 3
def send(self, message):
data = {
'from': message.sender,
'to': message.receiver,
'subject': message.subject,
}
for attempt in range(self._max_attempts):
response = requests.post(url='http://example.com/email', data=data)
if response.status_code == requests.codes.created:
return True
return False