Refactor to use pytest over unittest
MODIFY
testing-unit-py/README.md
testing-unit-py/README.md
@@ -9,13 +9,14 @@ An example of writing mock-based unit tests with both infrastructure definition
```bash
$ python3 -m venv venv
$ source venv/bin/activate
- $ pip3 install -r requirements.txt
+ $ python -m pip install --upgrade pip
+ $ python -m pip install -r requirements.txt
```
2. Run the tests:
```
- $ python -m unittest
+ $ python -m pytest # or simply `pytest`
------------------------------------------------------------
Ran 2 tests in 0.004s

MODIFY
testing-unit-py/requirements.txt
testing-unit-py/requirements.txt
pulumi>=3.5.1,<4.0.0
pulumi-aws>=4.0.0,<5.0.0
+pytest
\ No newline at end of file

MODIFY
testing-unit-py/test_ec2.py
testing-unit-py/test_ec2.py
@@ -24,33 +24,33 @@ pulumi.runtime.set_mocks(MyMocks())
# Now actually import the code that creates resources, and then test it.
import infra
-class TestingWithMocks(unittest.TestCase):
+
# Test if the service has tags and a name tag.
@pulumi.runtime.test
- def test_server_tags(self):
+def test_server_tags():
def check_tags(args):
urn, tags = args
- self.assertIsNotNone(tags, f'server {urn} must have tags')
- self.assertIn('Name', tags, 'server {urn} must have a name tag')
+ assert tags, f'server {urn} must have tags'
+ assert 'Name' in tags, 'server {urn} must have a name tag'
return pulumi.Output.all(infra.server.urn, infra.server.tags).apply(check_tags)
# Test if the instance is configured with user_data.
@pulumi.runtime.test
- def test_server_userdata(self):
+def test_server_userdata():
def check_user_data(args):
urn, user_data = args
- self.assertFalse(user_data, f'illegal use of user_data on server {urn}')
+ assert user_data == None, f'illegal use of user_data on server {urn}'
return pulumi.Output.all(infra.server.urn, infra.server.user_data).apply(check_user_data)
# Test if port 22 for ssh is exposed.
@pulumi.runtime.test
- def test_security_group_rules(self):
+def test_security_group_rules():
def check_security_group_rules(args):
urn, ingress = args
ssh_open = any([rule['from_port'] == 22 and any([block == "0.0.0.0/0" for block in rule['cidr_blocks']]) for rule in ingress])
- self.assertFalse(ssh_open, f'security group {urn} exposes port 22 to the Internet (CIDR 0.0.0.0/0)')
+ assert ssh_open == False, f'security group {urn} exposes port 22 to the Internet (CIDR 0.0.0.0/0)'
# Return the results of the unit tests.
return pulumi.Output.all(infra.group.urn, infra.group.ingress).apply(check_security_group_rules)

Refactor to use pytest over unittest (#1037)