...

What We Think

Blog

Keep up with the latest in technological advancements and business strategies, with thought leadership articles contributed by our staff.
TECH

March 28, 2024

Mocking in Python's Unittest

Mocking is a powerful technique in unit testing that allows developers to simulate the behavior of complex dependencies or external systems. In Python's unittest framework, the unittest.mock module provides robust support for creating and working with mock objects. This topic delves into the concept of mocking and demonstrates its usage within Python's unittest framework.

 

Concept of Mocking:

Mocking involves substituting real objects or functions with simulated versions, known as mock objects. These mock objects mimic the behavior of their real counterparts, allowing developers to isolate components under test from their dependencies. Mocks are programmable and can be configured to return predefined values, raise exceptions, or record interactions.

 

Key Concepts of Mocking:

  • Mock Objects: Mock objects are objects that simulate the behavior of real objects. They can be configured to behave in specific ways and record interactions with them.
  • Patch: Patching is a technique used to replace objects or functions in the code under test with mock objects. This allows developers to control the behavior of dependencies during testing.
  • Assertions: Assertions in unit tests verify that certain conditions are met. Mocks can be used in assertions to verify that specific methods were called with the expected arguments or to check the number of times a method was called.

 

Using Mocking in Python's Unittest:

Python's unittest.mock module provides a flexible framework for creating and working with mock objects. Developers can use the patch() function to replace objects or functions with mock equivalents temporarily. Additionally, assertions such as assert_called_once_with() and assert_called_with() can be used to verify the behavior of mock objects.

 

Advantages of Mocking:

  1. Isolation: Mocking enables the isolation of code under test, facilitating focused testing without reliance on external dependencies.
  2. Flexibility: Mock objects offer flexibility in configuring behaviors, allowing developers to simulate various scenarios and edge cases effortlessly.
  3. Speed: Mocking can expedite testing by eliminating the need to interact with external systems or resources, resulting in faster test execution times.
  4. Enhanced Test Coverage: Mocking empowers developers to test error-handling scenarios and exceptional conditions that may be challenging to reproduce with real dependencies.

 

Limitations of Mocking:

  1. Complexity: Overuse of mocking can lead to overly complex test suites, diminishing readability and maintainability.
  2. Dependency on Implementation: Mocks are tightly coupled to the implementation details of the code under test, making tests susceptible to breaking when implementation changes occur.
  3. Risk of False Positives: Inadequate verification of mock behavior may result in false positives, where tests pass despite incorrect implementations or missing assertions.

 

Best Practices for Effective Mocking:

  1. Focused Testing: Prioritize testing the behavior of the code under test rather than the implementation details of dependencies.
  2. Clear Documentation: Document the purpose and behavior of mock objects to improve code understanding and facilitate collaboration among team members.
  3. Regular Review: Periodically review mock usage to ensure tests remain relevant, maintainable, and aligned with evolving codebases.

 

Example:

Suppose you have a function in your application like the following, which communicates with an external API to retrieve data:

import requests

def get_data_from_api(url):

response = requests.get(url)
if response.status_code == 200:

return response.json()

else:

return None

In testing, you want to verify that the get_data_from_api() function handles situations correctly when the API returns data successfully and when it encounters errors. However, actually calling the API during testing may cause issues such as: time consumption, dependency on network connection, or error-prone behavior.

Instead of making actual calls to the API, you can use the Mocking technique to create a mock object, simulating the API's behavior during testing. Here's an example of how to do this in unittest:

import unittest
from unittest.mock import patch
from my_module import get_data_from_api
 
class TestGetDataFromAPI(unittest.TestCase):
 
@patch('my_module.requests.get')
def test_get_data_success(self, mock_get):
mock_get.return_value.status_code = 200
mock_get.return_value.json.return_value = {'data': 'test'}
data = get_data_from_api('http://example.com/api')
self.assertEqual(data, {'data': 'test'})
 
@patch('my_module.requests.get')
def test_get_data_failure(self, mock_get):
mock_get.return_value.status_code = 404
data = get_data_from_api('http://example.com/api')
self.assertIsNone(data)
 
if __name__ == '__main__': unittest.main()
 
In this example, we use the @patch decorator to replace the requests.get function with a mock object. In each test case, we set the expected return values of the mock object (e.g., status_code and json), thereby testing whether the get_data_from_api() function works correctly in both successful and failed cases.

 

Conclusion:

Mocking is a valuable technique in unit testing that enables developers to create reliable and maintainable test suites. By leveraging the capabilities of Python's unittest.mock module, developers can effectively simulate the behavior of dependencies and external systems, leading to more robust and efficient testing practices.

 

References:

View More
TECH

March 27, 2024

What have you gained from the software tester job?

You often hear about what you need to learn to become a tester, but have you ever wondered what you will learn when you are a tester? Besides enhancing specialized skills such as software testing, requirement analysis, and staying updated on new technologies, you can also improve some useful knowledge and skills in life as follows:

Deep Understanding of Various Business Domains

This is truly interesting because few professions can help you understand another industry's business so thoroughly. As a tester in software project, you have the opportunity to read all customer requirements, understand the project's detailed design, and thus comprehend the activities, processes, or specific requirements of a particular organization or industry. While developers may only understand a part of the functionality which they are responsible for. Due to job demands, testers must learn more about the context, operational environment, end-users behavior, security issues, and compliance of the field they are testing in. Therefore, testers accumulate knowledge about various business domains such as banking, logistics, ERP, etc.

Furthermore, because testers test all function of the product, they will have a deep understanding of how business operations are reflected in a software product. They know exactly how real-world data flows will be stored and processed within the software system.

Imagine after testing a material management software system for a manufacturing factory, you will know how the material ordering process works, how purchased materials are categorized and stored, how to calculate the quantity of materials for each production line, how to calculate inventory, and the appropriate time to reorder new materials... You may even understand the production process better than an employee of that factory. This is amazing!

 

 

Improving Communication Skills

In the world of developing a software product, developers are builders; they create code that makes everything work. Testers are detectives; they verify the correctness of the product, accompanied by a list of errors that developers need to fix. It is frustrating to be pointed out errors and have to fix them; especially those not mentioned in the design but must be done according to the tester's suggestion. Therefore, testers and developers are often seen as two opposing sides.

When starting out as a tester, it is hard to avoid arguments and conflicts. However, over times, to persuade and prevent arguments with developers, testers practice the ability to express opinions, provide feedback, and report clearly, understandably, and convincingly. They also learn to listen, share information, exchange ideas, and resolve conflicts constructively. This significantly improves their communication and persuasive skills.

Viewing Problems from Various Perspectives

To ensure that the testing process is comprehensive and reliable, throughout the work, testers must test the product from various perspectives. As a good tester, you not only test what is mentioned in the design but also have to stand from the end-user's perspective to think whether your software is user-friendly, helps them operate faster... You not only test the software when it operates under good conditions but also test it under poor conditions. You need to create various test scenarios. This helps you develop a multidimensional mindset for solving different life problems. 

 

In summary, as a tester, you not only contribute to the development of software, bring many useful experiences for end-users but also learn and improve many good skills for your life.

 

Ready to take your testing journey to the next level?

Reach out to IVC to explore practical QA methods and tailored guidance for software testers.

Contact IVC for a Free Consultation

Image source:

https://www.freepik.com/free-vector/disruptive-education-globe-background-vector-geography-digital-remix_17213285.htm#fromView=search&page=1&position=26&uuid=33b4ecf5-cd4b-4d6d-b917-6213ca1bf6d7

https://www.freepik.com/free-vector/flat-design-erp-illustration_25561035.htm#fromView=search&page=1&position=8&uuid=ebbdf32b-5bf8-433d-a85e-8dc413076bdd

https://www.freepik.com/free-photo/representation-user-experience-interface-design_94963704.htm#fromView=search&page=2&position=29&uuid=4ef0f53a-05c6-42d4-adda-7102f1ac25b2

https://www.freepik.com/free-photo/programmers-questioning-source-cyber-attacks-system-security-coverage-software-technician-triangulates-hacker-location-by-updating-safety-script-codes-data-processor-sequencer_25474009.htm#fromView=search&page=1&position=24&uuid=c8164e4a-0cb7-41c8-9492-953b98fbb71d

View More
TECH

March 26, 2024

Some array sorting issues and solutions in ReactJS

To sort the data array, we can use many methods. Incorrect selection can lead to errors that are difficult to detect with uniform, standard-format test data. I would like to share some errors and solutions that I have encountered in a React project, as follows:

View More
TECH

March 22, 2024

What is Google Cloud Search ?

Your company is using Google Workplace, You have many information in Gmail, Google Drive, Google Calendar, Google Contacts and others alike. Suddenly, you remember you need to find some information, and you don't remember where that information is in Google Workplace. Google Cloud Search is is what you need in this case.

View More
TECH

March 22, 2024

NextJS: Encrypt Cookie-Based sessions with NodeJS Crypto module

Cookie-base is one of the primary uses for session management. It is easy to implement, suits smaller applications, and has a lower server load but may offer less security than others.
As cookies are susceptible to client-side security risks, the key to safeguarding user information from unauthorized access is to carefully encrypt the sensitive data before storing it in the cookie. This way, even if a cookie is stolen, the data inside remains unreadable.

View More
TECH

March 20, 2024

Be Confident with Data Security: Introducing Microsoft Azure's KeyVault.

In today's digital world, data security has become a top priority for businesses and organizations.
Microsoft Azure, one of the world's leading cloud computing platforms, has introduced a powerful solution to this problem, which is a KeyVault. 

View More
TECH

March 19, 2024

Building A Basic Real-Time Application with Socket.io in Node.js and React.js

In today's digital age, real-time communication has become a crucial aspect of web applications. Whether it's for live chats, collaborative editing, or dynamic data updates, users expect instantaneous responses. Achieving this functionality is made possible by technologies like Socket.io, particularly when combined with the power of Node.js on the backend and React.js on the frontend.

View More
TECH

February 27, 2024

Enhancing Coding Experience: The Value of ChatGPT for Programmers

In the dynamic world of technology, programmers encounter a diverse array of challenges. These range from debugging intricate code to devising innovative solutions for software development projects. Amidst this complexity, ChatGPT emerges as a valuable companion for programmers, offering several advantages to streamline and enhance their coding experience.

View More
TECH

January 11, 2024

The cost of quality (CoQ) in software development

The software production and business environment is becoming more and more competitive, customers have more and better choices of high-quality products or services on the market.
Companies must differentiate themselves from the competition by hearing customer requirements and providing products or services that meet customer requirements with high levels of reliability and quality.

  • The cost of quality (CoQ)

The cost of quality is all of the costs that the software development team must bear to ensure the production of quality products or services.
The cost of quality allows the software development team to analyze the causes of problems and improve their products or services.
The cost of quality associated with a project consists of the cost of good quality and the cost of poor quality.
The cost of good quality (Cost of conformance) includes Prevention costs and Appraisal costs.
The cost of poor quality (Cost of nonconformance) includes Internal failure costs and External failure costs.

  • Prevention costs

These are costs associated with preventing problems and errors from occurring during the development of a product or service.
This includes activities such as training, process improvement, quality management planning, etc.

  • Appraisal costs

These are costs associated with evaluating product or service quality by finding errors and detecting defects during the development of a product or service.
This includes activities such as testing, inspection, etc.

  • Internal failure costs

Internal failure costs are the costs that arise when problems or issues are found and corrected before the product or service is released to users.
This includes costs associated with rework, scrap, etc.

  • External failure costs

External failure costs are the costs that arise when problems or bugs are found in a product or service after it has been released to users.
This includes costs associated with customer complaints, warranty claims, etc.

In summary, the cost of quality plays an important role in ensuring the quality of a product or service and creating value for customers.
The software development team should invest in preventing problems and errors from occurring by training employees on quality,
improving quality control processes and strengthening evaluation activities of product quality in the production process to ensure that the product or service meets quality standards and customer requirements.
The optimal cost of quality reflects the appropriate balance for investing in the cost of prevention and appraisal to avoid failure costs (internal/external).

Image Source
https://www.freepik.com

View More
TECH

December 8, 2023

Introducing Ngrok: Unified Ingress Platform for developers

By creating a tunnel from your computer (desktop, localhost) through the Firewall/Nat system, you can access the workstation from the internet.  Ngrok can help you run project demos for customers to view from their own computers without needing to deploy the web to the server.
Additionally, you can test responsiveness on mobile easily through the URL that Ngrok provides and build a webhook to your local host.
Ngrok is available for macOS, Windows, and Linux.

How does Ngrok Work?

When you use Ngrok, you start it on your local machine and specify the port number of the local server that you want to expose. When you do that, Ngrok creates a secure tunnel to a public endpoint (a ngrok.io URL) that is accessible over the internet.

 

So now, all the traffic to the public endpoint is forwarded as a request to the local server running on your machine. Your local server responds to this request or traffic back to this public endpoint. This is also called port forwarding or localhost tunneling. This is the underlying principle through which Ngrok maps your local development server to one of its servers, making it seem like it’s just your local development server hosted somewhere.

Pricing

Ngrok currently includes 1 free package and 3 paid packages.

About pricing: https://ngrok.com/pricing

Ngrok Security

Ngrok is a highly secure platform for remote access and is safe to use. Ngrok provides tunneling, as mentioned above, which enables users to access local-hosted servers from outside the machine.

Quick start

  • Step 1: Install Ngrok

https://ngrok.com/download

  • Step 2: Connect your account

You need to go to the homepage https://dashboard.ngrok.com/, register and manage your account, here after logging in, go to the Your Authtoken section to get the login token.

Run the following command in your terminal to install the auth token and connect the Ngrok agent to your account.

-> ngrok config add-authtoken <TOKEN>

 

  • Step 3: Start Ngrok by running the following command

-> ngrok http http://localhost:8080

If your app is listening on a different URL, change the above command to match.

 

As shown above, the tunnel is created - press CTRL+C to terminate this connection, once the connection is maintained you can access your web application using the URL provided by ngrok
You can access this address from any device on the internet such as using your phone to access, send to friends, send customers to check first...

Conclusion

We’ve learned how Ngrok works internally by understanding the concept of port-forwarding and local-host tunneling. Ngrok is an extremely helpful tool for developers, especially for testing and debugging purposes in various types of applications.

References

[1]: https://ngrok.com/

[2]: https://www.huntress.com/hubfs/Blog%20-%20The%20State%20of%20the%20Dark%20Web/Blog-Ngrok-Tunnelling.jpg

[3]: https://requestly.io/wp-content/uploads/2023/09/646e1ca5cf42db6cf447b6cd_5.webp

View More
1 19 20 21 22 23 26
Let's explore a Partnership Opportunity

CONTACT US



At ISB Vietnam, we are always open to exploring new partnership opportunities.

If you're seeking a reliable, long-term partner who values collaboration and shared growth, we'd be happy to connect and discuss how we can work together.

Add the attachment *Up to 10MB