Skip to content

Commit 023397b

Browse files
author
Janez Justin
committed
FIX tests
1 parent 09e20a3 commit 023397b

File tree

9 files changed

+134
-76
lines changed

9 files changed

+134
-76
lines changed

rpm/s3rpm.py

Lines changed: 22 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,8 @@ 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/')
32+
print(repo.repodir)
3533
# if repodata files exist download them to /tmp where we can manipulate with them
3634
if exists:
3735
print('repodata already exists, old files will be overwriten')
@@ -61,11 +59,23 @@ def lambda_handler(event, context):
6159

6260
#Let us clean up
6361
shutil.rmtree(repo.repodir)
64-
shutil.rmtree('/tmp/gpgdocs')
62+
if os.path.exists('/tmp/gpgdocs'):
63+
shutil.rmtree('/tmp/gpgdocs')
6564

6665
print('METADATA GENERATION COMPLETED')
6766

67+
def create_new_dir_if_not_exist(path):
68+
"""
69+
Creates dir at 'path' if it does not exist
6870
71+
returns true on success
72+
returns false if dir already exists
73+
"""
74+
if not os.path.exists(path):
75+
os.makedirs(path)
76+
return True
77+
else:
78+
return False
6979
def check_bucket_file_existance(path):
7080
"""
7181
checks if file exsist in bucket
@@ -85,7 +95,7 @@ def check_bucket_file_existance(path):
8595

8696
def get_public():
8797
"""
88-
If env variable PUBLIC is set to true returns 'public read'
98+
If env variable PUBLIC is set to true returns 'public-read', else returns 'private'
8999
"""
90100
if os.environ['PUBLIC'] == 'True' :
91101
acl = 'public-read'
@@ -118,6 +128,7 @@ def check_changed_files(repo):
118128
files = []
119129
#cycle through all objects ending with .rpm in REPO_DIR and check if they are already in repodata, if not add them
120130
for obj in s3.Bucket(os.environ['BUCKET_NAME']).objects.filter(Prefix=os.environ['REPO_DIR']):
131+
files.append(obj.key)
121132
if not obj.key.endswith(".rpm"):
122133
print('skipping %s - not rpm file' %(obj.key))
123134
continue
@@ -126,8 +137,7 @@ def check_changed_files(repo):
126137
s3c = boto3.client('s3')
127138
#Create path to folder where to download file, if it not yet exists
128139
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)
140+
create_new_dir_if_not_exist(repo.repodir+prefix)
131141
#Download file to repodir
132142
path = repo.repodir + fname
133143
s3c.download_file(os.environ['BUCKET_NAME'], obj.key, path)
@@ -139,15 +149,14 @@ def check_changed_files(repo):
139149
print('File %s added to metadata'%(obj.key))
140150
else:
141151
print('File %s is already in metadata'%(obj.key))
142-
files.append(obj.key)
143152

144153
removedPkgs = []
145154
for f in cache:
146155
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)
156+
print('removing ' +f)
157+
repo = remove_pkg(repo, cache, f)
149158
removedPkgs.append(f)
150-
159+
151160
for removed in removedPkgs:
152161
del cache[removed]
153162
return repo, cache
@@ -163,7 +172,7 @@ def remove_pkg(repo, cache, key):
163172
print('%s has been removed from metadata' % (filename))
164173
else:
165174
print('Tried to delete %s entry but was not found in cache' % (filename))
166-
return repo, cache
175+
return repo
167176

168177
def sign_md_file(repo):
169178
'''

rpm/s3rpm_test.py

Lines changed: 112 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -2,130 +2,182 @@
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'
2122

22-
2323
def test_public_private(self):
2424
os.environ['PUBLIC'] = 'True'
25-
assert s3rpm.get_public() == 'public-read'
25+
self.assertEqual(s3rpm.get_public(), 'public-read')
2626

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

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

3333

3434
@patch('s3rpm.boto3')
3535
def test_file_existance(self, s3_mock):
3636
ret = s3rpm.check_bucket_file_existance('path')
37-
assert ret == True
37+
self.assertEqual(ret, True)
3838
s3_mock.resource().Object.assert_called_with("bucket", "path")
3939
s3_mock.resource().Object().load.assert_called_with()
4040

41+
#404 error
42+
p = PropertyMock(side_effect=botocore.exceptions.ClientError({'Error':{'Code': '404','Message':'no msg'}}, 'aa'))
43+
s3_mock.resource().Object().load = p
4144

45+
ret = s3rpm.check_bucket_file_existance('path')
46+
self.assertEqual(ret, False)
47+
#non404 error
48+
p = PropertyMock(side_effect=botocore.exceptions.ClientError({'Error':{'Code': '403','Message':'no msg'}}, 'aa'))
49+
s3_mock.resource().Object().load = p
50+
51+
with self.assertRaises(botocore.exceptions.ClientError):
52+
s3rpm.check_bucket_file_existance('path')
53+
54+
@patch('s3rpm.YumRepository')
4255
@patch('s3rpm.boto3')
4356
@patch('s3rpm.check_bucket_file_existance')
44-
def test_cache(self, check_mock, s3_mock):
45-
repo = YumRepository('test/repo/')
46-
cache = '{"/pkgname":"ID"}'
57+
def test_cache(self, check_mock, s3_mock, yum_mock):
58+
yum_mock = MagicMock(repodir='test_s3rpm/')
59+
cache = '{"pkgname" : "ID"}'
60+
repo = yum_mock
4761
m = mock_open(read_data=cache)
4862
check_mock.return_value = True
4963

5064
with patch('s3rpm.open', m):
5165
cachenew = s3rpm.get_cache(repo)
52-
assert json.loads(cache) == cachenew
66+
s3_mock.client().download_file.assert_called_with('bucket', 'test_s3rpm/repo_cache', 'test_s3rpm/repo_cache')
67+
self.assertEqual(json.loads(cache), cachenew)
5368

5469
check_mock.return_value = False
5570

5671
cachenew = s3rpm.get_cache(repo)
57-
assert cachenew == {}
58-
72+
self.assertEqual(cachenew, {})
5973

74+
@patch('s3rpm.YumRepository')
75+
@patch('s3rpm.YumPackage')
6076
@patch('s3rpm.get_cache')
6177
@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"}
78+
def test_new_files(self, s3_mock, cache_mock, yump_mock, yum_mock):
79+
80+
cache_mock.return_value = {"/pkgname-0.3.7-x86_64.rpm": "test_id1"}
81+
yum_mock = MagicMock(repodir='test_s3rpm/')
82+
repo = yum_mock
83+
yump_mock.return_value = MagicMock(checksum='test_id2')
84+
cache = {"/pkgname-0.3.7-x86_64.rpm": "test_id1", "/pkgname-0.3.8-x86_64.rpm": "test_id2"}
85+
86+
87+
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')]
88+
m = mock_open(read_data='')
89+
with patch('s3rpm.open', m):
90+
reponew, cachenew = s3rpm.check_changed_files(repo)
6791

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)
92+
self.assertEqual(cache, cachenew)
93+
self.assertEqual(yum_mock.add_package.call_count, 1)
7094

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

74-
96+
@patch('s3rpm.YumRepository')
7597
@patch('s3rpm.get_cache')
7698
@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/')
99+
def test_delete_files(self, s3_mock, cache_mock, yum_mock):
100+
cache_mock.return_value = {"/pkgname-0.3.7-x86_64.rpm": "test_id1"}
101+
yum_mock = MagicMock(repodir='test_s3rpm/')
102+
repo = yum_mock
80103
cache = {}
81104

82105
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)
106+
_, cachenew = s3rpm.check_changed_files(repo)
107+
self.assertEqual(cache, cachenew)
108+
self.assertEqual(yum_mock.remove_package.call_count, 1)
109+
110+
@patch('s3rpm.YumRepository')
111+
@patch('s3rpm.gnupg')
112+
@patch('s3rpm.boto3')
113+
def test_gpg(self, s3_mock, gpg_mock, yum_mock):
114+
os.environ['GPG_KEY'] = 'KeyNowExists'
115+
m = mock_open()
116+
repo = yum_mock()
117+
with patch('s3rpm.open', m):
118+
s3rpm.sign_md_file(repo)
119+
gpg_mock.GPG().sign_file.assert_called_with(s3rpm.open(), binary=False, clearsign=True, detach=True, passphrase='123')
120+
s3_mock.resource().Object().put.assert_called_with(ACL='public-read', Body=str(gpg_mock.GPG().sign_file()))
121+
122+
def test_create_dir(self):
123+
ret = s3rpm.create_new_dir_if_not_exist('test_s3rpm/testfolder')
124+
self.assertEqual(True, ret)
125+
ret = s3rpm.create_new_dir_if_not_exist('test_s3rpm/testfolder')
126+
self.assertEqual(False, ret)
127+
if os.path.exists('test_s3rpm/'):
128+
shutil.rmtree('test_s3rpm/')
86129

87130

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

96-
repo_mock.return_value = YumRepository('test/repo/')
97-
m = mock_open(read_data='')
98-
with patch('s3rpm.open', m):
149+
yum_mock.return_value = MagicMock(repodir='test_s3rpm/')
150+
with patch('s3rpm.open', self.m):
99151
s3rpm.lambda_handler(S3_EVENT, {})
100152
self.assertEqual(len(s3_mock.resource().Object().put.mock_calls), 5)
101-
self.assertEqual(os.environ['REPO_DIR'],'test/repo')
102-
153+
self.assertEqual(os.environ['REPO_DIR'],'test_s3rpm')
154+
155+
@patch('s3rpm.gnupg')
156+
@patch('s3rpm.shutil')
157+
@patch('s3rpm.get_cache')
158+
@patch('s3rpm.YumRepository')
159+
@patch('s3rpm.boto3')
160+
def test_gpg_test(self, s3_mock, yum_mock, cache_mock, sh_mock, gpg_mock):
161+
cache_mock.return_value = {"pkgname":"ID"}
162+
163+
os.environ['GPG_KEY'] = 'KeyNowExists'
103164
check = MagicMock()
104165
check.return_value = False
105-
repo_mock.return_value = YumRepository('test/testrepo/')
106-
with patch('s3rpm.open', m):
166+
yum_mock.return_value = MagicMock(repodir='test_s3rpm/testrepo/')
167+
with patch('s3rpm.open', self.m):
107168
with patch('s3rpm.check_bucket_file_existance', check):
108169
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/')
170+
gpg_mock.GPG().sign_file.assert_called_with(s3rpm.open(), binary=False, clearsign=True, detach=True, passphrase='123')
171+
assert os.path.exists('test_s3rpm/testrepo/') == True
112172

113-
114-
@patch('s3rpm.gnupg')
115173
@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",}]}
174+
def test_bad_repo_dir_and_bucket_name(self, s3_mock):
175+
os.environ['REPO_DIR'] = '/test/repo/'
176+
os.environ['BUCKET_NAME'] = 'iamfakebucket'
177+
s3rpm.lambda_handler(S3_EVENT, {})
178+
self.assertEqual(os.environ['REPO_DIR'], 'test/repo')
179+
s3_mock.client.assert_called_with('s3')
180+
self.assertEqual(len(s3_mock.resource().Object().put.mock_calls), 0)
181+
S3_EVENT = {"Records":[{"s3": {"object": {"key": "test_s3rpm/repo/pkgname-0.3.8-x86_64.rpm",},"bucket": {"name": "bucket",},},"eventName": "ObjectCreated:Put",}]}
125182
if __name__ == '__main__':
126183
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)