Skip to content

Commit 708ac75

Browse files
author
Janez Justin
committed
FIX tests
1 parent 09e20a3 commit 708ac75

9 files changed

Lines changed: 135 additions & 76 deletions

File tree

rpm/s3rpm.py

Lines changed: 21 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
from __future__ import print_function
2-
from pyrpm.rpm import RPM
32
from pyrpm.yum import YumPackage
43
from pyrpm.tools.createrepo import YumRepository
54
import boto3
@@ -29,9 +28,7 @@ def lambda_handler(event, context):
2928
files = ['repomd.xml', 'primary.xml.gz','filelists.xml.gz', 'other.xml.gz']
3029

3130
#make /tmp/repodata path
32-
if not os.path.exists(repo.repodir+'/repodata/'):
33-
os.makedirs(repo.repodir+'/repodata/')
34-
31+
create_new_dir_if_not_exist(repo.repodir+'/repodata/')
3532
# if repodata files exist download them to /tmp where we can manipulate with them
3633
if exists:
3734
print('repodata already exists, old files will be overwriten')
@@ -61,11 +58,23 @@ def lambda_handler(event, context):
6158

6259
#Let us clean up
6360
shutil.rmtree(repo.repodir)
64-
shutil.rmtree('/tmp/gpgdocs')
61+
if os.path.exists('/tmp/gpgdocs'):
62+
shutil.rmtree('/tmp/gpgdocs')
6563

6664
print('METADATA GENERATION COMPLETED')
6765

66+
def create_new_dir_if_not_exist(path):
67+
"""
68+
Creates dir at 'path' if it does not exist
6869
70+
returns true on success
71+
returns false if dir already exists
72+
"""
73+
if not os.path.exists(path):
74+
os.makedirs(path)
75+
return True
76+
else:
77+
return False
6978
def check_bucket_file_existance(path):
7079
"""
7180
checks if file exsist in bucket
@@ -85,7 +94,7 @@ def check_bucket_file_existance(path):
8594

8695
def get_public():
8796
"""
88-
If env variable PUBLIC is set to true returns 'public read'
97+
If env variable PUBLIC is set to true returns 'public-read', else returns 'private'
8998
"""
9099
if os.environ['PUBLIC'] == 'True' :
91100
acl = 'public-read'
@@ -118,6 +127,7 @@ def check_changed_files(repo):
118127
files = []
119128
#cycle through all objects ending with .rpm in REPO_DIR and check if they are already in repodata, if not add them
120129
for obj in s3.Bucket(os.environ['BUCKET_NAME']).objects.filter(Prefix=os.environ['REPO_DIR']):
130+
files.append(obj.key)
121131
if not obj.key.endswith(".rpm"):
122132
print('skipping %s - not rpm file' %(obj.key))
123133
continue
@@ -126,8 +136,7 @@ def check_changed_files(repo):
126136
s3c = boto3.client('s3')
127137
#Create path to folder where to download file, if it not yet exists
128138
prefix = '/'.join(obj.key.split('/')[0:-1])[len(os.environ['REPO_DIR']):]
129-
if not os.path.exists(repo.repodir+prefix):
130-
os.makedirs(repo.repodir+prefix)
139+
create_new_dir_if_not_exist(repo.repodir+prefix)
131140
#Download file to repodir
132141
path = repo.repodir + fname
133142
s3c.download_file(os.environ['BUCKET_NAME'], obj.key, path)
@@ -139,15 +148,14 @@ def check_changed_files(repo):
139148
print('File %s added to metadata'%(obj.key))
140149
else:
141150
print('File %s is already in metadata'%(obj.key))
142-
files.append(obj.key)
143151

144152
removedPkgs = []
145153
for f in cache:
146154
if f.endswith('.rpm') and os.environ['REPO_DIR']+f not in files:
147-
print('removing ' + os.environ['REPO_DIR']+f)
148-
repo, _ = remove_pkg(repo, cache, f)
155+
print('removing ' +f)
156+
repo = remove_pkg(repo, cache, f)
149157
removedPkgs.append(f)
150-
158+
151159
for removed in removedPkgs:
152160
del cache[removed]
153161
return repo, cache
@@ -163,7 +171,7 @@ def remove_pkg(repo, cache, key):
163171
print('%s has been removed from metadata' % (filename))
164172
else:
165173
print('Tried to delete %s entry but was not found in cache' % (filename))
166-
return repo, cache
174+
return repo
167175

168176
def sign_md_file(repo):
169177
'''

rpm/s3rpm_test.py

Lines changed: 114 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -2,130 +2,184 @@
22
from unittest.mock import MagicMock
33
from unittest.mock import mock_open
44
from unittest.mock import patch
5+
from unittest.mock import PropertyMock
6+
57
import s3rpm
68

7-
from pyrpm.tools.createrepo import YumRepository
9+
import botocore
810
import os
911
import json
1012
import shutil
11-
import gnupg
1213

13-
class S3AptTest(unittest.TestCase):
14+
class SubFunctionsTest(unittest.TestCase):
1415

1516
def setUp(self):
1617
os.environ['BUCKET_NAME'] = 'bucket'
17-
os.environ['REPO_DIR'] = 'test/repo'
18+
os.environ['REPO_DIR'] = 'test_s3rpm'
1819
os.environ['GPG_KEY'] = ''
1920
os.environ['PUBLIC'] = 'True'
2021
os.environ['GPG_PASS']='123'
21-
22+
23+
def tearDown(self):
24+
if os.path.exists('test_s3rpm'):
25+
shutil.rmtree('test_s3rpm')
2226

2327
def test_public_private(self):
2428
os.environ['PUBLIC'] = 'True'
25-
assert s3rpm.get_public() == 'public-read'
29+
self.assertEqual(s3rpm.get_public(), 'public-read')
2630

2731
os.environ['PUBLIC'] = ''
28-
assert s3rpm.get_public() == 'private'
32+
self.assertEqual(s3rpm.get_public(), 'private')
2933

3034
os.environ['PUBLIC'] = 'False'
31-
assert s3rpm.get_public() == 'private'
35+
self.assertEqual(s3rpm.get_public(), 'private')
3236

3337

3438
@patch('s3rpm.boto3')
3539
def test_file_existance(self, s3_mock):
3640
ret = s3rpm.check_bucket_file_existance('path')
37-
assert ret == True
41+
self.assertEqual(ret, True)
3842
s3_mock.resource().Object.assert_called_with("bucket", "path")
3943
s3_mock.resource().Object().load.assert_called_with()
4044

45+
#404 error
46+
p = PropertyMock(side_effect=botocore.exceptions.ClientError({'Error':{'Code': '404','Message':'no msg'}}, 'aa'))
47+
s3_mock.resource().Object().load = p
4148

49+
ret = s3rpm.check_bucket_file_existance('path')
50+
self.assertEqual(ret, False)
51+
#non404 error
52+
p = PropertyMock(side_effect=botocore.exceptions.ClientError({'Error':{'Code': '403','Message':'no msg'}}, 'aa'))
53+
s3_mock.resource().Object().load = p
54+
55+
with self.assertRaises(botocore.exceptions.ClientError):
56+
s3rpm.check_bucket_file_existance('path')
57+
58+
@patch('s3rpm.YumRepository')
4259
@patch('s3rpm.boto3')
4360
@patch('s3rpm.check_bucket_file_existance')
44-
def test_cache(self, check_mock, s3_mock):
45-
repo = YumRepository('test/repo/')
46-
cache = '{"/pkgname":"ID"}'
61+
def test_cache(self, check_mock, s3_mock, yum_mock):
62+
yum_mock = MagicMock(repodir='test_s3rpm/')
63+
cache = '{"pkgname" : "ID"}'
64+
repo = yum_mock
4765
m = mock_open(read_data=cache)
4866
check_mock.return_value = True
4967

5068
with patch('s3rpm.open', m):
5169
cachenew = s3rpm.get_cache(repo)
52-
assert json.loads(cache) == cachenew
70+
s3_mock.client().download_file.assert_called_with('bucket', 'test_s3rpm/repo_cache', 'test_s3rpm/repo_cache')
71+
self.assertEqual(json.loads(cache), cachenew)
5372

5473
check_mock.return_value = False
5574

5675
cachenew = s3rpm.get_cache(repo)
57-
assert cachenew == {}
58-
76+
self.assertEqual(cachenew, {})
5977

78+
@patch('s3rpm.YumRepository')
79+
@patch('s3rpm.YumPackage')
6080
@patch('s3rpm.get_cache')
6181
@patch('s3rpm.boto3')
62-
def test_new_files(self, s3_mock, cache_mock):
63-
cache_mock.return_value = {"/pkgname-0.3.7-x86_64.rpm": "7cd368172d218ed2001ad7306ff74c727f0b1d7bfa5433d9b265e7830bf60184"}
64-
repo = YumRepository('test/repo/')
65-
repo.read()
66-
cache = {"/pkgname-0.3.7-x86_64.rpm": "7cd368172d218ed2001ad7306ff74c727f0b1d7bfa5433d9b265e7830bf60184", "/pkgname-0.3.8-x86_64.rpm": "edcdbd077673a759585b1ebd4589d900c230a63e2c91c787861bcdcec9004707"}
82+
def test_new_files(self, s3_mock, cache_mock, yump_mock, yum_mock):
83+
84+
cache_mock.return_value = {"/pkgname-0.3.7-x86_64.rpm": "test_id1"}
85+
yum_mock = MagicMock(repodir='test_s3rpm/')
86+
repo = yum_mock
87+
yump_mock.return_value = MagicMock(checksum='test_id2')
88+
cache = {"/pkgname-0.3.7-x86_64.rpm": "test_id1", "/pkgname-0.3.8-x86_64.rpm": "test_id2"}
89+
90+
91+
s3_mock.resource().Bucket().objects.filter.return_value = [MagicMock(key='test.file'),MagicMock(key='test_s3rpm/pkgname-0.3.8-x86_64.rpm'), MagicMock(key='test_s3rpm/pkgname-0.3.7-x86_64.rpm')]
92+
m = mock_open(read_data='')
93+
with patch('s3rpm.open', m):
94+
reponew, cachenew = s3rpm.check_changed_files(repo)
6795

68-
s3_mock.resource().Bucket().objects.filter.return_value = [MagicMock(key='test.file'),MagicMock(key='test/repo/pkgname-0.3.8-x86_64.rpm'), MagicMock(key='test/repo/pkgname-0.3.7-x86_64.rpm')]
69-
reponew, cachenew = s3rpm.check_changed_files(repo)
96+
self.assertEqual(cache, cachenew)
97+
self.assertEqual(yum_mock.add_package.call_count, 1)
7098

71-
assert cache == cachenew
72-
self.assertEqual(len(list(reponew.packages())), 2)
7399

74-
100+
@patch('s3rpm.YumRepository')
75101
@patch('s3rpm.get_cache')
76102
@patch('s3rpm.boto3')
77-
def test_delete_files(self, s3_mock, cache_mock):
78-
cache_mock.return_value = {"/pkgname-0.3.7-x86_64.rpm": "7cd368172d218ed2001ad7306ff74c727f0b1d7bfa5433d9b265e7830bf60184"}
79-
repo = YumRepository('test/repo/')
103+
def test_delete_files(self, s3_mock, cache_mock, yum_mock):
104+
cache_mock.return_value = {"/pkgname-0.3.7-x86_64.rpm": "test_id1"}
105+
yum_mock = MagicMock(repodir='test_s3rpm/')
106+
repo = yum_mock
80107
cache = {}
81108

82109
s3_mock.resource().Bucket().objects.filter.return_value = [MagicMock(key='test.file')]
83-
reponew, cachenew = s3rpm.check_changed_files(repo)
84-
assert cache == cachenew
85-
self.assertEqual(len(list(reponew.packages())), 0)
110+
_, cachenew = s3rpm.check_changed_files(repo)
111+
self.assertEqual(cache, cachenew)
112+
self.assertEqual(yum_mock.remove_package.call_count, 1)
113+
114+
@patch('s3rpm.YumRepository')
115+
@patch('s3rpm.gnupg')
116+
@patch('s3rpm.boto3')
117+
def test_gpg(self, s3_mock, gpg_mock, yum_mock):
118+
os.environ['GPG_KEY'] = 'KeyNowExists'
119+
m = mock_open()
120+
repo = yum_mock()
121+
with patch('s3rpm.open', m):
122+
s3rpm.sign_md_file(repo)
123+
gpg_mock.GPG().sign_file.assert_called_with(s3rpm.open(), binary=False, clearsign=True, detach=True, passphrase='123')
124+
s3_mock.resource().Object().put.assert_called_with(ACL='public-read', Body=str(gpg_mock.GPG().sign_file()))
125+
126+
def test_create_dir(self):
127+
ret = s3rpm.create_new_dir_if_not_exist('test_s3rpm/testfolder')
128+
self.assertEqual(True, ret)
129+
ret = s3rpm.create_new_dir_if_not_exist('test_s3rpm/testfolder')
130+
self.assertEqual(False, ret)
86131

87132

88-
@patch('s3rpm.shutil')
133+
class HandlerTest(unittest.TestCase):
134+
def setUp(self):
135+
os.environ['BUCKET_NAME'] = 'bucket'
136+
os.environ['REPO_DIR'] = 'test_s3rpm'
137+
os.environ['GPG_KEY'] = ''
138+
os.environ['PUBLIC'] = 'True'
139+
os.environ['GPG_PASS']='123'
140+
self.m = mock_open(read_data='')
141+
142+
def tearDown(self):
143+
if os.path.exists('test_s3rpm'):
144+
shutil.rmtree('test_s3rpm')
89145
@patch('s3rpm.get_cache')
90146
@patch('s3rpm.YumRepository')
91147
@patch('s3rpm.boto3')
92-
def test_hander(self, s3_mock, repo_mock, cache_mock, shutil_mock):
148+
def test_defined_repodir(self, s3_mock, yum_mock, cache_mock, ):
93149
cache_mock.return_value = {"pkgname":"ID"}
94-
os.environ['REPO_DIR'] = '/test/repo/'
95150

96-
repo_mock.return_value = YumRepository('test/repo/')
97-
m = mock_open(read_data='')
98-
with patch('s3rpm.open', m):
151+
yum_mock.return_value = MagicMock(repodir='test_s3rpm/')
152+
with patch('s3rpm.open', self.m):
99153
s3rpm.lambda_handler(S3_EVENT, {})
100154
self.assertEqual(len(s3_mock.resource().Object().put.mock_calls), 5)
101-
self.assertEqual(os.environ['REPO_DIR'],'test/repo')
102-
155+
self.assertEqual(os.environ['REPO_DIR'],'test_s3rpm')
156+
157+
@patch('s3rpm.gnupg')
158+
@patch('s3rpm.shutil')
159+
@patch('s3rpm.get_cache')
160+
@patch('s3rpm.YumRepository')
161+
@patch('s3rpm.boto3')
162+
def test_gpg_test(self, s3_mock, yum_mock, cache_mock, sh_mock, gpg_mock):
163+
cache_mock.return_value = {"pkgname":"ID"}
164+
165+
os.environ['GPG_KEY'] = 'KeyNowExists'
103166
check = MagicMock()
104167
check.return_value = False
105-
repo_mock.return_value = YumRepository('test/testrepo/')
106-
with patch('s3rpm.open', m):
168+
yum_mock.return_value = MagicMock(repodir='test_s3rpm/testrepo/')
169+
with patch('s3rpm.open', self.m):
107170
with patch('s3rpm.check_bucket_file_existance', check):
108171
s3rpm.lambda_handler(S3_EVENT, {})
109-
assert os.path.exists('test/testrepo/repodata/') == True
110-
if os.path.exists('test/testrepo/repodata/'):
111-
shutil.rmtree('test/testrepo/repodata/')
172+
gpg_mock.GPG().sign_file.assert_called_with(s3rpm.open(), binary=False, clearsign=True, detach=True, passphrase='123')
173+
assert os.path.exists('test_s3rpm/testrepo/') == True
112174

113-
114-
@patch('s3rpm.gnupg')
115175
@patch('s3rpm.boto3')
116-
def test_gpg(self, s3_mock, gpg_mock):
117-
repo = YumRepository('test/repo')
118-
os.environ['GPG_KEY'] = 'test/sec.key'
119-
m = mock_open()
120-
with patch('s3rpm.open', m):
121-
s3rpm.sign_md_file(repo)
122-
gpg_mock.GPG().sign_file.assert_called_with(s3rpm.open(), binary=False, clearsign=True, detach=True, passphrase='123')
123-
124-
S3_EVENT = {"Records":[{"s3": {"object": {"key": "test/repo/pkgname-0.3.8-x86_64.rpm",},"bucket": {"name": "bucket",},},"eventName": "ObjectCreated:Put",}]}
176+
def test_bad_repo_dir_and_bucket_name(self, s3_mock):
177+
os.environ['REPO_DIR'] = '/test/repo/'
178+
os.environ['BUCKET_NAME'] = 'iamfakebucket'
179+
s3rpm.lambda_handler(S3_EVENT, {})
180+
self.assertEqual(os.environ['REPO_DIR'], 'test/repo')
181+
s3_mock.client.assert_called_with('s3')
182+
self.assertEqual(len(s3_mock.resource().Object().put.mock_calls), 0)
183+
S3_EVENT = {"Records":[{"s3": {"object": {"key": "test_s3rpm/repo/pkgname-0.3.8-x86_64.rpm",},"bucket": {"name": "bucket",},},"eventName": "ObjectCreated:Put"}]}
125184
if __name__ == '__main__':
126185
unittest.main()
127-
128-
def createrepo():
129-
repo = YumRepository('test/repo/')
130-
repo.add_package(YumPackage(open('test/repo/pkgname-0.3.7-x86_64.rpm', 'rb')))
131-
repo.save()
-547 KB
Binary file not shown.
-547 KB
Binary file not shown.

rpm/test/repo/repo_cache

Lines changed: 0 additions & 1 deletion
This file was deleted.
-232 Bytes
Binary file not shown.
-231 Bytes
Binary file not shown.
-600 Bytes
Binary file not shown.

rpm/test/repo/repodata/repomd.xml

Lines changed: 0 additions & 2 deletions
This file was deleted.

0 commit comments

Comments
 (0)