Service virtualization and pact devops

Feb 25, 2024 | by Ralph Van Der Horst

Service Virtualization and PACT DEVOPS

Service Virtualization and PACT integration

Before we start I want you too look at this drawing and when you have read the blog I hope when you look at this drawing again you understand the context

The article starts with brief description of what service virtualization is, what pact is and where it comes together!

Service virtualization is a technique in software development and testing that allows for the simulation of external systems or services. By creating a virtual environment that mimics real external services, developers and testers can evaluate applications against these simulated services without relying on the actual external systems. This is particularly beneficial for integration testing, especially when external systems are difficult to access, unstable, or expensive to set up for testing purposes.

Some context regarding Stub Mock and the position of Service Virtualization

Stub:

  • Simplifies dependencies by providing predefined responses.

  • Used to simplify the environment, not for interaction control. Mock:

  • Simulates the behavior of dependencies with expectations about usage.

  • Focused on interaction verification, checks if methods have been called.

Service Virtualization:

  • A chain of mocks simulates external systems for integration tests.
  • Enables independent and detailed scenario testing without real external services.

Why Service virtualization

Service virtualization works by creating lightweight, scalable, and configurable simulations of real systems. These virtual services mimic the interfaces of dependent systems, allowing for the simulation of interactions with those systems without the need for their actual availability. This process includes capturing traffic between an application and the real services, and then configuring the virtual service to provide similar responses to requests. This enables testing of various scenarios, even in complex systems, without the cost and complexity of managing the real dependencies.

Call function

fetch('https://api.voorbeeldgemeente.nl/brp/persoonsgegevens?bsn=123456789', {
  method: 'GET',
  headers: {
    'Accept': 'application/json',
    'Authorization': 'Bearer uwTokenHier'  }})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Fout bij het ophalen van de gegevens:', error));});

Voorbeeld van een mock

const express = require('express');
const app = express();
const port = 3000;
app.use(express.json());

app.get('/brp/persoonsgegevens', (req, res) => {
    if (req.query.bsn === '123456789') {
        res.json({ "naam": "Jan Jansen", "bsn": "123456789" });
    } else {
        res.json({ "naam": "Jan de Vries", "bsn": "987654321" }); // Klein verschil in de response
    }
});
app.listen(port, () => {
    console.log(`Mock BRP server luistert op poort ${port}`);

The Upsides of Service Virtualization

Service virtualization stands out for its ability to create realistic testing environments, which is crucial for validating the integration and performance of various components in a software ecosystem. Here are its key benefits:

  • Increased Test Coverage: Ability to execute test scenarios that are difficult or impossible in a physical environment.
  • Risk Reduction: Early testing with virtualized services helps to identify integration issues sooner, decreasing the risk of errors in production.
  • Parallel Development and Testing: Simulation of dependent services allows for simultaneous development and testing, increasing efficiency and reducing development time.
  • Cost Savings: By virtualizing only necessary services, full testing environments become unnecessary, leading to cost savings.
  • Quality Improvement: Early and more comprehensive testing through service virtualization helps to identify and fix errors sooner, improving software quality.

The Flip Side: Challenges of Service Virtualization

Despite its numerous advantages, service virtualization isn’t without its drawbacks, which can impact its implementation and effectiveness:

  • Initial Costs and Time: Setting up service virtualization requires an initial investment.
  • Complexity: Accurately simulating all external system behaviors is complex and needs expert developers and testers at first
  • Obsolescence Risk: Virtual services can become outdated as real services evolve.

Pact: A Mitigating Force for Service Virtualization

  • Reduces the need for detailed simulations.
  • Focuses on essential interactions from a consumer perspective.
  • Makes integration tests lighter and more maintainable.

Why PACT

Why Choose Pact for Software Testing Pact is a tool that makes software testing easier and more focused on what the user needs. Here’s why it’s great for developers and customer which is central as the consumer:

  • Defining Contracts: Pact uses contracts that describe the expected interactions between consumers and providers. These contracts are automatically generated during the test phase of the consumer (the customer).
  • Verifying Contracts: When the provider develops or updates their part of the software, Pact verifies whether the provider still meets the expectations of the consumer as outlined in the contract.
  • Feedback Loop: If there are discrepancies, Pact provides immediate feedback, allowing developers to identify and resolve issues before the code goes into production.

PACT contract between consumer en provider

app.get('/brp/persoonsgegevens', (req, res) => {
   if (req.query.bsn === '123456789') {
       res.json({ "naam": "Jan Jansen", "bsn": "123456789" });
 }})

Provider has a new and other response definition

app.get('/brp/persoonsgegevens', (req, res) => {
if (req.query.bsn === '123456789')     // Let op: `oorspronkelijke contract.
  res.json({ "volledigeNaam": "Jan Jansen", "bsn": "123456789", "geboortedatum": "01-01-1980" });
}});
const { Pact } = require('@pact-foundation/pact')
const path = require('path')
 const provider = new Pact({
consumer: 'MijnApp',
provider: 'BRPService',
port: 1234,
log: path.resolve(process.cwd(), 'logs', 'pact.log'),
dir: path.resolve(process.cwd(), 'pacts'),
spec: 2,});
provider.addInteraction({
	uponReceiving: 'een verzoek voor persoonsgegevens met BSN 123456789',
	withRequest: {
		method: 'GET',
		path: '/brp/persoonsgegevens',
		query: 'bsn=123456789'},
willRespondWith: {
	status: 200,
	body: {
 		naam: 'Jan Jansen',
		bsn: '123456789}
}
});

How Pact Makes Your Software More Reliable

When building software, making sure different parts work well together is super important. That’s where Pact comes in. It’s like a helper that makes sure all the pieces of your software can talk to each other without problems. Here’s why Pact is awesome for anyone making software:

Finding Problems Early:

  • Spot Issues Sooner: Pact lets you find any chat problems between different parts of your software early on. It’s like knowing it’s going to rain before you leave the house, so you can grab an umbrella.

Trusting Your Software More

  • Keeping Things Smooth: When you change one part of your software, Pact checks to make sure it doesn’t mess up how it talks to other parts. This is like making sure a new piece in a puzzle still fits perfectly.

Better Software, Faster

  • Quick and Safe Updates: By using Pact in your software checks (CI/CD pipelines), it’s like having a safety net. It makes sure any updates you make don’t cause problems, helping you share your software updates smoothly and confidently.
  • Faster to the Finish Line: With Pact, you can be sure that all parts of your software are chatting nicely, which means you can make updates or new versions faster and without worrying about breaking things.

In Simple Terms

Pact is like the friend who makes sure everyone in the group is on the same page. It checks that all parts of your software are working well together, so you can make changes and improve things without causing any drama. This means happier teams and better software for everyone.

Benefits of Using Pact

  • Early Detection of Issues: Pact allows teams to identify problems between services early in the development cycle. This means less time spent fixing bugs in later stages.
  • Increased Confidence: By ensuring that all parts of your application can communicate effectively, Pact boosts confidence in the stability and reliability of your system.
  • Facilitates Parallel Development:
  • Developers can work on different services simultaneously without waiting for the other parts to be completed, speeding up the development process.
  • Integration with CI/CD:
  • Pact integrates seamlessly into Continuous Integration/Continuous Deployment pipelines, automating contract testing and verification
  • Improved Quality: With regular and automated contract testing, the overall quality of the application improves as integration issues are caught and resolved early.

Downsides of Using Pact

  • Initial Learning Curve: Teams may need time to learn how to effectively use Pact and integrate it into their development workflow.
  • Setup Time: Initial setup and configuration of Pact can take some time, especially in complex systems with many interdependent services.
  • Maintenance of Contracts: Contracts need to be kept up-to-date with changes in service interfaces, which can add overhead to development processes.
  • Potential for Over-reliance: There’s a risk of relying too much on Pact tests and neglecting other forms of testing like end-to-end tests, which can lead to gaps in test coverage.
  • Integration Challenges: In some cases, integrating Pact into existing projects or with certain technologies can be challenging and may require additional tooling or workarounds.

Summary

In summary, while Pact offers significant advantages for testing and ensuring reliable integrations in microservices architectures, teams should be mindful of the potential challenges and be prepared to invest time in learning and maintaining the tool.

In conclusion, both service virtualization and Pact offer compelling advantages for modern software development, particularly in environments where microservices and complex integrations are common. Service virtualization enables teams to simulate and test against external dependencies without the need for actual services to be available, which significantly increases test coverage and efficiency. It allows for testing in isolation, reducing risks associated with integration issues and enabling faster, more reliable development cycles.

Pact, on the other hand, provides a robust framework for Consumer-Driven Contract Testing, ensuring that interactions between different parts of a system meet agreed-upon expectations. Its early detection of integration issues, seamless integration into CI/CD pipelines, and emphasis on consumer-provider contracts improve the quality and reliability of software deployments. By facilitating parallel development and reducing the feedback loop for identifying and fixing bugs, Pact enhances team productivity and fosters a more agile development process.

While both approaches come with their initial setup complexities and learning curves, the long-term benefits—such as cost savings, improved software quality, and faster release cycles—far outweigh these challenges. The combination of service virtualization and Pact represents a powerful strategy for achieving more reliable and efficient software development and testing processes. Overall, the adoption of these methodologies is a positive move for organizations looking to innovate and maintain high standards of quality and reliability in their software products.

by Ralph Van Der Horst

arrow right
back to blog

share this article

Relevant articles

Serverless Pact Broker in AWS ECS Fargate

Serverless Pact Broker in AWS ECS Fargate

Free Course Testautomation with Katalon Studio and Salesforce

Free Course Testautomation with Katalon Studio and Salesforce

AI Generated course leveraging on Chat gpt

AI Generated course leveraging on Chat gpt