Skip to content

Commit 510e7d7

Browse files
Update Blog “sivayanama-testing-opsramp-apis-with-pytest-fixtures”
1 parent c5e7234 commit 510e7d7

File tree

1 file changed

+186
-19
lines changed

1 file changed

+186
-19
lines changed

content/blog/sivayanama-testing-opsramp-apis-with-pytest-fixtures.md

Lines changed: 186 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
---
2-
title: Sivayanama - Testing OpsRamp APIs with PyTest Fixtures
2+
title: Testing OpsRamp APIs with PyTest Fixtures
33
date: 2023-07-26T06:58:31.750Z
44
featuredBlog: true
55
author: BalaSubramanian Vetrivel
@@ -8,67 +8,234 @@ disable: false
88
---
99
<!--StartFragment-->
1010

11-
# Sivayanama - Testing OpsRamp APIs with PyTest Fixtures
12-
13-
<!--EndFragment-->
11+
# Testing OpsRamp APIs with PyTest Fixtures
1412

1513

1614

1715
OpsRamp platform  provides rich set of APIs. By using these APIs customers can build soultion to automate various ITOM workflows such as discovery and monitoring , event and incident mangement and remidiation and automation. Testing these APIs, automated solution  are very critical to ensure reliability and stability of the same. PyTest is a powerful python testing framework and it is widely used to test APIs. Fixtures is one of the most important capabilities of PyTest framework. In this article, we will discuss some advanced techniques of testing OpsRamp APIs using PyTest fixtures.
1816

1917

2018

21-
What Fixtures are 
19+
## What Fixtures are 
2220

2321
PyTest fixtures are a special type of python function that provision fixed base line for testing.With the help of this base line we can ensure tests are run in reliable manner and produce consistent results and the same tests can be repeatable.
2422

25-
26-
27-
Install PyTest
23+
## Install PyTest
2824

2925
Run the below command 
3026

27+
```shell
3128
pip install -U pytest
29+
```
3230

3331

3432

35-
Verify PyTest installation 
33+
## Verify PyTest installation 
3634

3735
Run the below command 
3836

39-
 pytest --version
40-
37+
```shell
38+
pytest --version
4139
pytest 7.4.0
4240

41+
```
4342

44-
45-
Define Fixture
43+
## Define Fixture
4644

4745
We can define fixtures just by decorating a simple python function with [@pytest.fixture](https://docs.pytest.org/en/6.2.x/reference.html#pytest.fixture) for example 
4846

47+
```python
48+
import pytest
49+
50+
@pytest.fixture
51+
def hello_world():
52+
return 'Hello, Happy testing'
53+
```
54+
55+
56+
57+
## Invoke fixtures
58+
59+
Test functions can invoke fixtures just by declaring the required fixtures as arguments. 
4960

61+
```python
62+
def test_hello_world(hello_world):
63+
assert hello_world == 'Hello, Happy testing'
64+
```
65+
66+
## Invoke OpsRamp API
67+
68+
Let us try to execute OpsRamp [Get Access Token API](https://develop.opsramp.com/v2/api/auth/tenancy-auth-oauth-token)  as shown below.
69+
70+
```python
71+
import http.client
72+
import json
73+
import traceback
74+
import urllib
75+
from asyncio.log import logger
5076

5177
import pytest
5278

79+
def get_auth_header(api_endpoint, client_id, client_secret, grant_type="client_credentials"):
80+
"""
81+
Returns bearer token string in the blow format
82+
bearer adfa-afdaf-1599-402c-a3ee-1ed24f597cc8
83+
"""
84+
85+
api_connection = http.client.HTTPSConnection(api_endpoint)
86+
params = {"client_id": client_id, "client_secret": client_secret, "grant_type": "client_credentials"}
87+
88+
payload = urllib.parse.urlencode(params)
89+
90+
headers = {
91+
'accept': "application/json",
92+
'content-type': "application/x-www-form-urlencoded",
93+
}
94+
95+
```
96+
97+
## Define Fixture to get Access Token
98+
99+
You can transform above function as PyTest Fixture by simply decorating the code as shown below 
100+
53101

54102

55103
@pytest.fixture
56104

57-
def hello_world()
105+
def get_auth_header(api_endpoint, client_id, client_secret, grant_type="client_credentials"):
58106

59-
return 'Hello, Happy testing'
60107

61108

109+
## Autouse fixtures
62110

63-
Invoking fixtures
111+
Sometimes some of your fixtures are required for all other tests. The above Get acces token is perfect use case for this. Every API call is depending on this API. In this case you can make this fixture as “autouse fixture”  by passing in autouse=True to the fixture’s decorator. The autouse fixure capability will reduce lot of reduanct requests. 
64112

65-
Test functions can invoke fixtures just by declaring the required fixtures as arguments. 
113+
```python
114+
@pytest.fixture(autouse=True)
115+
def get_auth_header(api_endpoint, client_id, client_secret, grant_type="client_credentials"):
116+
```
117+
118+
119+
120+
## Provisioing of third-party plugin Fixtures 
121+
122+
Not necessarily you have to define all fixtures on your own code. Fixtures can be provided by third party plugins as well and you are free to use them. You just need to install the required plugins. We will see an example with  pytest-datadir plugin
123+
124+
125+
126+
Install this plugin as shown below 
127+
128+
```shell
129+
pip install pytest-datadir
130+
```
131+
132+
133+
134+
```python
135+
@pytest.fixture(autouse=True)
136+
137+
def get_bearer_token(shared_datadir,request):
138+
139+
json_path = (shared_datadir / "auth_header_input.json")
140+
```
141+
142+
![](https://lh4.googleusercontent.com/dacTgDdw17BzeyCitShA73WSip9LVtenQoNN-uraaN5tKEU5cA_xP3cEmNPWmTzU3A1HegdoOVvwPbyYqQuoLeEk4W766nIvpBdoTzUdIiT2dXiOQG0_h7atQWS7-T9qvRrieuhlEV84VS15ir11Ocw)
143+
144+
145+
146+
get_bearer_token  fixture is using [shared_datadir](https://pypi.org/project/pytest-datadir/) fixture from third party plugin. Shared_datadir fixture provision  data folder from the current folder as pathlib.Path object. 
147+
148+
149+
150+
## Fixture finalization
151+
152+
Usually we do teardown or cleanup acititivties for each test for many good reasons such as the following 
153+
154+
The executed tests will not impact other tests
155+
156+
Do not want to have the testing environment piled up with tons of test data
157+
158+
Every tests should execute in a clean state
159+
160+
161+
162+
Fixtures offers very powerful teardown, cleanup capability known as finalization. 
163+
164+
165+
166+
```python
167+
@pytest.fixture()
168+
169+
def create_client( shared_datadir, get_bearer_token,request):
170+
171+
client = Client()
172+
173+
client.logger.debug("IN\*\**")
174+
175+
176+
177+
payload_file = (shared_datadir / "create_client1.json")
178+
179+
input_payload= client.http_helper.to_json(payload_file)
180+
181+
182+
183+
client_response = client.create_client(input_payload,get_bearer_token)
184+
185+
186+
187+
def terminate_client():
188+
189+
client.logger.debug("IN\*\**")
190+
191+
util=Utils()
192+
193+
194+
195+
clientId=Client.clientId
196+
197+
198+
199+
if len(str(clientId)) > 0:
200+
201+
oauth_token=get_bearer_token
202+
203+
client.terminate_client(clientId, oauth_token)
204+
205+
client.logger.debug("OUT\*\**")
206+
207+
208+
209+
request.addfinalizer(terminate_client)
210+
211+
212+
213+
214+
215+
client.print_log(client_response)
216+
217+
client.logger.debug("OUT\*\**")
218+
219+
return client_response
220+
```
221+
222+
You should add the finalizer function to the request’s context object of the test as shown below 
223+
224+
request.addfinalizer(terminate_client)
225+
226+
227+
228+
In the above example we do all the test set up on the client and execute the tests, Once the test is complete finalizer function runs and cleans up the whole thing. 
229+
230+
231+
232+
## Conclusion
233+
234+
In this article we have seen what are PyTest Fixtures, how to define, invoke and Fixtures. Also we have seen how to leverage testing of OpsRamp APIs using these fixtures, how to do teardown activities using finalizer functions. 
66235

67236

68237

69-
def test_hello_world(hello_world)
70238

71-
assert hello_world == 'Hello, Happy testing'
72239

73240

74241

0 commit comments

Comments
 (0)