mirror of
https://github.com/ansible-collections/community.general.git
synced 2026-05-07 22:02:50 +00:00
Reformat everything.
This commit is contained in:
@@ -12,7 +12,10 @@ from ansible_collections.community.general.plugins.lookup.onepassword import One
|
||||
@pytest.fixture
|
||||
def fake_op(mocker):
|
||||
def _fake_op(version):
|
||||
mocker.patch("ansible_collections.community.general.plugins.lookup.onepassword.OnePassCLIBase.get_current_version", return_value=version)
|
||||
mocker.patch(
|
||||
"ansible_collections.community.general.plugins.lookup.onepassword.OnePassCLIBase.get_current_version",
|
||||
return_value=version,
|
||||
)
|
||||
op = OnePass()
|
||||
op._config._config_file_path = "/home/jin/.op/config"
|
||||
mocker.patch.object(op._cli, "_run")
|
||||
|
||||
@@ -22,31 +22,22 @@ def load_file(file):
|
||||
MOCK_ENTRIES = {
|
||||
OnePassCLIv1: [
|
||||
{
|
||||
'vault_name': 'Acme "Quot\'d" Servers',
|
||||
'queries': [
|
||||
'0123456789',
|
||||
'Mock "Quot\'d" Server'
|
||||
],
|
||||
'expected': ['t0pS3cret', 't0pS3cret'],
|
||||
'output': load_file("v1_out_01.json"),
|
||||
"vault_name": 'Acme "Quot\'d" Servers',
|
||||
"queries": ["0123456789", 'Mock "Quot\'d" Server'],
|
||||
"expected": ["t0pS3cret", "t0pS3cret"],
|
||||
"output": load_file("v1_out_01.json"),
|
||||
},
|
||||
{
|
||||
'vault_name': 'Acme Logins',
|
||||
'queries': [
|
||||
'9876543210',
|
||||
'Mock Website',
|
||||
'acme.com'
|
||||
],
|
||||
'expected': ['t0pS3cret', 't0pS3cret', 't0pS3cret'],
|
||||
'output': load_file("v1_out_02.json"),
|
||||
"vault_name": "Acme Logins",
|
||||
"queries": ["9876543210", "Mock Website", "acme.com"],
|
||||
"expected": ["t0pS3cret", "t0pS3cret", "t0pS3cret"],
|
||||
"output": load_file("v1_out_02.json"),
|
||||
},
|
||||
{
|
||||
'vault_name': 'Acme Logins',
|
||||
'queries': [
|
||||
'864201357'
|
||||
],
|
||||
'expected': ['vauxhall'],
|
||||
'output': load_file("v1_out_03.json"),
|
||||
"vault_name": "Acme Logins",
|
||||
"queries": ["864201357"],
|
||||
"expected": ["vauxhall"],
|
||||
"output": load_file("v1_out_03.json"),
|
||||
},
|
||||
],
|
||||
OnePassCLIv2: [
|
||||
@@ -67,7 +58,7 @@ MOCK_ENTRIES = {
|
||||
"field": "password1",
|
||||
},
|
||||
"expected": ["data in custom field"],
|
||||
"output": load_file("v2_out_02.json")
|
||||
"output": load_file("v2_out_02.json"),
|
||||
},
|
||||
{
|
||||
# Request data from a custom section
|
||||
@@ -78,7 +69,7 @@ MOCK_ENTRIES = {
|
||||
"section": "Section 2",
|
||||
},
|
||||
"expected": ["first value"],
|
||||
"output": load_file("v2_out_03.json")
|
||||
"output": load_file("v2_out_03.json"),
|
||||
},
|
||||
{
|
||||
# Request data from an omitted value (label lookup, no section)
|
||||
@@ -88,7 +79,7 @@ MOCK_ENTRIES = {
|
||||
"field": "label-without-value",
|
||||
},
|
||||
"expected": [""],
|
||||
"output": load_file("v2_out_04.json")
|
||||
"output": load_file("v2_out_04.json"),
|
||||
},
|
||||
{
|
||||
# Request data from an omitted value (id lookup, no section)
|
||||
@@ -98,18 +89,15 @@ MOCK_ENTRIES = {
|
||||
"field": "67890q7mspf4x6zrlw3qejn7m",
|
||||
},
|
||||
"expected": [""],
|
||||
"output": load_file("v2_out_04.json")
|
||||
"output": load_file("v2_out_04.json"),
|
||||
},
|
||||
{
|
||||
# Request data from an omitted value (label lookup, with section)
|
||||
"vault_name": "Test Vault",
|
||||
"queries": ["Omitted values"],
|
||||
"kwargs": {
|
||||
"field": "section-label-without-value",
|
||||
"section": "Section-Without-Values"
|
||||
},
|
||||
"kwargs": {"field": "section-label-without-value", "section": "Section-Without-Values"},
|
||||
"expected": [""],
|
||||
"output": load_file("v2_out_04.json")
|
||||
"output": load_file("v2_out_04.json"),
|
||||
},
|
||||
{
|
||||
# Request data from an omitted value (id lookup, with section)
|
||||
@@ -120,7 +108,7 @@ MOCK_ENTRIES = {
|
||||
"section": "section-without-values",
|
||||
},
|
||||
"expected": [""],
|
||||
"output": load_file("v2_out_04.json")
|
||||
"output": load_file("v2_out_04.json"),
|
||||
},
|
||||
{
|
||||
# Query item without section by lowercase id (case matching)
|
||||
@@ -130,7 +118,7 @@ MOCK_ENTRIES = {
|
||||
"field": "lowercaseid",
|
||||
},
|
||||
"expected": ["lowercaseid"],
|
||||
"output": load_file("v2_out_05.json")
|
||||
"output": load_file("v2_out_05.json"),
|
||||
},
|
||||
{
|
||||
# Query item without section by lowercase id (case not matching)
|
||||
@@ -140,7 +128,7 @@ MOCK_ENTRIES = {
|
||||
"field": "LOWERCASEID",
|
||||
},
|
||||
"expected": ["lowercaseid"],
|
||||
"output": load_file("v2_out_05.json")
|
||||
"output": load_file("v2_out_05.json"),
|
||||
},
|
||||
{
|
||||
# Query item without section by lowercase label (case matching)
|
||||
@@ -150,7 +138,7 @@ MOCK_ENTRIES = {
|
||||
"field": "lowercaselabel",
|
||||
},
|
||||
"expected": ["lowercaselabel"],
|
||||
"output": load_file("v2_out_05.json")
|
||||
"output": load_file("v2_out_05.json"),
|
||||
},
|
||||
{
|
||||
# Query item without section by lowercase label (case not matching)
|
||||
@@ -160,7 +148,7 @@ MOCK_ENTRIES = {
|
||||
"field": "LOWERCASELABEL",
|
||||
},
|
||||
"expected": ["lowercaselabel"],
|
||||
"output": load_file("v2_out_05.json")
|
||||
"output": load_file("v2_out_05.json"),
|
||||
},
|
||||
{
|
||||
# Query item without section by mixed case id (case matching)
|
||||
@@ -170,7 +158,7 @@ MOCK_ENTRIES = {
|
||||
"field": "MiXeDcAsEiD",
|
||||
},
|
||||
"expected": ["mixedcaseid"],
|
||||
"output": load_file("v2_out_05.json")
|
||||
"output": load_file("v2_out_05.json"),
|
||||
},
|
||||
{
|
||||
# Query item without section by mixed case id (case not matching)
|
||||
@@ -180,7 +168,7 @@ MOCK_ENTRIES = {
|
||||
"field": "mixedcaseid",
|
||||
},
|
||||
"expected": ["mixedcaseid"],
|
||||
"output": load_file("v2_out_05.json")
|
||||
"output": load_file("v2_out_05.json"),
|
||||
},
|
||||
{
|
||||
# Query item without section by mixed case label (case matching)
|
||||
@@ -190,7 +178,7 @@ MOCK_ENTRIES = {
|
||||
"field": "MiXeDcAsElAbEl",
|
||||
},
|
||||
"expected": ["mixedcaselabel"],
|
||||
"output": load_file("v2_out_05.json")
|
||||
"output": load_file("v2_out_05.json"),
|
||||
},
|
||||
{
|
||||
# Query item without section by mixed case label (case not matching)
|
||||
@@ -200,7 +188,7 @@ MOCK_ENTRIES = {
|
||||
"field": "mixedcaselabel",
|
||||
},
|
||||
"expected": ["mixedcaselabel"],
|
||||
"output": load_file("v2_out_05.json")
|
||||
"output": load_file("v2_out_05.json"),
|
||||
},
|
||||
{
|
||||
# Query item with section by lowercase id (case matching)
|
||||
@@ -211,7 +199,7 @@ MOCK_ENTRIES = {
|
||||
"section": "section-with-values",
|
||||
},
|
||||
"expected": ["sectionlowercaseid"],
|
||||
"output": load_file("v2_out_05.json")
|
||||
"output": load_file("v2_out_05.json"),
|
||||
},
|
||||
{
|
||||
# Query item with section by lowercase id (case not matching)
|
||||
@@ -222,7 +210,7 @@ MOCK_ENTRIES = {
|
||||
"section": "section-with-values",
|
||||
},
|
||||
"expected": ["sectionlowercaseid"],
|
||||
"output": load_file("v2_out_05.json")
|
||||
"output": load_file("v2_out_05.json"),
|
||||
},
|
||||
{
|
||||
# Query item with section by lowercase label (case matching)
|
||||
@@ -233,7 +221,7 @@ MOCK_ENTRIES = {
|
||||
"section": "section-with-values",
|
||||
},
|
||||
"expected": ["sectionlowercaselabel"],
|
||||
"output": load_file("v2_out_05.json")
|
||||
"output": load_file("v2_out_05.json"),
|
||||
},
|
||||
{
|
||||
# Query item with section by lowercase label (case not matching)
|
||||
@@ -244,7 +232,7 @@ MOCK_ENTRIES = {
|
||||
"section": "section-with-values",
|
||||
},
|
||||
"expected": ["sectionlowercaselabel"],
|
||||
"output": load_file("v2_out_05.json")
|
||||
"output": load_file("v2_out_05.json"),
|
||||
},
|
||||
{
|
||||
# Query item with section by lowercase id (case matching)
|
||||
@@ -255,7 +243,7 @@ MOCK_ENTRIES = {
|
||||
"section": "section-with-values",
|
||||
},
|
||||
"expected": ["sectionmixedcaseid"],
|
||||
"output": load_file("v2_out_05.json")
|
||||
"output": load_file("v2_out_05.json"),
|
||||
},
|
||||
{
|
||||
# Query item with section by lowercase id (case not matching)
|
||||
@@ -266,7 +254,7 @@ MOCK_ENTRIES = {
|
||||
"section": "section-with-values",
|
||||
},
|
||||
"expected": ["sectionmixedcaseid"],
|
||||
"output": load_file("v2_out_05.json")
|
||||
"output": load_file("v2_out_05.json"),
|
||||
},
|
||||
{
|
||||
# Query item with section by lowercase label (case matching)
|
||||
@@ -277,7 +265,7 @@ MOCK_ENTRIES = {
|
||||
"section": "section-with-values",
|
||||
},
|
||||
"expected": ["sectionmixedcaselabel"],
|
||||
"output": load_file("v2_out_05.json")
|
||||
"output": load_file("v2_out_05.json"),
|
||||
},
|
||||
{
|
||||
# Query item with section by lowercase label (case not matching)
|
||||
@@ -288,7 +276,7 @@ MOCK_ENTRIES = {
|
||||
"section": "section-with-values",
|
||||
},
|
||||
"expected": ["sectionmixedcaselabel"],
|
||||
"output": load_file("v2_out_05.json")
|
||||
"output": load_file("v2_out_05.json"),
|
||||
},
|
||||
],
|
||||
}
|
||||
@@ -298,9 +286,7 @@ SSH_KEY_MOCK_ENTRIES = [
|
||||
{
|
||||
"vault_name": "Personal",
|
||||
"queries": ["ssh key"],
|
||||
"expected": [
|
||||
"-----BEGIN PRIVATE KEY-----\n..........=\n-----END PRIVATE KEY-----\n"
|
||||
],
|
||||
"expected": ["-----BEGIN PRIVATE KEY-----\n..........=\n-----END PRIVATE KEY-----\n"],
|
||||
"output": load_file("ssh_key_output.json"),
|
||||
},
|
||||
# loads private key in PKCS#8 format becasue ssh_format=false
|
||||
@@ -310,9 +296,7 @@ SSH_KEY_MOCK_ENTRIES = [
|
||||
"kwargs": {
|
||||
"ssh_format": False,
|
||||
},
|
||||
"expected": [
|
||||
"-----BEGIN PRIVATE KEY-----\n..........=\n-----END PRIVATE KEY-----\n"
|
||||
],
|
||||
"expected": ["-----BEGIN PRIVATE KEY-----\n..........=\n-----END PRIVATE KEY-----\n"],
|
||||
"output": load_file("ssh_key_output.json"),
|
||||
},
|
||||
# loads private key in ssh format
|
||||
@@ -322,9 +306,7 @@ SSH_KEY_MOCK_ENTRIES = [
|
||||
"kwargs": {
|
||||
"ssh_format": True,
|
||||
},
|
||||
"expected": [
|
||||
"-----BEGIN OPENSSH PRIVATE KEY-----\r\n.....\r\n-----END OPENSSH PRIVATE KEY-----\r\n"
|
||||
],
|
||||
"expected": ["-----BEGIN OPENSSH PRIVATE KEY-----\r\n.....\r\n-----END OPENSSH PRIVATE KEY-----\r\n"],
|
||||
"output": load_file("ssh_key_output.json"),
|
||||
},
|
||||
]
|
||||
|
||||
@@ -18,24 +18,12 @@ MOCK_ORGANIZATION_ID = "292ba0c6-f289-11ee-9301-ef7b639ccd2a"
|
||||
|
||||
MOCK_RECORDS = [
|
||||
{
|
||||
"collectionIds": [
|
||||
MOCK_COLLECTION_ID
|
||||
],
|
||||
"collectionIds": [MOCK_COLLECTION_ID],
|
||||
"deletedDate": None,
|
||||
"favorite": False,
|
||||
"fields": [
|
||||
{
|
||||
"linkedId": None,
|
||||
"name": "a_new_secret",
|
||||
"type": 1,
|
||||
"value": "this is a new secret"
|
||||
},
|
||||
{
|
||||
"linkedId": None,
|
||||
"name": "not so secret",
|
||||
"type": 0,
|
||||
"value": "not secret"
|
||||
}
|
||||
{"linkedId": None, "name": "a_new_secret", "type": 1, "value": "this is a new secret"},
|
||||
{"linkedId": None, "name": "not so secret", "type": 0, "value": "not secret"},
|
||||
],
|
||||
"folderId": "3b12a9da-7c49-40b8-ad33-aede017a7ead",
|
||||
"id": "90992f63-ddb6-4e76-8bfc-aede016ca5eb",
|
||||
@@ -43,29 +31,20 @@ MOCK_RECORDS = [
|
||||
"password": "passwordA3",
|
||||
"passwordRevisionDate": "2022-07-26T23:03:23.399Z",
|
||||
"totp": None,
|
||||
"username": "userA"
|
||||
"username": "userA",
|
||||
},
|
||||
"name": "a_test",
|
||||
"notes": None,
|
||||
"object": "item",
|
||||
"organizationId": MOCK_ORGANIZATION_ID,
|
||||
"passwordHistory": [
|
||||
{
|
||||
"lastUsedDate": "2022-07-26T23:03:23.405Z",
|
||||
"password": "a_new_secret: this is secret"
|
||||
},
|
||||
{
|
||||
"lastUsedDate": "2022-07-26T23:03:23.399Z",
|
||||
"password": "passwordA2"
|
||||
},
|
||||
{
|
||||
"lastUsedDate": "2022-07-26T22:59:52.885Z",
|
||||
"password": "passwordA"
|
||||
}
|
||||
{"lastUsedDate": "2022-07-26T23:03:23.405Z", "password": "a_new_secret: this is secret"},
|
||||
{"lastUsedDate": "2022-07-26T23:03:23.399Z", "password": "passwordA2"},
|
||||
{"lastUsedDate": "2022-07-26T22:59:52.885Z", "password": "passwordA"},
|
||||
],
|
||||
"reprompt": 0,
|
||||
"revisionDate": "2022-07-26T23:03:23.743Z",
|
||||
"type": 1
|
||||
"type": 1,
|
||||
},
|
||||
{
|
||||
"collectionIds": [],
|
||||
@@ -73,41 +52,29 @@ MOCK_RECORDS = [
|
||||
"favorite": False,
|
||||
"folderId": None,
|
||||
"id": "5ebd4d31-104c-49fc-a09c-aedf003d28ad",
|
||||
"login": {
|
||||
"password": "b",
|
||||
"passwordRevisionDate": None,
|
||||
"totp": None,
|
||||
"username": "a"
|
||||
},
|
||||
"login": {"password": "b", "passwordRevisionDate": None, "totp": None, "username": "a"},
|
||||
"name": "dupe_name",
|
||||
"notes": None,
|
||||
"object": "item",
|
||||
"organizationId": None,
|
||||
"reprompt": 0,
|
||||
"revisionDate": "2022-07-27T03:42:40.353Z",
|
||||
"type": 1
|
||||
"type": 1,
|
||||
},
|
||||
{
|
||||
"collectionIds": [
|
||||
MOCK_COLLECTION_ID
|
||||
],
|
||||
"collectionIds": [MOCK_COLLECTION_ID],
|
||||
"deletedDate": None,
|
||||
"favorite": False,
|
||||
"folderId": None,
|
||||
"id": "90657653-6695-496d-9431-aedf003d3015",
|
||||
"login": {
|
||||
"password": "d",
|
||||
"passwordRevisionDate": None,
|
||||
"totp": None,
|
||||
"username": "c"
|
||||
},
|
||||
"login": {"password": "d", "passwordRevisionDate": None, "totp": None, "username": "c"},
|
||||
"name": "dupe_name",
|
||||
"notes": None,
|
||||
"object": "item",
|
||||
"organizationId": MOCK_ORGANIZATION_ID,
|
||||
"reprompt": 0,
|
||||
"revisionDate": "2022-07-27T03:42:46.673Z",
|
||||
"type": 1
|
||||
"type": 1,
|
||||
},
|
||||
{
|
||||
"collectionIds": [],
|
||||
@@ -115,153 +82,142 @@ MOCK_RECORDS = [
|
||||
"favorite": False,
|
||||
"folderId": None,
|
||||
"id": "2bf517be-fb13-11ee-be89-a345aa369a94",
|
||||
"login": {
|
||||
"password": "e",
|
||||
"passwordRevisionDate": None,
|
||||
"totp": None,
|
||||
"username": "f"
|
||||
},
|
||||
"login": {"password": "e", "passwordRevisionDate": None, "totp": None, "username": "f"},
|
||||
"name": "non_collection_org_record",
|
||||
"notes": None,
|
||||
"object": "item",
|
||||
"organizationId": MOCK_ORGANIZATION_ID,
|
||||
"reprompt": 0,
|
||||
"revisionDate": "2024-14-15T11:30:00.000Z",
|
||||
"type": 1
|
||||
"type": 1,
|
||||
},
|
||||
{
|
||||
"object": "collection",
|
||||
"id": MOCK_COLLECTION_ID,
|
||||
"organizationId": MOCK_ORGANIZATION_ID,
|
||||
"name": "MOCK_COLLECTION",
|
||||
"externalId": None
|
||||
"externalId": None,
|
||||
},
|
||||
{
|
||||
"object": "collection",
|
||||
"id": "3b12a9da-7c49-40b8-ad33-aede017a8ead",
|
||||
"organizationId": "3b12a9da-7c49-40b8-ad33-aede017a9ead",
|
||||
"name": "some/other/collection",
|
||||
"externalId": None
|
||||
"externalId": None,
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
class MockBitwarden(Bitwarden):
|
||||
|
||||
unlocked = True
|
||||
|
||||
def _run(self, args, stdin=None, expected_rc=0):
|
||||
if args[0] == 'get':
|
||||
if args[1] == 'item':
|
||||
if args[0] == "get":
|
||||
if args[1] == "item":
|
||||
for item in MOCK_RECORDS:
|
||||
if item.get('id') == args[2]:
|
||||
return AnsibleJSONEncoder().encode(item), ''
|
||||
if args[0] == 'list':
|
||||
if args[1] == 'items':
|
||||
if item.get("id") == args[2]:
|
||||
return AnsibleJSONEncoder().encode(item), ""
|
||||
if args[0] == "list":
|
||||
if args[1] == "items":
|
||||
try:
|
||||
search_value = args[args.index('--search') + 1]
|
||||
search_value = args[args.index("--search") + 1]
|
||||
except ValueError:
|
||||
search_value = None
|
||||
|
||||
try:
|
||||
collection_to_filter = args[args.index('--collectionid') + 1]
|
||||
collection_to_filter = args[args.index("--collectionid") + 1]
|
||||
except ValueError:
|
||||
collection_to_filter = None
|
||||
|
||||
try:
|
||||
organization_to_filter = args[args.index('--organizationid') + 1]
|
||||
organization_to_filter = args[args.index("--organizationid") + 1]
|
||||
except ValueError:
|
||||
organization_to_filter = None
|
||||
|
||||
items = []
|
||||
for item in MOCK_RECORDS:
|
||||
if item.get('object') != 'item':
|
||||
if item.get("object") != "item":
|
||||
continue
|
||||
|
||||
if search_value and not re.search(search_value, item.get('name')):
|
||||
if search_value and not re.search(search_value, item.get("name")):
|
||||
continue
|
||||
if collection_to_filter and collection_to_filter not in item.get('collectionIds', []):
|
||||
if collection_to_filter and collection_to_filter not in item.get("collectionIds", []):
|
||||
continue
|
||||
if organization_to_filter and item.get('organizationId') != organization_to_filter:
|
||||
if organization_to_filter and item.get("organizationId") != organization_to_filter:
|
||||
continue
|
||||
items.append(item)
|
||||
return AnsibleJSONEncoder().encode(items), ''
|
||||
elif args[1] == 'collections':
|
||||
return AnsibleJSONEncoder().encode(items), ""
|
||||
elif args[1] == "collections":
|
||||
try:
|
||||
search_value = args[args.index('--search') + 1]
|
||||
search_value = args[args.index("--search") + 1]
|
||||
except ValueError:
|
||||
search_value = None
|
||||
|
||||
try:
|
||||
collection_to_filter = args[args.index('--collectionid') + 1]
|
||||
collection_to_filter = args[args.index("--collectionid") + 1]
|
||||
except ValueError:
|
||||
collection_to_filter = None
|
||||
|
||||
try:
|
||||
organization_to_filter = args[args.index('--organizationid') + 1]
|
||||
organization_to_filter = args[args.index("--organizationid") + 1]
|
||||
except ValueError:
|
||||
organization_to_filter = None
|
||||
|
||||
collections = []
|
||||
for item in MOCK_RECORDS:
|
||||
if item.get('object') != 'collection':
|
||||
if item.get("object") != "collection":
|
||||
continue
|
||||
|
||||
if search_value and not re.search(search_value, item.get('name')):
|
||||
if search_value and not re.search(search_value, item.get("name")):
|
||||
continue
|
||||
if collection_to_filter and collection_to_filter not in item.get('collectionIds', []):
|
||||
if collection_to_filter and collection_to_filter not in item.get("collectionIds", []):
|
||||
continue
|
||||
if organization_to_filter and item.get('organizationId') != organization_to_filter:
|
||||
if organization_to_filter and item.get("organizationId") != organization_to_filter:
|
||||
continue
|
||||
collections.append(item)
|
||||
return AnsibleJSONEncoder().encode(collections), ''
|
||||
return AnsibleJSONEncoder().encode(collections), ""
|
||||
|
||||
return '[]', ''
|
||||
return "[]", ""
|
||||
|
||||
|
||||
class LoggedOutMockBitwarden(MockBitwarden):
|
||||
|
||||
unlocked = False
|
||||
|
||||
|
||||
class TestLookupModule(unittest.TestCase):
|
||||
|
||||
def setUp(self):
|
||||
self.lookup = lookup_loader.get('community.general.bitwarden')
|
||||
self.lookup = lookup_loader.get("community.general.bitwarden")
|
||||
|
||||
@patch('ansible_collections.community.general.plugins.lookup.bitwarden._bitwarden', new=MockBitwarden())
|
||||
@patch("ansible_collections.community.general.plugins.lookup.bitwarden._bitwarden", new=MockBitwarden())
|
||||
def test_bitwarden_plugin_no_match(self):
|
||||
# Entry 0, "a_test" of the test input should have no duplicates.
|
||||
self.assertEqual([], self.lookup.run(['not_here'], field='password')[0])
|
||||
self.assertEqual([], self.lookup.run(["not_here"], field="password")[0])
|
||||
|
||||
@patch('ansible_collections.community.general.plugins.lookup.bitwarden._bitwarden', new=MockBitwarden())
|
||||
@patch("ansible_collections.community.general.plugins.lookup.bitwarden._bitwarden", new=MockBitwarden())
|
||||
def test_bitwarden_plugin_fields(self):
|
||||
# Entry 0, "a_test" of the test input should have no duplicates.
|
||||
record = MOCK_RECORDS[0]
|
||||
record_name = record['name']
|
||||
for k, v in record['login'].items():
|
||||
self.assertEqual([v],
|
||||
self.lookup.run([record_name], field=k)[0])
|
||||
record_name = record["name"]
|
||||
for k, v in record["login"].items():
|
||||
self.assertEqual([v], self.lookup.run([record_name], field=k)[0])
|
||||
|
||||
@patch('ansible_collections.community.general.plugins.lookup.bitwarden._bitwarden', new=MockBitwarden())
|
||||
@patch("ansible_collections.community.general.plugins.lookup.bitwarden._bitwarden", new=MockBitwarden())
|
||||
def test_bitwarden_plugin_duplicates(self):
|
||||
# There are two records with name dupe_name; we need to be order-insensitive with
|
||||
# checking what was retrieved.
|
||||
self.assertEqual(set(['b', 'd']),
|
||||
set(self.lookup.run(['dupe_name'], field='password')[0]))
|
||||
self.assertEqual(set(["b", "d"]), set(self.lookup.run(["dupe_name"], field="password")[0]))
|
||||
|
||||
@patch('ansible_collections.community.general.plugins.lookup.bitwarden._bitwarden', new=MockBitwarden())
|
||||
@patch("ansible_collections.community.general.plugins.lookup.bitwarden._bitwarden", new=MockBitwarden())
|
||||
def test_bitwarden_plugin_full_item(self):
|
||||
# Try to retrieve the full record of the first entry where the name is "a_name".
|
||||
self.assertEqual([MOCK_RECORDS[0]],
|
||||
self.lookup.run(['a_test'])[0])
|
||||
self.assertEqual([MOCK_RECORDS[0]], self.lookup.run(["a_test"])[0])
|
||||
|
||||
@patch('ansible_collections.community.general.plugins.lookup.bitwarden._bitwarden', LoggedOutMockBitwarden())
|
||||
@patch("ansible_collections.community.general.plugins.lookup.bitwarden._bitwarden", LoggedOutMockBitwarden())
|
||||
def test_bitwarden_plugin_unlocked(self):
|
||||
record = MOCK_RECORDS[0]
|
||||
record_name = record['name']
|
||||
record_name = record["name"]
|
||||
with self.assertRaises(AnsibleError) as raised_error:
|
||||
self.lookup.run([record_name], field='password')
|
||||
self.lookup.run([record_name], field="password")
|
||||
|
||||
self.assertEqual("Bitwarden Vault locked. Run 'bw unlock'.", str(raised_error.exception))
|
||||
|
||||
@@ -269,8 +225,8 @@ class TestLookupModule(unittest.TestCase):
|
||||
mock_bitwarden = MockBitwarden()
|
||||
with patch("ansible_collections.community.general.plugins.lookup.bitwarden._bitwarden", mock_bitwarden):
|
||||
record = MOCK_RECORDS[0]
|
||||
record_name = record['name']
|
||||
session = 'session'
|
||||
record_name = record["name"]
|
||||
session = "session"
|
||||
|
||||
self.lookup.run([record_name], field=None)
|
||||
self.assertIsNone(mock_bitwarden.session)
|
||||
@@ -279,37 +235,41 @@ class TestLookupModule(unittest.TestCase):
|
||||
mock_bitwarden = MockBitwarden()
|
||||
with patch("ansible_collections.community.general.plugins.lookup.bitwarden._bitwarden", mock_bitwarden):
|
||||
record = MOCK_RECORDS[0]
|
||||
record_name = record['name']
|
||||
session = 'session'
|
||||
record_name = record["name"]
|
||||
session = "session"
|
||||
|
||||
self.lookup.run([record_name], field=None, bw_session=session)
|
||||
self.assertEqual(mock_bitwarden.session, session)
|
||||
|
||||
@patch('ansible_collections.community.general.plugins.lookup.bitwarden._bitwarden', new=MockBitwarden())
|
||||
@patch("ansible_collections.community.general.plugins.lookup.bitwarden._bitwarden", new=MockBitwarden())
|
||||
def test_bitwarden_plugin_full_collection(self):
|
||||
# Try to retrieve the full records of the given collection.
|
||||
self.assertEqual([MOCK_RECORDS[0], MOCK_RECORDS[2]], self.lookup.run(None, collection_id=MOCK_COLLECTION_ID)[0])
|
||||
|
||||
@patch('ansible_collections.community.general.plugins.lookup.bitwarden._bitwarden', new=MockBitwarden())
|
||||
@patch("ansible_collections.community.general.plugins.lookup.bitwarden._bitwarden", new=MockBitwarden())
|
||||
def test_bitwarden_plugin_full_organization(self):
|
||||
self.assertEqual([MOCK_RECORDS[0], MOCK_RECORDS[2], MOCK_RECORDS[3]],
|
||||
self.lookup.run(None, organization_id=MOCK_ORGANIZATION_ID)[0])
|
||||
self.assertEqual(
|
||||
[MOCK_RECORDS[0], MOCK_RECORDS[2], MOCK_RECORDS[3]],
|
||||
self.lookup.run(None, organization_id=MOCK_ORGANIZATION_ID)[0],
|
||||
)
|
||||
|
||||
@patch('ansible_collections.community.general.plugins.lookup.bitwarden._bitwarden', new=MockBitwarden())
|
||||
@patch("ansible_collections.community.general.plugins.lookup.bitwarden._bitwarden", new=MockBitwarden())
|
||||
def test_bitwarden_plugin_filter_organization(self):
|
||||
self.assertEqual([MOCK_RECORDS[2]],
|
||||
self.lookup.run(['dupe_name'], organization_id=MOCK_ORGANIZATION_ID)[0])
|
||||
self.assertEqual([MOCK_RECORDS[2]], self.lookup.run(["dupe_name"], organization_id=MOCK_ORGANIZATION_ID)[0])
|
||||
|
||||
@patch('ansible_collections.community.general.plugins.lookup.bitwarden._bitwarden', new=MockBitwarden())
|
||||
@patch("ansible_collections.community.general.plugins.lookup.bitwarden._bitwarden", new=MockBitwarden())
|
||||
def test_bitwarden_plugin_full_collection_organization(self):
|
||||
self.assertEqual([MOCK_RECORDS[0], MOCK_RECORDS[2]], self.lookup.run(None,
|
||||
collection_id=MOCK_COLLECTION_ID, organization_id=MOCK_ORGANIZATION_ID)[0])
|
||||
self.assertEqual(
|
||||
[MOCK_RECORDS[0], MOCK_RECORDS[2]],
|
||||
self.lookup.run(None, collection_id=MOCK_COLLECTION_ID, organization_id=MOCK_ORGANIZATION_ID)[0],
|
||||
)
|
||||
|
||||
@patch('ansible_collections.community.general.plugins.lookup.bitwarden._bitwarden', new=MockBitwarden())
|
||||
@patch("ansible_collections.community.general.plugins.lookup.bitwarden._bitwarden", new=MockBitwarden())
|
||||
def test_bitwarden_plugin_collection_name_filter(self):
|
||||
# all passwords from MOCK_COLLECTION
|
||||
self.assertEqual([MOCK_RECORDS[0], MOCK_RECORDS[2]], self.lookup.run(None,
|
||||
collection_name="MOCK_COLLECTION")[0])
|
||||
self.assertEqual(
|
||||
[MOCK_RECORDS[0], MOCK_RECORDS[2]], self.lookup.run(None, collection_name="MOCK_COLLECTION")[0]
|
||||
)
|
||||
# Existing collection, no results
|
||||
self.assertEqual([], self.lookup.run(None, collection_name="some/other/collection")[0])
|
||||
|
||||
@@ -317,12 +277,13 @@ class TestLookupModule(unittest.TestCase):
|
||||
with self.assertRaises(BitwardenException):
|
||||
self.lookup.run(None, collection_name="nonexistent")
|
||||
|
||||
@patch('ansible_collections.community.general.plugins.lookup.bitwarden._bitwarden', new=MockBitwarden())
|
||||
@patch("ansible_collections.community.general.plugins.lookup.bitwarden._bitwarden", new=MockBitwarden())
|
||||
def test_bitwarden_plugin_result_count_check(self):
|
||||
self.lookup.run(None, collection_id=MOCK_COLLECTION_ID, organization_id=MOCK_ORGANIZATION_ID, result_count=2)
|
||||
with self.assertRaises(BitwardenException):
|
||||
self.lookup.run(None, collection_id=MOCK_COLLECTION_ID, organization_id=MOCK_ORGANIZATION_ID,
|
||||
result_count=1)
|
||||
self.lookup.run(
|
||||
None, collection_id=MOCK_COLLECTION_ID, organization_id=MOCK_ORGANIZATION_ID, result_count=1
|
||||
)
|
||||
|
||||
self.lookup.run(None, organization_id=MOCK_ORGANIZATION_ID, result_count=3)
|
||||
with self.assertRaises(BitwardenException):
|
||||
|
||||
@@ -23,7 +23,7 @@ MOCK_SECRETS = [
|
||||
"value": "1234supersecret5678",
|
||||
"note": "A test secret to use when developing the ansible bitwarden_secrets_manager lookup plugin",
|
||||
"creationDate": "2023-04-23T13:13:37.7507017Z",
|
||||
"revisionDate": "2023-04-23T13:13:37.7507017Z"
|
||||
"revisionDate": "2023-04-23T13:13:37.7507017Z",
|
||||
},
|
||||
{
|
||||
"object": "secret",
|
||||
@@ -34,13 +34,12 @@ MOCK_SECRETS = [
|
||||
"value": "abcd_such_secret_very_important_efgh",
|
||||
"note": "notes go here",
|
||||
"creationDate": "2023-04-23T13:26:44.0392906Z",
|
||||
"revisionDate": "2023-04-23T13:26:44.0392906Z"
|
||||
}
|
||||
"revisionDate": "2023-04-23T13:26:44.0392906Z",
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
class MockBitwardenSecretsManager(BitwardenSecretsManager):
|
||||
|
||||
def _run(self, args, stdin=None):
|
||||
# mock the --version call
|
||||
if args[0] == "--version":
|
||||
@@ -68,17 +67,24 @@ class MockBitwardenSecretsManager(BitwardenSecretsManager):
|
||||
|
||||
|
||||
class TestLookupModule(unittest.TestCase):
|
||||
|
||||
def setUp(self):
|
||||
self.lookup = lookup_loader.get('community.general.bitwarden_secrets_manager')
|
||||
self.lookup = lookup_loader.get("community.general.bitwarden_secrets_manager")
|
||||
|
||||
@patch('ansible_collections.community.general.plugins.lookup.bitwarden_secrets_manager._bitwarden_secrets_manager', new=MockBitwardenSecretsManager())
|
||||
@patch(
|
||||
"ansible_collections.community.general.plugins.lookup.bitwarden_secrets_manager._bitwarden_secrets_manager",
|
||||
new=MockBitwardenSecretsManager(),
|
||||
)
|
||||
def test_bitwarden_secrets_manager(self):
|
||||
# Getting a secret by its id should return the full secret info
|
||||
self.assertEqual([MOCK_SECRETS[0]], self.lookup.run(['ababc4a8-c242-4e54-bceb-77d17cdf2e07'], bws_access_token='123'))
|
||||
self.assertEqual(
|
||||
[MOCK_SECRETS[0]], self.lookup.run(["ababc4a8-c242-4e54-bceb-77d17cdf2e07"], bws_access_token="123")
|
||||
)
|
||||
|
||||
@patch('ansible_collections.community.general.plugins.lookup.bitwarden_secrets_manager._bitwarden_secrets_manager', new=MockBitwardenSecretsManager())
|
||||
@patch(
|
||||
"ansible_collections.community.general.plugins.lookup.bitwarden_secrets_manager._bitwarden_secrets_manager",
|
||||
new=MockBitwardenSecretsManager(),
|
||||
)
|
||||
def test_bitwarden_secrets_manager_no_match(self):
|
||||
# Getting a nonexistent secret id throws exception
|
||||
with self.assertRaises(AnsibleLookupError):
|
||||
self.lookup.run(['nonexistant_id'], bws_access_token='123')
|
||||
self.lookup.run(["nonexistant_id"], bws_access_token="123")
|
||||
|
||||
@@ -25,16 +25,16 @@ class TestLookupModule(TestCase):
|
||||
self.assertListEqual(
|
||||
self.lookup.run(
|
||||
[
|
||||
{'a': make_trusted('[1, 2]')},
|
||||
{'b': make_trusted('[item.a + 3, item.a + 6]')},
|
||||
{'c': make_trusted('[item.a + item.b * 10]')},
|
||||
{"a": make_trusted("[1, 2]")},
|
||||
{"b": make_trusted("[item.a + 3, item.a + 6]")},
|
||||
{"c": make_trusted("[item.a + item.b * 10]")},
|
||||
],
|
||||
{},
|
||||
),
|
||||
[
|
||||
{'a': 1, 'b': 4, 'c': 41},
|
||||
{'a': 1, 'b': 7, 'c': 71},
|
||||
{'a': 2, 'b': 5, 'c': 52},
|
||||
{'a': 2, 'b': 8, 'c': 82},
|
||||
{"a": 1, "b": 4, "c": 41},
|
||||
{"a": 1, "b": 7, "c": 71},
|
||||
{"a": 2, "b": 5, "c": 52},
|
||||
{"a": 2, "b": 8, "c": 82},
|
||||
],
|
||||
)
|
||||
|
||||
@@ -37,6 +37,10 @@ class TestLookupModule(TestCase):
|
||||
self.lookup.run(
|
||||
["/dummy"],
|
||||
[],
|
||||
**{"tenant": "dummy", "client_id": "dummy", "client_secret": "dummy", }
|
||||
**{
|
||||
"tenant": "dummy",
|
||||
"client_id": "dummy",
|
||||
"client_secret": "dummy",
|
||||
},
|
||||
),
|
||||
)
|
||||
|
||||
@@ -13,42 +13,39 @@ from ansible.plugins.loader import lookup_loader
|
||||
|
||||
|
||||
class FakeKVMetadata:
|
||||
|
||||
def __init__(self, keyvalue, header):
|
||||
self.key = keyvalue
|
||||
self.create_revision = ''
|
||||
self.mod_revision = ''
|
||||
self.version = ''
|
||||
self.lease_id = ''
|
||||
self.create_revision = ""
|
||||
self.mod_revision = ""
|
||||
self.version = ""
|
||||
self.lease_id = ""
|
||||
self.response_header = header
|
||||
|
||||
|
||||
class FakeEtcd3Client(MagicMock):
|
||||
|
||||
def get_prefix(self, key):
|
||||
for i in range(1, 4):
|
||||
yield self.get(f'{key}_{i}')
|
||||
yield self.get(f"{key}_{i}")
|
||||
|
||||
def get(self, key):
|
||||
return (f"{key} value", FakeKVMetadata(key, None))
|
||||
|
||||
|
||||
class TestLookupModule(unittest.TestCase):
|
||||
|
||||
def setUp(self):
|
||||
etcd3.HAS_ETCD = True
|
||||
self.lookup = lookup_loader.get('community.general.etcd3')
|
||||
self.lookup = lookup_loader.get("community.general.etcd3")
|
||||
|
||||
@patch('ansible_collections.community.general.plugins.lookup.etcd3.etcd3_client', FakeEtcd3Client())
|
||||
@patch("ansible_collections.community.general.plugins.lookup.etcd3.etcd3_client", FakeEtcd3Client())
|
||||
def test_key(self):
|
||||
expected_result = [{'key': 'a_key', 'value': 'a_key value'}]
|
||||
self.assertListEqual(expected_result, self.lookup.run(['a_key'], []))
|
||||
expected_result = [{"key": "a_key", "value": "a_key value"}]
|
||||
self.assertListEqual(expected_result, self.lookup.run(["a_key"], []))
|
||||
|
||||
@patch('ansible_collections.community.general.plugins.lookup.etcd3.etcd3_client', FakeEtcd3Client())
|
||||
@patch("ansible_collections.community.general.plugins.lookup.etcd3.etcd3_client", FakeEtcd3Client())
|
||||
def test_key_prefix(self):
|
||||
expected_result = [
|
||||
{'key': 'a_key_1', 'value': 'a_key_1 value'},
|
||||
{'key': 'a_key_2', 'value': 'a_key_2 value'},
|
||||
{'key': 'a_key_3', 'value': 'a_key_3 value'},
|
||||
{"key": "a_key_1", "value": "a_key_1 value"},
|
||||
{"key": "a_key_2", "value": "a_key_2 value"},
|
||||
{"key": "a_key_3", "value": "a_key_3 value"},
|
||||
]
|
||||
self.assertListEqual(expected_result, self.lookup.run(['a_key'], [], **{'prefix': True}))
|
||||
self.assertListEqual(expected_result, self.lookup.run(["a_key"], [], **{"prefix": True}))
|
||||
|
||||
@@ -16,8 +16,8 @@ from unittest.mock import (
|
||||
|
||||
from ansible.plugins.loader import lookup_loader
|
||||
|
||||
ENCODE_RESULT = 'Foobar'
|
||||
PRIVATE_KEY = 'private_key'
|
||||
ENCODE_RESULT = "Foobar"
|
||||
PRIVATE_KEY = "private_key"
|
||||
|
||||
|
||||
class MockJWT(MagicMock):
|
||||
@@ -31,101 +31,97 @@ class serialization(MagicMock):
|
||||
|
||||
|
||||
class MockResponse(MagicMock):
|
||||
response_token = 'Bar'
|
||||
response_token = "Bar"
|
||||
|
||||
def read(self):
|
||||
return json.dumps({
|
||||
"token": self.response_token,
|
||||
}).encode('utf-8')
|
||||
return json.dumps(
|
||||
{
|
||||
"token": self.response_token,
|
||||
}
|
||||
).encode("utf-8")
|
||||
|
||||
|
||||
class TestLookupModule(unittest.TestCase):
|
||||
def test_get_token_with_file_with_pyjwt(self):
|
||||
pyjwt = types.ModuleType("jwt")
|
||||
pyjwt.encode = MagicMock(return_value=ENCODE_RESULT)
|
||||
with patch.dict(sys.modules, {'jwt': pyjwt}), \
|
||||
patch.multiple("ansible_collections.community.general.plugins.lookup.github_app_access_token",
|
||||
open=mock_open(read_data="foo_bar"),
|
||||
open_url=MagicMock(return_value=MockResponse()),
|
||||
HAS_JWT=True,
|
||||
HAS_CRYPTOGRAPHY=True,
|
||||
serialization=serialization()):
|
||||
|
||||
lookup = lookup_loader.get('community.general.github_app_access_token')
|
||||
with (
|
||||
patch.dict(sys.modules, {"jwt": pyjwt}),
|
||||
patch.multiple(
|
||||
"ansible_collections.community.general.plugins.lookup.github_app_access_token",
|
||||
open=mock_open(read_data="foo_bar"),
|
||||
open_url=MagicMock(return_value=MockResponse()),
|
||||
HAS_JWT=True,
|
||||
HAS_CRYPTOGRAPHY=True,
|
||||
serialization=serialization(),
|
||||
),
|
||||
):
|
||||
lookup = lookup_loader.get("community.general.github_app_access_token")
|
||||
self.assertListEqual(
|
||||
[MockResponse.response_token],
|
||||
lookup.run(
|
||||
[],
|
||||
key_path="key",
|
||||
app_id="app_id",
|
||||
installation_id="installation_id",
|
||||
token_expiry=600
|
||||
)
|
||||
lookup.run([], key_path="key", app_id="app_id", installation_id="installation_id", token_expiry=600),
|
||||
)
|
||||
|
||||
def test_get_token_with_fact_with_pyjwt(self):
|
||||
pyjwt = types.ModuleType("jwt")
|
||||
pyjwt.encode = MagicMock(return_value=ENCODE_RESULT)
|
||||
with patch.dict(sys.modules, {'jwt': pyjwt}), \
|
||||
patch.multiple("ansible_collections.community.general.plugins.lookup.github_app_access_token",
|
||||
open=mock_open(read_data="foo_bar"),
|
||||
open_url=MagicMock(return_value=MockResponse()),
|
||||
HAS_JWT=True,
|
||||
HAS_CRYPTOGRAPHY=True,
|
||||
serialization=serialization()):
|
||||
|
||||
lookup = lookup_loader.get('community.general.github_app_access_token')
|
||||
with (
|
||||
patch.dict(sys.modules, {"jwt": pyjwt}),
|
||||
patch.multiple(
|
||||
"ansible_collections.community.general.plugins.lookup.github_app_access_token",
|
||||
open=mock_open(read_data="foo_bar"),
|
||||
open_url=MagicMock(return_value=MockResponse()),
|
||||
HAS_JWT=True,
|
||||
HAS_CRYPTOGRAPHY=True,
|
||||
serialization=serialization(),
|
||||
),
|
||||
):
|
||||
lookup = lookup_loader.get("community.general.github_app_access_token")
|
||||
self.assertListEqual(
|
||||
[MockResponse.response_token],
|
||||
lookup.run(
|
||||
[],
|
||||
app_id="app_id",
|
||||
installation_id="installation_id",
|
||||
private_key="foo_bar",
|
||||
token_expiry=600
|
||||
)
|
||||
[], app_id="app_id", installation_id="installation_id", private_key="foo_bar", token_expiry=600
|
||||
),
|
||||
)
|
||||
|
||||
def test_get_token_with_python_jwt(self):
|
||||
python_jwt = types.ModuleType("jwt")
|
||||
python_jwt.JWT = MagicMock()
|
||||
python_jwt.jwk_from_pem = MagicMock(return_value='private_key')
|
||||
python_jwt.jwk_from_pem = MagicMock(return_value="private_key")
|
||||
python_jwt.jwt_instance = MockJWT()
|
||||
with patch.dict(sys.modules, {'jwt': python_jwt}), \
|
||||
patch.multiple("ansible_collections.community.general.plugins.lookup.github_app_access_token",
|
||||
open=mock_open(read_data="foo_bar"),
|
||||
open_url=MagicMock(return_value=MockResponse()),
|
||||
HAS_JWT=True):
|
||||
lookup = lookup_loader.get('community.general.github_app_access_token')
|
||||
with (
|
||||
patch.dict(sys.modules, {"jwt": python_jwt}),
|
||||
patch.multiple(
|
||||
"ansible_collections.community.general.plugins.lookup.github_app_access_token",
|
||||
open=mock_open(read_data="foo_bar"),
|
||||
open_url=MagicMock(return_value=MockResponse()),
|
||||
HAS_JWT=True,
|
||||
),
|
||||
):
|
||||
lookup = lookup_loader.get("community.general.github_app_access_token")
|
||||
self.assertListEqual(
|
||||
[MockResponse.response_token],
|
||||
lookup.run(
|
||||
[],
|
||||
key_path="key",
|
||||
app_id="app_id",
|
||||
installation_id="installation_id",
|
||||
token_expiry=600
|
||||
)
|
||||
lookup.run([], key_path="key", app_id="app_id", installation_id="installation_id", token_expiry=600),
|
||||
)
|
||||
|
||||
def test_get_token_with_fact_with_python_jwt(self):
|
||||
python_jwt = types.ModuleType("jwt")
|
||||
python_jwt.JWT = MagicMock()
|
||||
python_jwt.jwk_from_pem = MagicMock(return_value='private_key')
|
||||
python_jwt.jwk_from_pem = MagicMock(return_value="private_key")
|
||||
python_jwt.jwt_instance = MockJWT()
|
||||
with patch.dict(sys.modules, {'jwt': python_jwt}), \
|
||||
patch.multiple("ansible_collections.community.general.plugins.lookup.github_app_access_token",
|
||||
open=mock_open(read_data="foo_bar"),
|
||||
open_url=MagicMock(return_value=MockResponse()),
|
||||
HAS_JWT=True):
|
||||
lookup = lookup_loader.get('community.general.github_app_access_token')
|
||||
with (
|
||||
patch.dict(sys.modules, {"jwt": python_jwt}),
|
||||
patch.multiple(
|
||||
"ansible_collections.community.general.plugins.lookup.github_app_access_token",
|
||||
open=mock_open(read_data="foo_bar"),
|
||||
open_url=MagicMock(return_value=MockResponse()),
|
||||
HAS_JWT=True,
|
||||
),
|
||||
):
|
||||
lookup = lookup_loader.get("community.general.github_app_access_token")
|
||||
self.assertListEqual(
|
||||
[MockResponse.response_token],
|
||||
lookup.run(
|
||||
[],
|
||||
app_id="app_id",
|
||||
installation_id="installation_id",
|
||||
private_key="foo_bar",
|
||||
token_expiry=600
|
||||
)
|
||||
[], app_id="app_id", installation_id="installation_id", private_key="foo_bar", token_expiry=600
|
||||
),
|
||||
)
|
||||
|
||||
@@ -14,112 +14,114 @@ from ansible.plugins.loader import lookup_loader
|
||||
from ansible_collections.community.general.plugins.lookup.lastpass import LPass, LPassException
|
||||
|
||||
|
||||
MOCK_ENTRIES = [{'username': 'user',
|
||||
'name': 'Mock Entry',
|
||||
'password': 't0pS3cret passphrase entry!',
|
||||
'url': 'https://localhost/login',
|
||||
'notes': 'Test\nnote with multiple lines.\n',
|
||||
'id': '0123456789'}]
|
||||
MOCK_ENTRIES = [
|
||||
{
|
||||
"username": "user",
|
||||
"name": "Mock Entry",
|
||||
"password": "t0pS3cret passphrase entry!",
|
||||
"url": "https://localhost/login",
|
||||
"notes": "Test\nnote with multiple lines.\n",
|
||||
"id": "0123456789",
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
class MockLPass(LPass):
|
||||
|
||||
_mock_logged_out = False
|
||||
_mock_disconnected = False
|
||||
|
||||
def _lookup_mock_entry(self, key):
|
||||
for entry in MOCK_ENTRIES:
|
||||
if key == entry['id'] or key == entry['name']:
|
||||
if key == entry["id"] or key == entry["name"]:
|
||||
return entry
|
||||
|
||||
def _run(self, args, stdin=None, expected_rc=0):
|
||||
# Mock behavior of lpass executable
|
||||
base_options = ArgumentParser(add_help=False)
|
||||
base_options.add_argument('--color', default="auto", choices=['auto', 'always', 'never'])
|
||||
base_options.add_argument("--color", default="auto", choices=["auto", "always", "never"])
|
||||
|
||||
p = ArgumentParser()
|
||||
sp = p.add_subparsers(help='command', dest='subparser_name')
|
||||
sp = p.add_subparsers(help="command", dest="subparser_name")
|
||||
|
||||
logout_p = sp.add_parser('logout', parents=[base_options], help='logout')
|
||||
show_p = sp.add_parser('show', parents=[base_options], help='show entry details')
|
||||
logout_p = sp.add_parser("logout", parents=[base_options], help="logout")
|
||||
show_p = sp.add_parser("show", parents=[base_options], help="show entry details")
|
||||
|
||||
field_group = show_p.add_mutually_exclusive_group(required=True)
|
||||
for field in MOCK_ENTRIES[0].keys():
|
||||
field_group.add_argument(f"--{field}", default=False, action='store_true')
|
||||
field_group.add_argument('--field', default=None)
|
||||
show_p.add_argument('selector', help='Unique Name or ID')
|
||||
field_group.add_argument(f"--{field}", default=False, action="store_true")
|
||||
field_group.add_argument("--field", default=None)
|
||||
show_p.add_argument("selector", help="Unique Name or ID")
|
||||
|
||||
args = p.parse_args(args)
|
||||
|
||||
def mock_exit(output='', error='', rc=0):
|
||||
def mock_exit(output="", error="", rc=0):
|
||||
if rc != expected_rc:
|
||||
raise LPassException(error)
|
||||
return output, error
|
||||
|
||||
if args.color != 'never':
|
||||
return mock_exit(error='Error: Mock only supports --color=never', rc=1)
|
||||
if args.color != "never":
|
||||
return mock_exit(error="Error: Mock only supports --color=never", rc=1)
|
||||
|
||||
if args.subparser_name == 'logout':
|
||||
if args.subparser_name == "logout":
|
||||
if self._mock_logged_out:
|
||||
return mock_exit(error='Error: Not currently logged in', rc=1)
|
||||
return mock_exit(error="Error: Not currently logged in", rc=1)
|
||||
|
||||
logged_in_error = 'Are you sure you would like to log out? [Y/n]'
|
||||
if stdin and stdin.lower() == 'n\n':
|
||||
return mock_exit(output='Log out: aborted.', error=logged_in_error, rc=1)
|
||||
elif stdin and stdin.lower() == 'y\n':
|
||||
return mock_exit(output='Log out: complete.', error=logged_in_error, rc=0)
|
||||
logged_in_error = "Are you sure you would like to log out? [Y/n]"
|
||||
if stdin and stdin.lower() == "n\n":
|
||||
return mock_exit(output="Log out: aborted.", error=logged_in_error, rc=1)
|
||||
elif stdin and stdin.lower() == "y\n":
|
||||
return mock_exit(output="Log out: complete.", error=logged_in_error, rc=0)
|
||||
else:
|
||||
return mock_exit(error='Error: aborted response', rc=1)
|
||||
return mock_exit(error="Error: aborted response", rc=1)
|
||||
|
||||
if args.subparser_name == 'show':
|
||||
if args.subparser_name == "show":
|
||||
if self._mock_logged_out:
|
||||
return mock_exit(error="Error: Could not find decryption key. Perhaps you need to login with `lpass login`.", rc=1)
|
||||
return mock_exit(
|
||||
error="Error: Could not find decryption key. Perhaps you need to login with `lpass login`.", rc=1
|
||||
)
|
||||
|
||||
if self._mock_disconnected:
|
||||
return mock_exit(error='Error: Couldn\'t resolve host name.', rc=1)
|
||||
return mock_exit(error="Error: Couldn't resolve host name.", rc=1)
|
||||
|
||||
mock_entry = self._lookup_mock_entry(args.selector)
|
||||
|
||||
if args.field:
|
||||
return mock_exit(output=mock_entry.get(args.field, ''))
|
||||
return mock_exit(output=mock_entry.get(args.field, ""))
|
||||
elif args.password:
|
||||
return mock_exit(output=mock_entry.get('password', ''))
|
||||
return mock_exit(output=mock_entry.get("password", ""))
|
||||
elif args.username:
|
||||
return mock_exit(output=mock_entry.get('username', ''))
|
||||
return mock_exit(output=mock_entry.get("username", ""))
|
||||
elif args.url:
|
||||
return mock_exit(output=mock_entry.get('url', ''))
|
||||
return mock_exit(output=mock_entry.get("url", ""))
|
||||
elif args.name:
|
||||
return mock_exit(output=mock_entry.get('name', ''))
|
||||
return mock_exit(output=mock_entry.get("name", ""))
|
||||
elif args.id:
|
||||
return mock_exit(output=mock_entry.get('id', ''))
|
||||
return mock_exit(output=mock_entry.get("id", ""))
|
||||
elif args.notes:
|
||||
return mock_exit(output=mock_entry.get('notes', ''))
|
||||
return mock_exit(output=mock_entry.get("notes", ""))
|
||||
|
||||
raise LPassException('We should never get here')
|
||||
raise LPassException("We should never get here")
|
||||
|
||||
|
||||
class DisconnectedMockLPass(MockLPass):
|
||||
|
||||
_mock_disconnected = True
|
||||
|
||||
|
||||
class LoggedOutMockLPass(MockLPass):
|
||||
|
||||
_mock_logged_out = True
|
||||
|
||||
|
||||
class TestLPass(unittest.TestCase):
|
||||
|
||||
def setUp(self):
|
||||
self.lookup = lookup_loader.get('community.general.lastpass')
|
||||
self.lookup = lookup_loader.get("community.general.lastpass")
|
||||
|
||||
def test_lastpass_cli_path(self):
|
||||
lp = MockLPass(path='/dev/null')
|
||||
self.assertEqual('/dev/null', lp.cli_path)
|
||||
lp = MockLPass(path="/dev/null")
|
||||
self.assertEqual("/dev/null", lp.cli_path)
|
||||
|
||||
def test_lastpass_build_args_logout(self):
|
||||
lp = MockLPass()
|
||||
self.assertEqual(['logout', '--color=never'], lp._build_args("logout"))
|
||||
self.assertEqual(["logout", "--color=never"], lp._build_args("logout"))
|
||||
|
||||
def test_lastpass_logged_in_true(self):
|
||||
lp = MockLPass()
|
||||
@@ -133,39 +135,37 @@ class TestLPass(unittest.TestCase):
|
||||
lp = DisconnectedMockLPass()
|
||||
|
||||
with self.assertRaises(LPassException):
|
||||
lp.get_field('0123456789', 'username')
|
||||
lp.get_field("0123456789", "username")
|
||||
|
||||
def test_lastpass_show(self):
|
||||
lp = MockLPass()
|
||||
for entry in MOCK_ENTRIES:
|
||||
entry_id = entry.get('id')
|
||||
entry_id = entry.get("id")
|
||||
for k, v in entry.items():
|
||||
self.assertEqual(v.strip(), lp.get_field(entry_id, k))
|
||||
|
||||
|
||||
class TestLastpassPlugin(unittest.TestCase):
|
||||
|
||||
def setUp(self):
|
||||
self.lookup = lookup_loader.get('community.general.lastpass')
|
||||
self.lookup = lookup_loader.get("community.general.lastpass")
|
||||
|
||||
@patch('ansible_collections.community.general.plugins.lookup.lastpass.LPass', new=MockLPass)
|
||||
@patch("ansible_collections.community.general.plugins.lookup.lastpass.LPass", new=MockLPass)
|
||||
def test_lastpass_plugin_normal(self):
|
||||
for entry in MOCK_ENTRIES:
|
||||
entry_id = entry.get('id')
|
||||
entry_id = entry.get("id")
|
||||
for k, v in entry.items():
|
||||
self.assertEqual(v.strip(),
|
||||
self.lookup.run([entry_id], field=k)[0])
|
||||
self.assertEqual(v.strip(), self.lookup.run([entry_id], field=k)[0])
|
||||
|
||||
@patch('ansible_collections.community.general.plugins.lookup.lastpass.LPass', LoggedOutMockLPass)
|
||||
@patch("ansible_collections.community.general.plugins.lookup.lastpass.LPass", LoggedOutMockLPass)
|
||||
def test_lastpass_plugin_logged_out(self):
|
||||
entry = MOCK_ENTRIES[0]
|
||||
entry_id = entry.get('id')
|
||||
entry_id = entry.get("id")
|
||||
with self.assertRaises(AnsibleError):
|
||||
self.lookup.run([entry_id], field='password')
|
||||
self.lookup.run([entry_id], field="password")
|
||||
|
||||
@patch('ansible_collections.community.general.plugins.lookup.lastpass.LPass', DisconnectedMockLPass)
|
||||
@patch("ansible_collections.community.general.plugins.lookup.lastpass.LPass", DisconnectedMockLPass)
|
||||
def test_lastpass_plugin_disconnected(self):
|
||||
entry = MOCK_ENTRIES[0]
|
||||
entry_id = entry.get('id')
|
||||
entry_id = entry.get("id")
|
||||
with self.assertRaises(AnsibleError):
|
||||
self.lookup.run([entry_id], field='password')
|
||||
self.lookup.run([entry_id], field="password")
|
||||
|
||||
@@ -18,7 +18,6 @@ from ansible_collections.community.general.plugins.lookup import merge_variables
|
||||
|
||||
class TestMergeVariablesLookup(unittest.TestCase):
|
||||
class HostVarsMock(dict):
|
||||
|
||||
def __getattr__(self, item):
|
||||
return super().__getitem__(item)
|
||||
|
||||
@@ -33,269 +32,241 @@ class TestMergeVariablesLookup(unittest.TestCase):
|
||||
self.templar = Templar(loader=self.loader, variables={})
|
||||
self.merge_vars_lookup = merge_variables.LookupModule(loader=self.loader, templar=self.templar)
|
||||
|
||||
@patch.object(AnsiblePlugin, 'set_options')
|
||||
@patch.object(AnsiblePlugin, 'get_option', side_effect=[None, 'ignore', 'suffix', None])
|
||||
@patch.object(Templar, 'template', side_effect=[['item1'], ['item3']])
|
||||
@patch.object(AnsiblePlugin, "set_options")
|
||||
@patch.object(AnsiblePlugin, "get_option", side_effect=[None, "ignore", "suffix", None])
|
||||
@patch.object(Templar, "template", side_effect=[["item1"], ["item3"]])
|
||||
def test_merge_list(self, mock_set_options, mock_get_option, mock_template):
|
||||
results = self.merge_vars_lookup.run(['__merge_list'], {
|
||||
'testlist1__merge_list': ['item1'],
|
||||
'testlist2': ['item2'],
|
||||
'testlist3__merge_list': ['item3']
|
||||
})
|
||||
results = self.merge_vars_lookup.run(
|
||||
["__merge_list"],
|
||||
{"testlist1__merge_list": ["item1"], "testlist2": ["item2"], "testlist3__merge_list": ["item3"]},
|
||||
)
|
||||
|
||||
self.assertEqual(results, [['item1', 'item3']])
|
||||
self.assertEqual(results, [["item1", "item3"]])
|
||||
|
||||
@patch.object(AnsiblePlugin, 'set_options')
|
||||
@patch.object(AnsiblePlugin, 'get_option', side_effect=[['initial_item'], 'ignore', 'suffix', None])
|
||||
@patch.object(Templar, 'template', side_effect=[['item1'], ['item3']])
|
||||
@patch.object(AnsiblePlugin, "set_options")
|
||||
@patch.object(AnsiblePlugin, "get_option", side_effect=[["initial_item"], "ignore", "suffix", None])
|
||||
@patch.object(Templar, "template", side_effect=[["item1"], ["item3"]])
|
||||
def test_merge_list_with_initial_value(self, mock_set_options, mock_get_option, mock_template):
|
||||
results = self.merge_vars_lookup.run(['__merge_list'], {
|
||||
'testlist1__merge_list': ['item1'],
|
||||
'testlist2': ['item2'],
|
||||
'testlist3__merge_list': ['item3']
|
||||
})
|
||||
results = self.merge_vars_lookup.run(
|
||||
["__merge_list"],
|
||||
{"testlist1__merge_list": ["item1"], "testlist2": ["item2"], "testlist3__merge_list": ["item3"]},
|
||||
)
|
||||
|
||||
self.assertEqual(results, [['initial_item', 'item1', 'item3']])
|
||||
self.assertEqual(results, [["initial_item", "item1", "item3"]])
|
||||
|
||||
@patch.object(AnsiblePlugin, 'set_options')
|
||||
@patch.object(AnsiblePlugin, 'get_option', side_effect=[None, 'ignore', 'suffix', None])
|
||||
@patch.object(Templar, 'template', side_effect=[{'item1': 'test', 'list_item': ['test1']},
|
||||
{'item2': 'test', 'list_item': ['test2']}])
|
||||
@patch.object(AnsiblePlugin, "set_options")
|
||||
@patch.object(AnsiblePlugin, "get_option", side_effect=[None, "ignore", "suffix", None])
|
||||
@patch.object(
|
||||
Templar,
|
||||
"template",
|
||||
side_effect=[{"item1": "test", "list_item": ["test1"]}, {"item2": "test", "list_item": ["test2"]}],
|
||||
)
|
||||
def test_merge_dict(self, mock_set_options, mock_get_option, mock_template):
|
||||
results = self.merge_vars_lookup.run(['__merge_dict'], {
|
||||
'testdict1__merge_dict': {
|
||||
'item1': 'test',
|
||||
'list_item': ['test1']
|
||||
},
|
||||
'testdict2__merge_dict': {
|
||||
'item2': 'test',
|
||||
'list_item': ['test2']
|
||||
}
|
||||
})
|
||||
|
||||
self.assertEqual(results, [
|
||||
results = self.merge_vars_lookup.run(
|
||||
["__merge_dict"],
|
||||
{
|
||||
'item1': 'test',
|
||||
'item2': 'test',
|
||||
'list_item': ['test1', 'test2']
|
||||
}
|
||||
])
|
||||
"testdict1__merge_dict": {"item1": "test", "list_item": ["test1"]},
|
||||
"testdict2__merge_dict": {"item2": "test", "list_item": ["test2"]},
|
||||
},
|
||||
)
|
||||
|
||||
@patch.object(AnsiblePlugin, 'set_options')
|
||||
@patch.object(AnsiblePlugin, 'get_option', side_effect=[{'initial_item': 'random value', 'list_item': ['test0']},
|
||||
'ignore', 'suffix', None])
|
||||
@patch.object(Templar, 'template', side_effect=[{'item1': 'test', 'list_item': ['test1']},
|
||||
{'item2': 'test', 'list_item': ['test2']}])
|
||||
self.assertEqual(results, [{"item1": "test", "item2": "test", "list_item": ["test1", "test2"]}])
|
||||
|
||||
@patch.object(AnsiblePlugin, "set_options")
|
||||
@patch.object(
|
||||
AnsiblePlugin,
|
||||
"get_option",
|
||||
side_effect=[{"initial_item": "random value", "list_item": ["test0"]}, "ignore", "suffix", None],
|
||||
)
|
||||
@patch.object(
|
||||
Templar,
|
||||
"template",
|
||||
side_effect=[{"item1": "test", "list_item": ["test1"]}, {"item2": "test", "list_item": ["test2"]}],
|
||||
)
|
||||
def test_merge_dict_with_initial_value(self, mock_set_options, mock_get_option, mock_template):
|
||||
results = self.merge_vars_lookup.run(['__merge_dict'], {
|
||||
'testdict1__merge_dict': {
|
||||
'item1': 'test',
|
||||
'list_item': ['test1']
|
||||
},
|
||||
'testdict2__merge_dict': {
|
||||
'item2': 'test',
|
||||
'list_item': ['test2']
|
||||
}
|
||||
})
|
||||
|
||||
self.assertEqual(results, [
|
||||
results = self.merge_vars_lookup.run(
|
||||
["__merge_dict"],
|
||||
{
|
||||
'initial_item': 'random value',
|
||||
'item1': 'test',
|
||||
'item2': 'test',
|
||||
'list_item': ['test0', 'test1', 'test2']
|
||||
}
|
||||
])
|
||||
"testdict1__merge_dict": {"item1": "test", "list_item": ["test1"]},
|
||||
"testdict2__merge_dict": {"item2": "test", "list_item": ["test2"]},
|
||||
},
|
||||
)
|
||||
|
||||
@patch.object(AnsiblePlugin, 'set_options')
|
||||
@patch.object(AnsiblePlugin, 'get_option', side_effect=[None, 'warn', 'suffix', None])
|
||||
@patch.object(Templar, 'template', side_effect=[{'item': 'value1'}, {'item': 'value2'}])
|
||||
@patch.object(Display, 'warning')
|
||||
self.assertEqual(
|
||||
results,
|
||||
[
|
||||
{
|
||||
"initial_item": "random value",
|
||||
"item1": "test",
|
||||
"item2": "test",
|
||||
"list_item": ["test0", "test1", "test2"],
|
||||
}
|
||||
],
|
||||
)
|
||||
|
||||
@patch.object(AnsiblePlugin, "set_options")
|
||||
@patch.object(AnsiblePlugin, "get_option", side_effect=[None, "warn", "suffix", None])
|
||||
@patch.object(Templar, "template", side_effect=[{"item": "value1"}, {"item": "value2"}])
|
||||
@patch.object(Display, "warning")
|
||||
def test_merge_dict_non_unique_warning(self, mock_set_options, mock_get_option, mock_template, mock_display):
|
||||
results = self.merge_vars_lookup.run(['__merge_non_unique'], {
|
||||
'testdict1__merge_non_unique': {'item': 'value1'},
|
||||
'testdict2__merge_non_unique': {'item': 'value2'}
|
||||
})
|
||||
results = self.merge_vars_lookup.run(
|
||||
["__merge_non_unique"],
|
||||
{"testdict1__merge_non_unique": {"item": "value1"}, "testdict2__merge_non_unique": {"item": "value2"}},
|
||||
)
|
||||
|
||||
self.assertTrue(mock_display.called)
|
||||
self.assertEqual(results, [{'item': 'value2'}])
|
||||
self.assertEqual(results, [{"item": "value2"}])
|
||||
|
||||
@patch.object(AnsiblePlugin, 'set_options')
|
||||
@patch.object(AnsiblePlugin, 'get_option', side_effect=[None, 'error', 'suffix', None])
|
||||
@patch.object(Templar, 'template', side_effect=[{'item': 'value1'}, {'item': 'value2'}])
|
||||
@patch.object(AnsiblePlugin, "set_options")
|
||||
@patch.object(AnsiblePlugin, "get_option", side_effect=[None, "error", "suffix", None])
|
||||
@patch.object(Templar, "template", side_effect=[{"item": "value1"}, {"item": "value2"}])
|
||||
def test_merge_dict_non_unique_error(self, mock_set_options, mock_get_option, mock_template):
|
||||
with self.assertRaises(AnsibleError):
|
||||
self.merge_vars_lookup.run(['__merge_non_unique'], {
|
||||
'testdict1__merge_non_unique': {'item': 'value1'},
|
||||
'testdict2__merge_non_unique': {'item': 'value2'}
|
||||
})
|
||||
self.merge_vars_lookup.run(
|
||||
["__merge_non_unique"],
|
||||
{"testdict1__merge_non_unique": {"item": "value1"}, "testdict2__merge_non_unique": {"item": "value2"}},
|
||||
)
|
||||
|
||||
@patch.object(AnsiblePlugin, 'set_options')
|
||||
@patch.object(AnsiblePlugin, 'get_option', side_effect=[None, 'ignore', 'suffix', None])
|
||||
@patch.object(Templar, 'template', side_effect=[{'item1': 'test', 'list_item': ['test1']},
|
||||
['item2', 'item3']])
|
||||
@patch.object(AnsiblePlugin, "set_options")
|
||||
@patch.object(AnsiblePlugin, "get_option", side_effect=[None, "ignore", "suffix", None])
|
||||
@patch.object(Templar, "template", side_effect=[{"item1": "test", "list_item": ["test1"]}, ["item2", "item3"]])
|
||||
def test_merge_list_and_dict(self, mock_set_options, mock_get_option, mock_template):
|
||||
with self.assertRaises(AnsibleError):
|
||||
self.merge_vars_lookup.run(['__merge_var'], {
|
||||
'testlist__merge_var': {
|
||||
'item1': 'test',
|
||||
'list_item': ['test1']
|
||||
self.merge_vars_lookup.run(
|
||||
["__merge_var"],
|
||||
{
|
||||
"testlist__merge_var": {"item1": "test", "list_item": ["test1"]},
|
||||
"testdict__merge_var": ["item2", "item3"],
|
||||
},
|
||||
'testdict__merge_var': ['item2', 'item3']
|
||||
})
|
||||
)
|
||||
|
||||
@patch.object(AnsiblePlugin, 'set_options')
|
||||
@patch.object(AnsiblePlugin, 'get_option', side_effect=[None, 'ignore', 'suffix', ['all']])
|
||||
@patch.object(Templar, 'template', side_effect=[
|
||||
{'var': [{'item1': 'value1', 'item2': 'value2'}]},
|
||||
{'var': [{'item5': 'value5', 'item6': 'value6'}]},
|
||||
])
|
||||
@patch.object(AnsiblePlugin, "set_options")
|
||||
@patch.object(AnsiblePlugin, "get_option", side_effect=[None, "ignore", "suffix", ["all"]])
|
||||
@patch.object(
|
||||
Templar,
|
||||
"template",
|
||||
side_effect=[
|
||||
{"var": [{"item1": "value1", "item2": "value2"}]},
|
||||
{"var": [{"item5": "value5", "item6": "value6"}]},
|
||||
],
|
||||
)
|
||||
def test_merge_dict_group_all(self, mock_set_options, mock_get_option, mock_template):
|
||||
hostvars = self.HostVarsMock({
|
||||
'host1': {
|
||||
'group_names': ['dummy1'],
|
||||
'inventory_hostname': 'host1',
|
||||
'1testlist__merge_var': {
|
||||
'var': [{'item1': 'value1', 'item2': 'value2'}]
|
||||
}
|
||||
},
|
||||
'host2': {
|
||||
'group_names': ['dummy1'],
|
||||
'inventory_hostname': 'host2',
|
||||
'2otherlist__merge_var': {
|
||||
'var': [{'item5': 'value5', 'item6': 'value6'}]
|
||||
}
|
||||
hostvars = self.HostVarsMock(
|
||||
{
|
||||
"host1": {
|
||||
"group_names": ["dummy1"],
|
||||
"inventory_hostname": "host1",
|
||||
"1testlist__merge_var": {"var": [{"item1": "value1", "item2": "value2"}]},
|
||||
},
|
||||
"host2": {
|
||||
"group_names": ["dummy1"],
|
||||
"inventory_hostname": "host2",
|
||||
"2otherlist__merge_var": {"var": [{"item5": "value5", "item6": "value6"}]},
|
||||
},
|
||||
}
|
||||
})
|
||||
variables = {
|
||||
'inventory_hostname': 'host1',
|
||||
'hostvars': hostvars
|
||||
}
|
||||
)
|
||||
variables = {"inventory_hostname": "host1", "hostvars": hostvars}
|
||||
|
||||
results = self.merge_vars_lookup.run(['__merge_var'], variables)
|
||||
results = self.merge_vars_lookup.run(["__merge_var"], variables)
|
||||
|
||||
self.assertEqual(results, [
|
||||
{'var': [
|
||||
{'item1': 'value1', 'item2': 'value2'},
|
||||
{'item5': 'value5', 'item6': 'value6'}
|
||||
]}
|
||||
])
|
||||
self.assertEqual(
|
||||
results, [{"var": [{"item1": "value1", "item2": "value2"}, {"item5": "value5", "item6": "value6"}]}]
|
||||
)
|
||||
|
||||
@patch.object(AnsiblePlugin, 'set_options')
|
||||
@patch.object(AnsiblePlugin, 'get_option', side_effect=[None, 'ignore', 'suffix', ['dummy1']])
|
||||
@patch.object(Templar, 'template', side_effect=[
|
||||
{'var': [{'item1': 'value1', 'item2': 'value2'}]},
|
||||
{'var': [{'item5': 'value5', 'item6': 'value6'}]},
|
||||
])
|
||||
@patch.object(AnsiblePlugin, "set_options")
|
||||
@patch.object(AnsiblePlugin, "get_option", side_effect=[None, "ignore", "suffix", ["dummy1"]])
|
||||
@patch.object(
|
||||
Templar,
|
||||
"template",
|
||||
side_effect=[
|
||||
{"var": [{"item1": "value1", "item2": "value2"}]},
|
||||
{"var": [{"item5": "value5", "item6": "value6"}]},
|
||||
],
|
||||
)
|
||||
def test_merge_dict_group_single(self, mock_set_options, mock_get_option, mock_template):
|
||||
hostvars = self.HostVarsMock({
|
||||
'host1': {
|
||||
'group_names': ['dummy1'],
|
||||
'inventory_hostname': 'host1',
|
||||
'1testlist__merge_var': {
|
||||
'var': [{'item1': 'value1', 'item2': 'value2'}]
|
||||
}
|
||||
},
|
||||
'host2': {
|
||||
'group_names': ['dummy1'],
|
||||
'inventory_hostname': 'host2',
|
||||
'2otherlist__merge_var': {
|
||||
'var': [{'item5': 'value5', 'item6': 'value6'}]
|
||||
}
|
||||
},
|
||||
'host3': {
|
||||
'group_names': ['dummy2'],
|
||||
'inventory_hostname': 'host3',
|
||||
'3otherlist__merge_var': {
|
||||
'var': [{'item3': 'value3', 'item4': 'value4'}]
|
||||
}
|
||||
hostvars = self.HostVarsMock(
|
||||
{
|
||||
"host1": {
|
||||
"group_names": ["dummy1"],
|
||||
"inventory_hostname": "host1",
|
||||
"1testlist__merge_var": {"var": [{"item1": "value1", "item2": "value2"}]},
|
||||
},
|
||||
"host2": {
|
||||
"group_names": ["dummy1"],
|
||||
"inventory_hostname": "host2",
|
||||
"2otherlist__merge_var": {"var": [{"item5": "value5", "item6": "value6"}]},
|
||||
},
|
||||
"host3": {
|
||||
"group_names": ["dummy2"],
|
||||
"inventory_hostname": "host3",
|
||||
"3otherlist__merge_var": {"var": [{"item3": "value3", "item4": "value4"}]},
|
||||
},
|
||||
}
|
||||
})
|
||||
variables = {
|
||||
'inventory_hostname': 'host1',
|
||||
'hostvars': hostvars
|
||||
}
|
||||
)
|
||||
variables = {"inventory_hostname": "host1", "hostvars": hostvars}
|
||||
|
||||
results = self.merge_vars_lookup.run(['__merge_var'], variables)
|
||||
results = self.merge_vars_lookup.run(["__merge_var"], variables)
|
||||
|
||||
self.assertEqual(results, [
|
||||
{'var': [
|
||||
{'item1': 'value1', 'item2': 'value2'},
|
||||
{'item5': 'value5', 'item6': 'value6'}
|
||||
]}
|
||||
])
|
||||
self.assertEqual(
|
||||
results, [{"var": [{"item1": "value1", "item2": "value2"}, {"item5": "value5", "item6": "value6"}]}]
|
||||
)
|
||||
|
||||
@patch.object(AnsiblePlugin, 'set_options')
|
||||
@patch.object(AnsiblePlugin, 'get_option', side_effect=[None, 'ignore', 'suffix', ['dummy1', 'dummy2']])
|
||||
@patch.object(Templar, 'template', side_effect=[
|
||||
{'var': [{'item1': 'value1', 'item2': 'value2'}]},
|
||||
{'var': [{'item5': 'value5', 'item6': 'value6'}]},
|
||||
])
|
||||
@patch.object(AnsiblePlugin, "set_options")
|
||||
@patch.object(AnsiblePlugin, "get_option", side_effect=[None, "ignore", "suffix", ["dummy1", "dummy2"]])
|
||||
@patch.object(
|
||||
Templar,
|
||||
"template",
|
||||
side_effect=[
|
||||
{"var": [{"item1": "value1", "item2": "value2"}]},
|
||||
{"var": [{"item5": "value5", "item6": "value6"}]},
|
||||
],
|
||||
)
|
||||
def test_merge_dict_group_multiple(self, mock_set_options, mock_get_option, mock_template):
|
||||
hostvars = self.HostVarsMock({
|
||||
'host1': {
|
||||
'group_names': ['dummy1'],
|
||||
'inventory_hostname': 'host1',
|
||||
'1testlist__merge_var': {
|
||||
'var': [{'item1': 'value1', 'item2': 'value2'}]
|
||||
}
|
||||
},
|
||||
'host2': {
|
||||
'group_names': ['dummy2'],
|
||||
'inventory_hostname': 'host2',
|
||||
'2otherlist__merge_var': {
|
||||
'var': [{'item5': 'value5', 'item6': 'value6'}]
|
||||
}
|
||||
},
|
||||
'host3': {
|
||||
'group_names': ['dummy3'],
|
||||
'inventory_hostname': 'host3',
|
||||
'3otherlist__merge_var': {
|
||||
'var': [{'item3': 'value3', 'item4': 'value4'}]
|
||||
}
|
||||
hostvars = self.HostVarsMock(
|
||||
{
|
||||
"host1": {
|
||||
"group_names": ["dummy1"],
|
||||
"inventory_hostname": "host1",
|
||||
"1testlist__merge_var": {"var": [{"item1": "value1", "item2": "value2"}]},
|
||||
},
|
||||
"host2": {
|
||||
"group_names": ["dummy2"],
|
||||
"inventory_hostname": "host2",
|
||||
"2otherlist__merge_var": {"var": [{"item5": "value5", "item6": "value6"}]},
|
||||
},
|
||||
"host3": {
|
||||
"group_names": ["dummy3"],
|
||||
"inventory_hostname": "host3",
|
||||
"3otherlist__merge_var": {"var": [{"item3": "value3", "item4": "value4"}]},
|
||||
},
|
||||
}
|
||||
})
|
||||
variables = {
|
||||
'inventory_hostname': 'host1',
|
||||
'hostvars': hostvars
|
||||
}
|
||||
results = self.merge_vars_lookup.run(['__merge_var'], variables)
|
||||
)
|
||||
variables = {"inventory_hostname": "host1", "hostvars": hostvars}
|
||||
results = self.merge_vars_lookup.run(["__merge_var"], variables)
|
||||
|
||||
self.assertEqual(results, [
|
||||
{'var': [
|
||||
{'item1': 'value1', 'item2': 'value2'},
|
||||
{'item5': 'value5', 'item6': 'value6'}
|
||||
]}
|
||||
])
|
||||
self.assertEqual(
|
||||
results, [{"var": [{"item1": "value1", "item2": "value2"}, {"item5": "value5", "item6": "value6"}]}]
|
||||
)
|
||||
|
||||
@patch.object(AnsiblePlugin, 'set_options')
|
||||
@patch.object(AnsiblePlugin, 'get_option', side_effect=[None, 'ignore', 'suffix', ['dummy1', 'dummy2']])
|
||||
@patch.object(Templar, 'template', side_effect=[
|
||||
['item1'],
|
||||
['item5'],
|
||||
])
|
||||
@patch.object(AnsiblePlugin, "set_options")
|
||||
@patch.object(AnsiblePlugin, "get_option", side_effect=[None, "ignore", "suffix", ["dummy1", "dummy2"]])
|
||||
@patch.object(
|
||||
Templar,
|
||||
"template",
|
||||
side_effect=[
|
||||
["item1"],
|
||||
["item5"],
|
||||
],
|
||||
)
|
||||
def test_merge_list_group_multiple(self, mock_set_options, mock_get_option, mock_template):
|
||||
hostvars = self.HostVarsMock({
|
||||
'host1': {
|
||||
'group_names': ['dummy1'],
|
||||
'inventory_hostname': 'host1',
|
||||
'1testlist__merge_var': ['item1']
|
||||
},
|
||||
'host2': {
|
||||
'group_names': ['dummy2'],
|
||||
'inventory_hostname': 'host2',
|
||||
'2otherlist__merge_var': ['item5']
|
||||
},
|
||||
'host3': {
|
||||
'group_names': ['dummy3'],
|
||||
'inventory_hostname': 'host3',
|
||||
'3otherlist__merge_var': ['item3']
|
||||
hostvars = self.HostVarsMock(
|
||||
{
|
||||
"host1": {"group_names": ["dummy1"], "inventory_hostname": "host1", "1testlist__merge_var": ["item1"]},
|
||||
"host2": {"group_names": ["dummy2"], "inventory_hostname": "host2", "2otherlist__merge_var": ["item5"]},
|
||||
"host3": {"group_names": ["dummy3"], "inventory_hostname": "host3", "3otherlist__merge_var": ["item3"]},
|
||||
}
|
||||
})
|
||||
variables = {
|
||||
'inventory_hostname': 'host1',
|
||||
'hostvars': hostvars
|
||||
}
|
||||
results = self.merge_vars_lookup.run(['__merge_var'], variables)
|
||||
)
|
||||
variables = {"inventory_hostname": "host1", "hostvars": hostvars}
|
||||
results = self.merge_vars_lookup.run(["__merge_var"], variables)
|
||||
|
||||
self.assertEqual(results, [['item1', 'item5']])
|
||||
self.assertEqual(results, [["item1", "item5"]])
|
||||
|
||||
@@ -19,19 +19,34 @@ from ansible_collections.community.general.plugins.lookup.onepassword import (
|
||||
)
|
||||
|
||||
|
||||
OP_VERSION_FIXTURES = [
|
||||
"opv1",
|
||||
"opv2"
|
||||
]
|
||||
OP_VERSION_FIXTURES = ["opv1", "opv2"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("args", "rc", "expected_call_args", "expected_call_kwargs", "expected"),
|
||||
(
|
||||
([], 0, ["get", "account"], {"ignore_errors": True}, True,),
|
||||
([], 1, ["get", "account"], {"ignore_errors": True}, False,),
|
||||
(["acme"], 1, ["get", "account", "--account", "acme.1password.com"], {"ignore_errors": True}, False,),
|
||||
)
|
||||
(
|
||||
[],
|
||||
0,
|
||||
["get", "account"],
|
||||
{"ignore_errors": True},
|
||||
True,
|
||||
),
|
||||
(
|
||||
[],
|
||||
1,
|
||||
["get", "account"],
|
||||
{"ignore_errors": True},
|
||||
False,
|
||||
),
|
||||
(
|
||||
["acme"],
|
||||
1,
|
||||
["get", "account", "--account", "acme.1password.com"],
|
||||
{"ignore_errors": True},
|
||||
False,
|
||||
),
|
||||
),
|
||||
)
|
||||
def test_assert_logged_in_v1(mocker, args, rc, expected_call_args, expected_call_kwargs, expected):
|
||||
mocker.patch.object(OnePassCLIv1, "_run", return_value=[rc, "", ""])
|
||||
@@ -54,23 +69,44 @@ def test_full_signin_v1(mocker):
|
||||
)
|
||||
result = op_cli.full_signin()
|
||||
|
||||
op_cli._run.assert_called_with([
|
||||
"signin",
|
||||
"acme.1password.com",
|
||||
b"bob@acme.com",
|
||||
b"SECRET",
|
||||
"--raw",
|
||||
], command_input=b"ONEKEYTORULETHEMALL")
|
||||
op_cli._run.assert_called_with(
|
||||
[
|
||||
"signin",
|
||||
"acme.1password.com",
|
||||
b"bob@acme.com",
|
||||
b"SECRET",
|
||||
"--raw",
|
||||
],
|
||||
command_input=b"ONEKEYTORULETHEMALL",
|
||||
)
|
||||
assert result == [0, "", ""]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("args", "out", "expected_call_args", "expected_call_kwargs", "expected"),
|
||||
(
|
||||
([], "list of accounts", ["account", "get"], {"ignore_errors": True}, True,),
|
||||
(["acme"], "list of accounts", ["account", "get", "--account", "acme.1password.com"], {"ignore_errors": True}, True,),
|
||||
([], "", ["account", "list"], {}, False,),
|
||||
)
|
||||
(
|
||||
[],
|
||||
"list of accounts",
|
||||
["account", "get"],
|
||||
{"ignore_errors": True},
|
||||
True,
|
||||
),
|
||||
(
|
||||
["acme"],
|
||||
"list of accounts",
|
||||
["account", "get", "--account", "acme.1password.com"],
|
||||
{"ignore_errors": True},
|
||||
True,
|
||||
),
|
||||
(
|
||||
[],
|
||||
"",
|
||||
["account", "list"],
|
||||
{},
|
||||
False,
|
||||
),
|
||||
),
|
||||
)
|
||||
def test_assert_logged_in_v2(mocker, args, out, expected_call_args, expected_call_kwargs, expected):
|
||||
mocker.patch.object(OnePassCLIv2, "_run", return_value=[0, out, ""])
|
||||
@@ -100,13 +136,17 @@ def test_full_signin_v2(mocker):
|
||||
|
||||
op_cli._run.assert_called_with(
|
||||
[
|
||||
"account", "add", "--raw",
|
||||
"--address", "acme.1password.com",
|
||||
"--email", b"bob@acme.com",
|
||||
"account",
|
||||
"add",
|
||||
"--raw",
|
||||
"--address",
|
||||
"acme.1password.com",
|
||||
"--email",
|
||||
b"bob@acme.com",
|
||||
"--signin",
|
||||
],
|
||||
command_input=b"ONEKEYTORULETHEMALL",
|
||||
environment_update={'OP_SECRET_KEY': 'SECRET'},
|
||||
environment_update={"OP_SECRET_KEY": "SECRET"},
|
||||
)
|
||||
assert result == [0, "", ""]
|
||||
|
||||
@@ -116,7 +156,7 @@ def test_full_signin_v2(mocker):
|
||||
(
|
||||
("1.17.2", OnePassCLIv1),
|
||||
("2.27.4", OnePassCLIv2),
|
||||
)
|
||||
),
|
||||
)
|
||||
def test_op_correct_cli_class(fake_op, version, version_class):
|
||||
op = fake_op(version)
|
||||
@@ -146,12 +186,11 @@ def test_op_set_token_with_config(op_fixture, mocker, request):
|
||||
[
|
||||
(op, value)
|
||||
for op in OP_VERSION_FIXTURES
|
||||
for value in
|
||||
(
|
||||
for value in (
|
||||
"Missing required parameters",
|
||||
"The operation is unauthorized",
|
||||
)
|
||||
]
|
||||
],
|
||||
)
|
||||
def test_op_set_token_with_config_missing_args(op_fixture, message, request, mocker):
|
||||
op = request.getfixturevalue(op_fixture)
|
||||
@@ -169,7 +208,9 @@ def test_op_set_token_with_config_missing_args(op_fixture, message, request, moc
|
||||
def test_op_set_token_with_config_full_signin(op_fixture, request, mocker):
|
||||
op = request.getfixturevalue(op_fixture)
|
||||
mocker.patch("os.path.isfile", return_value=True)
|
||||
mocker.patch.object(op._cli, "signin", return_value=(99, "", ""), side_effect=AnsibleLookupError("Raised intentionally"))
|
||||
mocker.patch.object(
|
||||
op._cli, "signin", return_value=(99, "", ""), side_effect=AnsibleLookupError("Raised intentionally")
|
||||
)
|
||||
mocker.patch.object(op._cli, "full_signin", return_value=(0, "", ""))
|
||||
|
||||
op.set_token()
|
||||
@@ -192,8 +233,7 @@ def test_op_set_token_without_config(op_fixture, request, mocker):
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("op_fixture", "login_status"),
|
||||
[(op, value) for op in OP_VERSION_FIXTURES for value in [False, True]]
|
||||
("op_fixture", "login_status"), [(op, value) for op in OP_VERSION_FIXTURES for value in [False, True]]
|
||||
)
|
||||
def test_op_assert_logged_in(mocker, login_status, op_fixture, request):
|
||||
op = request.getfixturevalue(op_fixture)
|
||||
@@ -230,7 +270,7 @@ def test_op_get_raw_v1(mocker, op_fixture, request):
|
||||
(None, ""),
|
||||
("", ""),
|
||||
]
|
||||
)
|
||||
),
|
||||
)
|
||||
def test_op_get_field(mocker, op_fixture, output, expected, request):
|
||||
op = request.getfixturevalue(op_fixture)
|
||||
@@ -251,12 +291,17 @@ def test_op_get_field(mocker, op_fixture, output, expected, request):
|
||||
(_cli_class, item["vault_name"], item["queries"], item.get("kwargs", {}), item["output"], item["expected"])
|
||||
for _cli_class in sorted(MOCK_ENTRIES, key=operator.attrgetter("__name__"))
|
||||
for item in MOCK_ENTRIES[_cli_class]
|
||||
)
|
||||
),
|
||||
)
|
||||
def test_op_lookup(mocker, cli_class, vault, queries, kwargs, output, expected):
|
||||
mocker.patch("ansible_collections.community.general.plugins.lookup.onepassword.OnePass._get_cli_class", cli_class)
|
||||
mocker.patch("ansible_collections.community.general.plugins.lookup.onepassword.OnePass.assert_logged_in", return_value=True)
|
||||
mocker.patch("ansible_collections.community.general.plugins.lookup.onepassword.OnePassCLIBase._run", return_value=(0, json.dumps(output), ""))
|
||||
mocker.patch(
|
||||
"ansible_collections.community.general.plugins.lookup.onepassword.OnePass.assert_logged_in", return_value=True
|
||||
)
|
||||
mocker.patch(
|
||||
"ansible_collections.community.general.plugins.lookup.onepassword.OnePassCLIBase._run",
|
||||
return_value=(0, json.dumps(output), ""),
|
||||
)
|
||||
|
||||
op_lookup = lookup_loader.get("community.general.onepassword")
|
||||
result = op_lookup.run(queries, vault=vault, **kwargs)
|
||||
@@ -269,14 +314,19 @@ def test_signin(op_fixture, request):
|
||||
op = request.getfixturevalue(op_fixture)
|
||||
op._cli.master_password = "master_pass"
|
||||
op._cli.signin()
|
||||
op._cli._run.assert_called_once_with(['signin', '--raw'], command_input=b"master_pass")
|
||||
op._cli._run.assert_called_once_with(["signin", "--raw"], command_input=b"master_pass")
|
||||
|
||||
|
||||
def test_op_doc(mocker):
|
||||
document_contents = "Document Contents\n"
|
||||
|
||||
mocker.patch("ansible_collections.community.general.plugins.lookup.onepassword.OnePass.assert_logged_in", return_value=True)
|
||||
mocker.patch("ansible_collections.community.general.plugins.lookup.onepassword.OnePassCLIBase._run", return_value=(0, document_contents, ""))
|
||||
mocker.patch(
|
||||
"ansible_collections.community.general.plugins.lookup.onepassword.OnePass.assert_logged_in", return_value=True
|
||||
)
|
||||
mocker.patch(
|
||||
"ansible_collections.community.general.plugins.lookup.onepassword.OnePassCLIBase._run",
|
||||
return_value=(0, document_contents, ""),
|
||||
)
|
||||
|
||||
op_lookup = lookup_loader.get("community.general.onepassword_doc")
|
||||
result = op_lookup.run(["Private key doc"])
|
||||
@@ -289,17 +339,18 @@ def test_op_doc(mocker):
|
||||
[
|
||||
(plugin, connect_host, connect_token)
|
||||
for plugin in ("community.general.onepassword", "community.general.onepassword_raw")
|
||||
for (connect_host, connect_token) in
|
||||
(
|
||||
for (connect_host, connect_token) in (
|
||||
("http://localhost", None),
|
||||
(None, "foobar"),
|
||||
)
|
||||
]
|
||||
],
|
||||
)
|
||||
def test_op_connect_partial_args(plugin, connect_host, connect_token, mocker):
|
||||
op_lookup = lookup_loader.get(plugin)
|
||||
|
||||
mocker.patch("ansible_collections.community.general.plugins.lookup.onepassword.OnePass._get_cli_class", OnePassCLIv2)
|
||||
mocker.patch(
|
||||
"ansible_collections.community.general.plugins.lookup.onepassword.OnePass._get_cli_class", OnePassCLIv2
|
||||
)
|
||||
|
||||
with pytest.raises(AnsibleOptionsError):
|
||||
op_lookup.run("login", vault_name="test vault", connect_host=connect_host, connect_token=connect_token)
|
||||
@@ -310,7 +361,7 @@ def test_op_connect_partial_args(plugin, connect_host, connect_token, mocker):
|
||||
(
|
||||
{"connect_host": "http://localhost", "connect_token": "foobar"},
|
||||
{"service_account_token": "foobar"},
|
||||
)
|
||||
),
|
||||
)
|
||||
def test_opv1_unsupported_features(kwargs):
|
||||
op_cli = OnePassCLIv1(**kwargs)
|
||||
|
||||
@@ -17,11 +17,16 @@ from ansible.plugins.loader import lookup_loader
|
||||
(
|
||||
(item["vault_name"], item["queries"], item.get("kwargs", {}), item["output"], item["expected"])
|
||||
for item in SSH_KEY_MOCK_ENTRIES
|
||||
)
|
||||
),
|
||||
)
|
||||
def test_ssh_key(mocker, vault, queries, kwargs, output, expected):
|
||||
mocker.patch("ansible_collections.community.general.plugins.lookup.onepassword.OnePass.assert_logged_in", return_value=True)
|
||||
mocker.patch("ansible_collections.community.general.plugins.lookup.onepassword.OnePassCLIBase._run", return_value=(0, json.dumps(output), ""))
|
||||
mocker.patch(
|
||||
"ansible_collections.community.general.plugins.lookup.onepassword.OnePass.assert_logged_in", return_value=True
|
||||
)
|
||||
mocker.patch(
|
||||
"ansible_collections.community.general.plugins.lookup.onepassword.OnePassCLIBase._run",
|
||||
return_value=(0, json.dumps(output), ""),
|
||||
)
|
||||
|
||||
op_lookup = lookup_loader.get("community.general.onepassword_ssh_key")
|
||||
result = op_lookup.run(queries, vault=vault, **kwargs)
|
||||
|
||||
@@ -14,7 +14,7 @@ from ansible.plugins.loader import lookup_loader
|
||||
|
||||
|
||||
class MockPamSecrets(MagicMock):
|
||||
RESPONSE = 'dummy value'
|
||||
RESPONSE = "dummy value"
|
||||
|
||||
def get_pam_secret(self, path):
|
||||
return self.RESPONSE
|
||||
@@ -30,13 +30,7 @@ class TestLookupModule(TestCase):
|
||||
MockPamSecrets(),
|
||||
)
|
||||
def test_get_pam_secret(self):
|
||||
terms = ['dummy secret']
|
||||
terms = ["dummy secret"]
|
||||
variables = []
|
||||
kwargs = {
|
||||
"base_url": 'https://dummy.url',
|
||||
"api_key": 'dummy'
|
||||
}
|
||||
self.assertListEqual(
|
||||
[{'dummy secret': 'dummy value'}],
|
||||
self.lookup.run(terms, variables, **kwargs)
|
||||
)
|
||||
kwargs = {"base_url": "https://dummy.url", "api_key": "dummy"}
|
||||
self.assertListEqual([{"dummy secret": "dummy value"}], self.lookup.run(terms, variables, **kwargs))
|
||||
|
||||
@@ -16,7 +16,7 @@ from ansible_collections.community.general.plugins.lookup import tss
|
||||
from ansible.plugins.loader import lookup_loader
|
||||
|
||||
|
||||
TSS_IMPORT_PATH = 'ansible_collections.community.general.plugins.lookup.tss'
|
||||
TSS_IMPORT_PATH = "ansible_collections.community.general.plugins.lookup.tss"
|
||||
|
||||
|
||||
def make_absolute(name):
|
||||
@@ -25,7 +25,7 @@ def make_absolute(name):
|
||||
|
||||
class SecretServerError(Exception):
|
||||
def __init__(self):
|
||||
self.message = ''
|
||||
self.message = ""
|
||||
|
||||
|
||||
class MockSecretServer(MagicMock):
|
||||
@@ -40,41 +40,39 @@ class MockFaultySecretServer(MagicMock):
|
||||
raise SecretServerError
|
||||
|
||||
|
||||
@patch(make_absolute('SecretServer'), MockSecretServer())
|
||||
@patch(make_absolute("SecretServer"), MockSecretServer())
|
||||
class TestTSSClient(TestCase):
|
||||
def setUp(self):
|
||||
self.server_params = {
|
||||
'base_url': '',
|
||||
'username': '',
|
||||
'domain': '',
|
||||
'password': '',
|
||||
'api_path_uri': '',
|
||||
'token_path_uri': '',
|
||||
"base_url": "",
|
||||
"username": "",
|
||||
"domain": "",
|
||||
"password": "",
|
||||
"api_path_uri": "",
|
||||
"token_path_uri": "",
|
||||
}
|
||||
|
||||
def test_from_params(self):
|
||||
with patch(make_absolute('HAS_TSS_AUTHORIZER'), False):
|
||||
self.assert_client_version('v0')
|
||||
with patch(make_absolute("HAS_TSS_AUTHORIZER"), False):
|
||||
self.assert_client_version("v0")
|
||||
|
||||
with patch.dict(self.server_params, {'domain': 'foo'}):
|
||||
with patch.dict(self.server_params, {"domain": "foo"}):
|
||||
with self.assertRaises(tss.AnsibleError):
|
||||
self._get_client()
|
||||
|
||||
with patch.multiple(TSS_IMPORT_PATH,
|
||||
HAS_TSS_AUTHORIZER=True,
|
||||
PasswordGrantAuthorizer=DEFAULT,
|
||||
DomainPasswordGrantAuthorizer=DEFAULT):
|
||||
with patch.multiple(
|
||||
TSS_IMPORT_PATH,
|
||||
HAS_TSS_AUTHORIZER=True,
|
||||
PasswordGrantAuthorizer=DEFAULT,
|
||||
DomainPasswordGrantAuthorizer=DEFAULT,
|
||||
):
|
||||
self.assert_client_version("v1")
|
||||
|
||||
self.assert_client_version('v1')
|
||||
|
||||
with patch.dict(self.server_params, {'domain': 'foo'}):
|
||||
self.assert_client_version('v1')
|
||||
with patch.dict(self.server_params, {"domain": "foo"}):
|
||||
self.assert_client_version("v1")
|
||||
|
||||
def assert_client_version(self, version):
|
||||
version_to_class = {
|
||||
'v0': tss.TSSClientV0,
|
||||
'v1': tss.TSSClientV1
|
||||
}
|
||||
version_to_class = {"v0": tss.TSSClientV0, "v1": tss.TSSClientV1}
|
||||
|
||||
client = self._get_client()
|
||||
self.assertIsInstance(client, version_to_class[version])
|
||||
@@ -85,29 +83,25 @@ class TestTSSClient(TestCase):
|
||||
|
||||
class TestLookupModule(TestCase):
|
||||
VALID_TERMS = [1]
|
||||
INVALID_TERMS = ['foo']
|
||||
INVALID_TERMS = ["foo"]
|
||||
|
||||
def setUp(self):
|
||||
self.lookup = lookup_loader.get("community.general.tss")
|
||||
|
||||
@patch.multiple(TSS_IMPORT_PATH,
|
||||
HAS_TSS_SDK=False,
|
||||
SecretServer=MockSecretServer)
|
||||
@patch.multiple(TSS_IMPORT_PATH, HAS_TSS_SDK=False, SecretServer=MockSecretServer)
|
||||
def test_missing_sdk(self):
|
||||
with self.assertRaises(tss.AnsibleError):
|
||||
self._run_lookup(self.VALID_TERMS)
|
||||
|
||||
@patch.multiple(TSS_IMPORT_PATH,
|
||||
HAS_TSS_SDK=True,
|
||||
SecretServerError=SecretServerError)
|
||||
@patch.multiple(TSS_IMPORT_PATH, HAS_TSS_SDK=True, SecretServerError=SecretServerError)
|
||||
def test_get_secret_json(self):
|
||||
with patch(make_absolute('SecretServer'), MockSecretServer):
|
||||
with patch(make_absolute("SecretServer"), MockSecretServer):
|
||||
self.assertListEqual([MockSecretServer.RESPONSE], self._run_lookup(self.VALID_TERMS))
|
||||
|
||||
with self.assertRaises(tss.AnsibleOptionsError):
|
||||
self._run_lookup(self.INVALID_TERMS)
|
||||
|
||||
with patch(make_absolute('SecretServer'), MockFaultySecretServer):
|
||||
with patch(make_absolute("SecretServer"), MockFaultySecretServer):
|
||||
with self.assertRaises(tss.AnsibleError):
|
||||
self._run_lookup(self.VALID_TERMS)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user