ArcBlock presents Elixir ExUnit. Learn how to write a unit test for Elixir code? This talk will give an introduction to ExUnit in Elixir, what components are included in it and how to use them.
Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...solit
Виктор Короневич, Минск. Senior Software Test Automation Engineer with 3+ years of experience specializing in automation on Java, http://www.linkedin.com/in/agileseph
«Автоматизация тестирования сложных систем: mixed mode automated test case.» Использование Selenium + jUnit + Frank + custom java tools для тестирования Web + DB + Web Services + iOS. Development секция.
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.
Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...solit
Виктор Короневич, Минск. Senior Software Test Automation Engineer with 3+ years of experience specializing in automation on Java, http://www.linkedin.com/in/agileseph
«Автоматизация тестирования сложных систем: mixed mode automated test case.» Использование Selenium + jUnit + Frank + custom java tools для тестирования Web + DB + Web Services + iOS. Development секция.
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.
JUnit is the de facto standard in Java testing. Yet many advanced JUnit features are little known and poorly understood. This session reviews some lesser-known features of JUnit, along with a few associated libraries, that can make your unit tests more powerful, expressive, and fun. The session is intended for Java developers, lead developers, and architects trying to introduce good testing practices into their teams.
In this talk we are going tο… talk about what unit testing is, how you can apply it to ensure your code works as expected and how TDD can help you write new and refactor existing code. Also about how to decide what to test and how you can test real world iOS apps. Finally, we will go through a few tips and tricks that made unit testing in Swift and Xcode 'click' for me and can hopefully help you too.
Kill the mutants and test your tests - Roy van RijnNLJUG
Quis custodiet ipsos custodes? Better known as: *Who watches the watchmen?* We are all writing tests, doing TDD, BDD. We measure the quality of the tests with line coverage or (even better) branch coverage. This gives you a false sense of security. I've seen projects with tests which have 100% branch coverage but not a single assertion! This is where mutation testing helps out. By creating broken mutated instances of your codebase (mutants) this should result in failing unit tests. This way we can verify that slight code changes (like real life bugs) actually break your tests. In this talk I'll explain what mutation testing is and how it works. We'll also compare some Java frameworks (PIT, Jester, Jumble) that enable automatic mutation testing in your continuous build and how you can start doing mutation testing *right now*.
Introduction to Nightwatch.js artifacts, usage in a CI environment, and current integration with Drupal 8.
Video of session: https://www.youtube.com/watch?v=9GYZJ1AZqI8
JUnit is the de facto standard in Java testing. Yet many advanced JUnit features are little known and poorly understood. This session reviews some lesser-known features of JUnit, along with a few associated libraries, that can make your unit tests more powerful, expressive, and fun. The session is intended for Java developers, lead developers, and architects trying to introduce good testing practices into their teams.
In this talk we are going tο… talk about what unit testing is, how you can apply it to ensure your code works as expected and how TDD can help you write new and refactor existing code. Also about how to decide what to test and how you can test real world iOS apps. Finally, we will go through a few tips and tricks that made unit testing in Swift and Xcode 'click' for me and can hopefully help you too.
Kill the mutants and test your tests - Roy van RijnNLJUG
Quis custodiet ipsos custodes? Better known as: *Who watches the watchmen?* We are all writing tests, doing TDD, BDD. We measure the quality of the tests with line coverage or (even better) branch coverage. This gives you a false sense of security. I've seen projects with tests which have 100% branch coverage but not a single assertion! This is where mutation testing helps out. By creating broken mutated instances of your codebase (mutants) this should result in failing unit tests. This way we can verify that slight code changes (like real life bugs) actually break your tests. In this talk I'll explain what mutation testing is and how it works. We'll also compare some Java frameworks (PIT, Jester, Jumble) that enable automatic mutation testing in your continuous build and how you can start doing mutation testing *right now*.
Introduction to Nightwatch.js artifacts, usage in a CI environment, and current integration with Drupal 8.
Video of session: https://www.youtube.com/watch?v=9GYZJ1AZqI8
Unit testing patterns for concurrent codeDror Helper
Getting started with unit testing is not hard, the only problem is that most programs are more than a simple calculator with two parameters and a returns value that is easy to verify.
Writing unit tests for multi-threaded code is harder still.
Over the years I discovered useful patterns that helped me to test multi-threaded and asynchronous code and enabled the creation of deterministic, simple and robust unit tests.
Come learn how to test code that uses concurrency and parallelism – so that the excuses of not writing unit tests for such code would become as obsolete as a single core processors.
Building unit tests correctly with visual studio 2013Dror Helper
Unit testing is now considered a mainstream practice, but that does not mean it is as common, pervasive or as well understood as it could or should be. Many programmers struggle with the quality of their tests and with the focus of their code. In this session we’ll learn how to write good unit testing code.
Similar to Technical Learning Series - Elixir ExUnit (20)
A introduction to core concepts and ideas behind blockchain helping everyone understanding what it is, how to use it and how it can deliver benefits in a range of use cases.
https://www.arcblock.io
Learn how to use Forge Framework to easily deploy your own blockchains in the real world. This introduction includes instructions on how to build a deployment script, reference architecture and looks at some of the most common issues app developers run into when building apps.
https://www.arcblock.io
Part 4 of ArcBlock's Designing DApps learning series focuses on the concept of Programmable Tokens and looks at why tokens are required to have a successful DApp.
https://www.arcblock.io/en/learning
Build a Decentralized, public verifiable Database with ex_abci and TendermintArcBlock
ArcBlock's VP of Engineering, Tyr Chen, led a session at CodeBEAM SF and presented a talk called Build Decentralized, Pubically Verifiable DB with ex_abci and Tendermint. The session included an in-depth look at why decentralization and having services that are publically verifiable matter. Tyr Chen also looked at different use cases that ArcBlock is exploring including ownership of digital assets and how those can be verified publicly.
https://www.arcblock.io
The talk also gave developers a preview of ArcBlock's Forge Framework. A new chain building service that includes everything needed to create, build and deploy a user created blockchain.
https://www.arcblock.io/en/forge-framework
ArcBlock Presents 5 Winning Factors to Building a Successful DAppArcBlock
ArcBlock's Technical Learning Series presents part 2 of our Designing DApps series. This session is focused on the 5 winning factors for designing, building and launching a successful DApp.
https://www.arcblock.io
QRCodes are Fun, Easy, and Useful for Links, Payments and Identity VerificationArcBlock
ArcBlock Technical Learning Series Presents an introduction to QRCodes.
We scan QRCode for payment, links and basically everything. How do QRcodes work? Are QRcodes secure? Why can I put a logo in the middle of QRCode and it still works? In this talk, we will show you how the QRCode is being drawn. Also, we will talk about Reed-Solomon error correction inside QRCode that makes it fault tolerant.
二维码源于日本,如今世界各国都在使用。一张简单的二维码蕴藏了不简单的信息。二维码究竟是如何画出来的?二维码安全吗?为何在二维码中加个图标还能被扫出来?卫星通讯中用到的Reed-Solomon纠错码如何被用在了二维码中?本次讲座为您揭晓二维码的生成原理,听完保证可以get手绘二维码技能。
https://www.arcblock.io
ArcBlock Technical Learning Series presents Designing Decentralized Applications (DApps) Part 1. This is the first of a 5-part series to help developers, Venture Capitalists, Fund Analysts and product managers prepare, plan and design real-world decentralized applications.
https://www.arcblock.io
The goal of this series is to create a new product mindset focused on decentralization. This includes examining the role of decentralization in the past, problems related to the centralized internet including user account and data controlled by a few companies, security and privacy and more.
We will also look at some of the first decentralized applications like Napster, Popcorn Time, Mastadon, ZeroNet, and OpenBazaar.
Next, we will review the role of identity and how today's companies are pushing people back towards decentralized applications to get control of their own identities. This includes new digital wallets and self-sovereign identity and how future applications will leverage these new decentralized identity models.
https://hack.arcblock.io/learning
ArcBlock's Technical Learning Series presents: Cryptography for everyone.
Cryptography is a foundational piece in BlockChain technology. The reason BlockChain is secured is based on the promise of the underlying cryptographic primitives. In this talk, we will give an introduction to cryptography, from symmetric encryption to public key encryption. We will see how it makes blockchain technology possible. Also, we will talk about the crypto primitives behind cryptocurrency wallet. So you will know how important is your private key.
区块链是集多种高大上技术为大成的应用,密码学占其中最重要的一环。事实上,平日我们在互联网上做的任何事情都有密码学的身影在里面。区块链所用到的的sha256, secp256k1, ed25519都是些什么鬼?本次讲座将从一个最简单的问题开始——如何隐藏不能说的秘密——一直讲到现代密码学在区块链以及钱包中的应用,为您揭开密码学娇羞的面纱。 听完您会明白,为什么我不该在云上备份钱包里的私钥。
https://www.arcblock.io
ArcBlock's Technical Learning Series Presents: Intro to HTTP/2.
You may not know that your browser supports HTTP/2 long times ago. What exactly is HTTP/2? What's the difference between HTTP/2 and HTTP? Why do we even need HTTP2/? What can we do with HTTP/2's new feature? This talk is all about HTTP/2, also we will demonstrate how to write a simple HTTP/2 client in 33 lines of code.
HTTP/2早在2015年就被互联网工程任务小组制定为标准,我们用的浏览器其实早就悄悄支持HTTP/2了。HTTP/2到底比HTTP/1.1好在哪里?关于HTTP/2我需要知道什么?听说HTTP/3快要出了现在才讲HTTP/2是不是有点晚?这篇讲座将解答您的这些问题。另外我们也会现场演示如何用33行代码写一个最简单的HTTP/2客户端。"
ArcBlock Technical Learning Series Presents IPFS.
If there's a missing piece in current blockchain stack, that'll be a decentralized, public verifiable file system. Ideally before decentralizing computing, we shall decentralize the data. IPFS filled in this area, and it has a great potential to push web to the true web3 - decentralized web. This talk will talk about what problem IPFS is trying to solve, how it solves the problem, and how to use IPFS in our applications.
https://www.arcblock.io
https://hack.arcblock.io/learning
Ethereum virtual machine for Developers Part 1ArcBlock
Learn all about Ethereum Virtual Machines and how they work including basic concepts, smart contracts, best practices for developers and next steps to support various uses cases.
https://www.arcblock.io
Understanding hd wallets design and implementationArcBlock
ArcBlock Technical Learning Series Presents Understanding HD Wallets. This talk will look at the building blocks to creating a virtual currency wallet including some of the basic design ideas, and implementation methods.
ArcBlock's Technical Learning Series presents Tendermint: Consensus made easy.
Tendermint is an opensource software aimed to securely and consistently replicating an application on many machines. It acts as a consensus engine and provides a generic application interface called ABCI which makes it pretty easy to integrate itself into other blockchain technology, like Ethereum.
This talk will give a high-level introduction to Tendermint, its architecture, how consensus works and how application data are replicated. We will also give some scenario about how Tendermint could be used to solve various problems.
https://www.arcblock.io
This session of ArcBlock's Technical Learning Series will introduce CQRS and commanded.
CQRS stands for Command Query Responsibility Segregation. At its heart is the notion that you can use a different model to update information than the model you use to read information.
We will have a look into what CQRS and commanded (a framework for elixir) are and how they fit together, followed by a introduction on how to implement an application using CQRS concepts with commanded in our service. "
Decipher Multi-Factor Authentication - A Developers IntroductionArcBlock
ArcBlock's Technical Learning Series presents Deciphering MFA.
Multi-Factor Authentication or MFA is used widely for enhanced account security. This talks will describe and outline the underlying technology used for MFA. For example, TOTP - Time-Based One-Time Password. This is an IETF standard - RFC 6238.
Learn how to develop and build MFA into your DApp, application or platform.
https://www.arcblock.io
https://hack.arcblock.io/learning
Introduction to aws data pipeline servicesArcBlock
This session of the ArcBlock Learning Series will teach you how to access, transform, and process stored data at scale with AWS's Data Pipeline Service. ArcBlock will also demonstrate several use case examples by looking at how ArcBlock is using AWS Data Pipeline today.
AWS Pipeline Service is a web service that helps users reliable process and moves data between different compute and storage services. It is a powerful tool that allows users to easily create complex data processing workloads without being an expert in fault tolerance, resource availability or being worried about retrying transient failures or timeouts for your individual tasks.
ArcBlock Technical Learning Series introduces Smart Contracts.
During this technical learning session, ArcBlock Engineers take a deep drive into Smart Contracts and introduce critical concepts and functionality to make smart contracts work.
https://www.arcblock.io
During this training, ArcBlock also looks key processes and best practices for developers on how to create, maintain and work with Smart Contracts. Finally, ArcBlock looks at its own use cases and provides several examples demonstrating the concepts and features shown during the training
ArcBlock Presents An Introduction to BlockchainArcBlock
A walk through on the history of blockchain including the history and transition between blockchain 1.0, blockchain 2.0 and today's latest iteration Blockchain 3.0. The presentation looks at how blockchain got started with Bitcoin and evolved with Ethereum and the smart based contract. It also looks at how today, decentralized applications and platforms are driving change in the blockchain industry by making blockchain more available to end-users and companies.
A Comprehensive Look at Generative AI in Retail App Testing.pdfkalichargn70th171
Traditional software testing methods are being challenged in retail, where customer expectations and technological advancements continually shape the landscape. Enter generative AI—a transformative subset of artificial intelligence technologies poised to revolutionize software testing.
Quarkus Hidden and Forbidden ExtensionsMax Andersen
Quarkus has a vast extension ecosystem and is known for its subsonic and subatomic feature set. Some of these features are not as well known, and some extensions are less talked about, but that does not make them less interesting - quite the opposite.
Come join this talk to see some tips and tricks for using Quarkus and some of the lesser known features, extensions and development techniques.
Navigating the Metaverse: A Journey into Virtual Evolution"Donna Lenk
Join us for an exploration of the Metaverse's evolution, where innovation meets imagination. Discover new dimensions of virtual events, engage with thought-provoking discussions, and witness the transformative power of digital realms."
How Recreation Management Software Can Streamline Your Operations.pptxwottaspaceseo
Recreation management software streamlines operations by automating key tasks such as scheduling, registration, and payment processing, reducing manual workload and errors. It provides centralized management of facilities, classes, and events, ensuring efficient resource allocation and facility usage. The software offers user-friendly online portals for easy access to bookings and program information, enhancing customer experience. Real-time reporting and data analytics deliver insights into attendance and preferences, aiding in strategic decision-making. Additionally, effective communication tools keep participants and staff informed with timely updates. Overall, recreation management software enhances efficiency, improves service delivery, and boosts customer satisfaction.
We describe the deployment and use of Globus Compute for remote computation. This content is aimed at researchers who wish to compute on remote resources using a unified programming interface, as well as system administrators who will deploy and operate Globus Compute services on their research computing infrastructure.
Experience our free, in-depth three-part Tendenci Platform Corporate Membership Management workshop series! In Session 1 on May 14th, 2024, we began with an Introduction and Setup, mastering the configuration of your Corporate Membership Module settings to establish membership types, applications, and more. Then, on May 16th, 2024, in Session 2, we focused on binding individual members to a Corporate Membership and Corporate Reps, teaching you how to add individual members and assign Corporate Representatives to manage dues, renewals, and associated members. Finally, on May 28th, 2024, in Session 3, we covered questions and concerns, addressing any queries or issues you may have.
For more Tendenci AMS events, check out www.tendenci.com/events
Enterprise Resource Planning System includes various modules that reduce any business's workload. Additionally, it organizes the workflows, which drives towards enhancing productivity. Here are a detailed explanation of the ERP modules. Going through the points will help you understand how the software is changing the work dynamics.
To know more details here: https://blogs.nyggs.com/nyggs/enterprise-resource-planning-erp-system-modules/
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Shahin Sheidaei
Games are powerful teaching tools, fostering hands-on engagement and fun. But they require careful consideration to succeed. Join me to explore factors in running and selecting games, ensuring they serve as effective teaching tools. Learn to maintain focus on learning objectives while playing, and how to measure the ROI of gaming in education. Discover strategies for pitching gaming to leadership. This session offers insights, tips, and examples for coaches, team leads, and enterprise leaders seeking to teach from simple to complex concepts.
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Globus
The U.S. Geological Survey (USGS) has made substantial investments in meeting evolving scientific, technical, and policy driven demands on storing, managing, and delivering data. As these demands continue to grow in complexity and scale, the USGS must continue to explore innovative solutions to improve its management, curation, sharing, delivering, and preservation approaches for large-scale research data. Supporting these needs, the USGS has partnered with the University of Chicago-Globus to research and develop advanced repository components and workflows leveraging its current investment in Globus. The primary outcome of this partnership includes the development of a prototype enterprise repository, driven by USGS Data Release requirements, through exploration and implementation of the entire suite of the Globus platform offerings, including Globus Flow, Globus Auth, Globus Transfer, and Globus Search. This presentation will provide insights into this research partnership, introduce the unique requirements and challenges being addressed and provide relevant project progress.
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteGoogle
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
👉👉 Click Here To Get More Info 👇👇
https://sumonreview.com/ai-pilot-review/
AI Pilot Review: Key Features
✅Deploy AI expert bots in Any Niche With Just A Click
✅With one keyword, generate complete funnels, websites, landing pages, and more.
✅More than 85 AI features are included in the AI pilot.
✅No setup or configuration; use your voice (like Siri) to do whatever you want.
✅You Can Use AI Pilot To Create your version of AI Pilot And Charge People For It…
✅ZERO Manual Work With AI Pilot. Never write, Design, Or Code Again.
✅ZERO Limits On Features Or Usages
✅Use Our AI-powered Traffic To Get Hundreds Of Customers
✅No Complicated Setup: Get Up And Running In 2 Minutes
✅99.99% Up-Time Guaranteed
✅30 Days Money-Back Guarantee
✅ZERO Upfront Cost
See My Other Reviews Article:
(1) TubeTrivia AI Review: https://sumonreview.com/tubetrivia-ai-review
(2) SocioWave Review: https://sumonreview.com/sociowave-review
(3) AI Partner & Profit Review: https://sumonreview.com/ai-partner-profit-review
(4) AI Ebook Suite Review: https://sumonreview.com/ai-ebook-suite-review
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Globus
The Earth System Grid Federation (ESGF) is a global network of data servers that archives and distributes the planet’s largest collection of Earth system model output for thousands of climate and environmental scientists worldwide. Many of these petabyte-scale data archives are located in proximity to large high-performance computing (HPC) or cloud computing resources, but the primary workflow for data users consists of transferring data, and applying computations on a different system. As a part of the ESGF 2.0 US project (funded by the United States Department of Energy Office of Science), we developed pre-defined data workflows, which can be run on-demand, capable of applying many data reduction and data analysis to the large ESGF data archives, transferring only the resultant analysis (ex. visualizations, smaller data files). In this talk, we will showcase a few of these workflows, highlighting how Globus Flows can be used for petabyte-scale climate analysis.
Developing Distributed High-performance Computing Capabilities of an Open Sci...Globus
COVID-19 had an unprecedented impact on scientific collaboration. The pandemic and its broad response from the scientific community has forged new relationships among public health practitioners, mathematical modelers, and scientific computing specialists, while revealing critical gaps in exploiting advanced computing systems to support urgent decision making. Informed by our team’s work in applying high-performance computing in support of public health decision makers during the COVID-19 pandemic, we present how Globus technologies are enabling the development of an open science platform for robust epidemic analysis, with the goal of collaborative, secure, distributed, on-demand, and fast time-to-solution analyses to support public health.
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamtakuyayamamoto1800
In this slide, we show the simulation example and the way to compile this solver.
In this solver, the Helmholtz equation can be solved by helmholtzFoam. Also, the Helmholtz equation with uniformly dispersed bubbles can be simulated by helmholtzBubbleFoam.
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Anthony Dahanne
Les Buildpacks existent depuis plus de 10 ans ! D’abord, ils étaient utilisés pour détecter et construire une application avant de la déployer sur certains PaaS. Ensuite, nous avons pu créer des images Docker (OCI) avec leur dernière génération, les Cloud Native Buildpacks (CNCF en incubation). Sont-ils une bonne alternative au Dockerfile ? Que sont les buildpacks Paketo ? Quelles communautés les soutiennent et comment ?
Venez le découvrir lors de cette session ignite
Accelerate Enterprise Software Engineering with PlatformlessWSO2
Key takeaways:
Challenges of building platforms and the benefits of platformless.
Key principles of platformless, including API-first, cloud-native middleware, platform engineering, and developer experience.
How Choreo enables the platformless experience.
How key concepts like application architecture, domain-driven design, zero trust, and cell-based architecture are inherently a part of Choreo.
Demo of an end-to-end app built and deployed on Choreo.
Enhancing Research Orchestration Capabilities at ORNL.pdfGlobus
Cross-facility research orchestration comes with ever-changing constraints regarding the availability and suitability of various compute and data resources. In short, a flexible data and processing fabric is needed to enable the dynamic redirection of data and compute tasks throughout the lifecycle of an experiment. In this talk, we illustrate how we easily leveraged Globus services to instrument the ACE research testbed at the Oak Ridge Leadership Computing Facility with flexible data and task orchestration capabilities.
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns
Unlocking Business Potential: Tailored Technology Solutions by Prosigns
Discover how Prosigns, a leading technology solutions provider, partners with businesses to drive innovation and success. Our presentation showcases our comprehensive range of services, including custom software development, web and mobile app development, AI & ML solutions, blockchain integration, DevOps services, and Microsoft Dynamics 365 support.
Custom Software Development: Prosigns specializes in creating bespoke software solutions that cater to your unique business needs. Our team of experts works closely with you to understand your requirements and deliver tailor-made software that enhances efficiency and drives growth.
Web and Mobile App Development: From responsive websites to intuitive mobile applications, Prosigns develops cutting-edge solutions that engage users and deliver seamless experiences across devices.
AI & ML Solutions: Harnessing the power of Artificial Intelligence and Machine Learning, Prosigns provides smart solutions that automate processes, provide valuable insights, and drive informed decision-making.
Blockchain Integration: Prosigns offers comprehensive blockchain solutions, including development, integration, and consulting services, enabling businesses to leverage blockchain technology for enhanced security, transparency, and efficiency.
DevOps Services: Prosigns' DevOps services streamline development and operations processes, ensuring faster and more reliable software delivery through automation and continuous integration.
Microsoft Dynamics 365 Support: Prosigns provides comprehensive support and maintenance services for Microsoft Dynamics 365, ensuring your system is always up-to-date, secure, and running smoothly.
Learn how our collaborative approach and dedication to excellence help businesses achieve their goals and stay ahead in today's digital landscape. From concept to deployment, Prosigns is your trusted partner for transforming ideas into reality and unlocking the full potential of your business.
Join us on a journey of innovation and growth. Let's partner for success with Prosigns.
2. What
From wiki
In computer programming, unit testing is a software testing method by which
individual units of source code, sets of one or more computer program modules
together with associated control data, usage procedures, and operating
procedures, are tested to determine whether they are fit for use.
Unit testing simply verifies that individual units of code work as expected.
“
2
3. Why
• improve code quality
• self-confidence
• assurance for modifing
• learning by test cases
3
5. Entrance
start
Mix will load the test_helper.exs file before executing the tests.
# test/test_helper.exs
ExUnit.start()
5
6. Cases
options
:async - configures tests in this module to run concurrently with tests in other modules. Tests
in the same module do not run concurrently. It should be enabled only if tests do not change
any global state. Defaults to false.
use ExUnit.Case, async: true
“
6
8. Cases
context
All tests receive a context as an argument. There are some ways to build the context before
run all test cases in individual test module.
with context:
test "unit test case with context", context do
IO.inspect(context, label: "The context is:")
assert true
end
8
10. Assertions
assert
test "unit test assert" do
assert true
assert 1
assert ""
assert !nil
assert !false
assert %{} = %{a: :a, b: :b}
assert %{} != %{a: :a, b: :b}
end
10
11. Assertions
assert_raise
test "unit test assert_raise" do
assert_raise ArithmeticError, "bad argument in arithmetic expression", fn -> 1 + :a end
assert_raise RuntimeError, fn -> raise "oops" end
end
11
12. Assertions
assert_receive(d)
test "unit test assert_receive" do
main_pid = self()
spawn(fn ->
Process.sleep(1_000)
send(main_pid, {:ok, self()})
end)
assert_receive {:ok, _}, 2_000
end
test "unit test assert_received" do
send(self(), {:ok, self()})
assert_received {:ok, _}
end
12
15. Callbacks
There are many usual callbacks for ExUnit:
• setup
• setup_all
• on_exit
• start_supervised
• stop_supervised
15
16. Callbacks
purpose
Build context for test case.
The context is a map, can be used in each test case.
test "unit test case with context", context do
IO.inspect(context, label: "The context is:")
assert true
end
16
17. Callbacks
setup
• Optionally receive a map with test state and metadata.
• All setup callbacks are run before each test.
• Return keyword list / map / {:ok, keywords | map} / :ok .
17
18. Callbacks
setup
setup do
# IO.puts("Generate random number 1 in setup")
[random_num_1: Enum.random(1..1_000)]
end
setup :generate_random_number_2
defp generate_random_number_2(context) do
# IO.puts("Generate random number 2 in setup")
context
|> Map.put(:random_num_2, Enum.random(1..1_000))
end
test "setup case 1", %{random_num_1: random_num_1, random_num_2: random_num_2} = _context do
IO.puts("The random numbers in case #1 are: {#{random_num_1}, #{random_num_2}}")
assert true
end
test "setup case 2", %{random_num_1: random_num_1, random_num_2: random_num_2} = _context do
IO.puts("The random numbers in case #2 are: {#{random_num_1}, #{random_num_2}}")
assert true
end
18
19. Callbacks
setup_all
• Optionally receive a map with test state and metadata.
• Return keyword list / map / {:ok, keywords | map} / :ok .
• Invoked only once per module.
19
20. Callbacks
setup_all
setup_all do
[setup_all_random_num_1: Enum.random(1..1_000)]
end
setup_all :generate_setup_all_random_number_2
defp generate_setup_all_random_number_2(context) do
context
|> Map.put(:setup_all_random_num_2, Enum.random(1..1_000))
end
test "setup_all case 1", %{setup_all_random_num_1: num_1, setup_all_random_num_2: num_2} do
IO.puts("The random numbers in case setup_all #1 are: {#{num_1}, #{num_2}}")
end
test "setup_all case 2", %{setup_all_random_num_1: num_1, setup_all_random_num_2: num_2} do
IO.puts("The random numbers in case setup_all #2 are: {#{num_1}, #{num_2}}")
end
20
22. Mock
mock one module with test
test "unit test mock with one mocked module" do
with_mock(ModuleA, cross_gwf: fn -> :ok end, kill_gwf: fn _ -> true end) do
assert :ok == ModuleA.cross_gwf()
assert true == ModuleA.kill_gwf(nil)
end
end
22
23. Mock
mock one module with test_with_mock
test_with_mock "unit test mock using macro test_with_mock", ModuleA, [],
cross_gwf: fn -> :ok end,
kill_gwf: fn _ -> true end do
assert :ok == ModuleA.cross_gwf()
assert true == ModuleA.kill_gwf(nil)
end
23
24. Mock
mock multi-mocked modules
test "unit test mock with multi-mocked modules" do
with_mocks([
{ModuleA, [], [cross_gwf: fn -> :ok end, kill_gwf: fn _ -> true end]},
{ModuleB, [], [cross_gwf: fn -> :ok end, kill_gwf: fn _ -> true end]}
]) do
assert :ok == ModuleA.cross_gwf()
assert true == ModuleA.kill_gwf(nil)
assert :ok == ModuleB.cross_gwf()
assert true == ModuleB.kill_gwf(nil)
end
end
24
25. Mock
use callback setup_with_mocks
setup_with_mocks([
{ModuleA, [], [cross_gwf: fn -> 1 end, kill_gwf: fn _ -> 2 end]},
{ModuleB, [], [cross_gwf: fn -> 1 end, kill_gwf: fn _ -> 2 end]}
]) do
:ok
end
test "unit test mock use setup with setup with mocks modulea" do
assert 1 == ModuleA.cross_gwf()
assert 2 == ModuleA.kill_gwf(nil)
end
test "unit test mock use setup with setup with mocks moduleb" do
assert 1 == ModuleB.cross_gwf()
assert 2 == ModuleB.kill_gwf(nil)
end
25
26. Reversed to codes
reasonable input and output for one function
test "unit test for reversed to codes" do
assert :"1" == LearnExunit.to_to_atom(build_params_for_func("1"))
assert :a == LearnExunit.to_to_atom(build_params_for_func("a"))
assert :"1" == LearnExunit.to_atom("1")
assert :a == LearnExunit.to_atom("a")
end
26
27. Reversed to codes
well-de ned boundaries
defp login_by_email(user, %{password: password} = args) do
login_verify_passwd(is_correct_password?(password), user, args)
end
@doc false
defp login_verify_passwd(true, %{if_mfa: false} = user, args) do
after_login_successfully(user, args, "email", %{})
end
defp login_verify_passwd(true, user, _args) do
{:ok, %{user: user, if_need_verify_mfa: true}}
end
defp login_verify_passwd(false, _, _) do
{:error, %{message: "Password is incorrect.", status: 400}}
end
27