1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

352

353

354

355

356

357

358

359

360

361

362

363

364

365

366

367

368

369

370

371

372

373

374

375

376

377

378

379

380

381

382

383

384

385

386

387

388

389

390

391

392

393

394

395

396

397

398

399

400

401

402

403

404

405

406

407

408

409

410

411

412

413

414

415

416

417

418

419

420

421

422

423

424

425

426

427

428

429

430

431

432

433

434

435

436

437

438

439

440

441

442

443

444

445

446

447

448

449

450

451

452

453

454

455

456

457

458

459

460

461

462

463

464

465

466

467

468

469

470

471

472

473

474

475

# -*- coding: utf-8 -*- 

 

# Copyright 2014-2018 The Distro Tracker Developers 

# See the COPYRIGHT file at the top-level directory of this distribution and 

# at https://deb.li/DTAuthors 

# 

# This file is part of Distro Tracker. It is subject to the license terms 

# in the LICENSE file found in the top-level directory of this 

# distribution and at https://deb.li/DTLicense. No part of Distro Tracker, 

# including this file, may be copied, modified, propagated, or distributed 

# except according to the terms contained in the LICENSE file. 

 

""" 

Distro Tracker test infrastructure. 

""" 

 

import codecs 

import gzip 

import inspect 

import json 

import lzma 

import os 

import os.path 

import shutil 

import tempfile 

from unittest import mock 

 

from bs4 import BeautifulSoup as soup 

 

import django.test 

from django.conf import settings 

from django.contrib.staticfiles.testing import StaticLiveServerTestCase 

from django.test.signals import setting_changed 

 

import requests 

 

from distro_tracker.accounts.models import UserEmail 

from distro_tracker.core.models import ( 

Architecture, 

BinaryPackageName, 

ContributorName, 

PackageData, 

PackageName, 

Repository, 

SourcePackage, 

SourcePackageName, 

) 

from distro_tracker.core.utils.packages import package_hashdir 

 

from django_email_accounts.models import User 

 

 

class TempDirsMixin(object): 

""" 

Diverts all distro-tracker path settings to make them point 

to temporary directories while testing. 

""" 

 

DISTRO_TRACKER_PATH_SETTINGS = { 

'STATIC_ROOT': 'static', 

'MEDIA_ROOT': 'media', 

'DISTRO_TRACKER_CACHE_DIRECTORY': 'cache', 

'DISTRO_TRACKER_KEYRING_DIRECTORY': 'keyring', 

'DISTRO_TRACKER_TEMPLATE_DIRECTORY': 'templates', 

'DISTRO_TRACKER_LOG_DIRECTORY': 'logs', 

'DISTRO_TRACKER_MAILDIR_DIRECTORY': 'maildir', 

} 

 

def _backup_settings(self, name): 

self._settings_copy[name] = getattr(settings, name) 

 

def _restore_settings(self): 

for key, value in self._settings_copy.items(): 

setattr(settings, key, value) 

 

def __call__(self, result=None): 

""" 

Wrapper around __call__ to perform temporary directories setup. 

This means that user-defined Test Cases aren't required to 

include a call to super().setUp(). 

""" 

self._settings_copy = {} 

self.addCleanup(self._restore_settings) 

self._backup_settings('DISTRO_TRACKER_DATA_PATH') 

tempdir = tempfile.mkdtemp(prefix='distro-tracker-tests-') 

self.addCleanup(shutil.rmtree, tempdir, ignore_errors=True) 

setattr(settings, 'DISTRO_TRACKER_DATA_PATH', tempdir) 

for name, dirname in self.DISTRO_TRACKER_PATH_SETTINGS.items(): 

self._backup_settings(name) 

dirname = os.path.join(tempdir, dirname) 

setattr(settings, name, dirname) 

os.mkdir(dirname) 

return super(TempDirsMixin, self).__call__(result) 

 

 

class TestCaseHelpersMixin(object): 

""" 

Helpers method injected into distro_tracker's ``*TestCase`` objects. 

""" 

 

def get_test_data_path(self, name): 

""" 

Returns an absolute path name of file within the tests-data 

subdirectory in the calling TestCase. 

""" 

return os.path.join(os.path.dirname(inspect.getabsfile(self.__class__)), 

'tests-data', name) 

 

def add_test_template_dir(self, name='tests-templates'): 

template_dir = self.get_test_data_path(name) 

settings.TEMPLATES[0]['DIRS'].append(template_dir) 

setting_changed.send(sender=self.__class__, setting='TEMPLATES', 

value=settings.TEMPLATES, enter=True) 

 

def cleanup_test_template_dir(): 

settings.TEMPLATES[0]['DIRS'].remove(template_dir) 

setting_changed.send(sender=self.__class__, setting='TEMPLATES', 

value=settings.TEMPLATES, enter=False) 

 

self.addCleanup(cleanup_test_template_dir) 

 

def get_temporary_directory(self, prefix=None, suffix=None): 

tempdir = tempfile.mkdtemp(prefix=prefix, suffix=suffix) 

self.addCleanup(shutil.rmtree, tempdir, ignore_errors=True) 

 

return tempdir 

 

def mock_http_request( 

self, requests_location='distro_tracker.core.utils.http.requests', 

**kwargs): 

patcher = mock.patch(requests_location) 

self._mocked_requests = patcher.start() 

self._http_responses = {} 

 

def mocked_get(url, params=None, **kwargs): 

response = self._mocked_requests.models.Response() 

if url in self._http_responses: 

response_data = self._http_responses[url] 

elif None in self._http_responses: 

response_data = self._http_responses[None] 

else: 

response_data = { 

'text': '', 

'status_code': 404, 

'headers': None, 

} 

 

if 'content' in response_data: 

content = response_data['content'] 

text = codecs.encode(content, 'base64').decode('ascii') 

encoding = 'base64' 

else: 

text = response_data['text'] 

content = text.encode('utf-8') 

encoding = 'utf-8' 

 

response.text = text 

response.content = content 

response.encoding = encoding 

response.headers = response_data['headers'] or {} 

response.status_code = response_data['status_code'] 

response.iter_lines.return_value = text.splitlines() 

response.ok = response_data['status_code'] < 400 

response.__bool__.return_value = response.ok 

 

if response_data['status_code'] >= 400: 

response.raise_for_status.side_effect = ( 

requests.exceptions.HTTPError(response=response)) 

else: 

response.raise_for_status.return_value = None 

 

response.iter_content.side_effect = NotImplementedError() 

response.json.side_effect = NotImplementedError() 

 

# Avoid automatic creation of new attributes during tests 

mock.seal(response) 

 

return response 

 

self._mocked_requests.get.side_effect = mocked_get 

self.addCleanup(patcher.stop) 

 

if kwargs: 

self.set_http_get_response(**kwargs) 

 

def set_http_get_response(self, url=None, text='', status_code=200, 

headers=None, json_data=None, content=None, 

compress_with=None): 

response_data = { 

'status_code': status_code, 

'headers': headers, 

} 

if json_data is not None: 

text = json.dumps(json_data) 

 

def compress(data): 

if compress_with == 'gzip': 

return gzip.compress(data) 

elif compress_with == 'xz': 

return lzma.compress(data) 

else: 

raise NotImplementedError( 

'set_http_get_response does not support {} as ' 

'compression method'.format(compress_with)) 

 

if content: 

if compress_with: 

response_data['content'] = compress(content) 

else: 

response_data['content'] = content 

else: 

if compress_with: 

response_data['content'] = compress(text.encode('utf-8')) 

else: 

response_data['text'] = text 

 

self._http_responses[url] = response_data 

 

def import_key_into_keyring(self, filename): 

""" 

Imports a key from an ascii armored file located in tests-data/keys/ 

into Distro Tracker's keyrings/. 

""" 

import gpg 

 

old = os.environ.get('GNUPGHOME', None) 

os.environ['GNUPGHOME'] = settings.DISTRO_TRACKER_KEYRING_DIRECTORY 

 

file_path = self.get_test_data_path('keys/' + filename) 

keydata = gpg.Data() 

keydata.new_from_file(file_path) 

 

with gpg.Context() as ctx: 

ctx.op_import(keydata) 

 

236 ↛ exitline 236 didn't return from function 'import_key_into_keyring', because the condition on line 236 was never false if old: 

os.environ['GNUPGHOME'] = old 

 

 

class DatabaseMixin(object): 

""" 

Database-related assertions injected into distro_tracker's ``*TestCase`` 

objects. 

""" 

 

def assertDoesNotExist(self, obj): 

with self.assertRaises(obj.__class__.DoesNotExist): 

obj.__class__.objects.get(pk=obj.id) 

 

def assertDoesExist(self, obj): 

try: 

self.assertIsNotNone(obj.__class__.objects.get(pk=obj.id)) 

except obj.__class__.DoesNotExist as error: 

raise AssertionError(error) 

 

def create_source_package(self, **kwargs): 

""" 

Creates a source package and any related object requested through the 

keyword arguments. The following arguments are supported: 

- name 

- version 

- directory 

- dsc_file_name 

- maintainer (dict with 'name' and 'email') 

- uploaders (list of emails) 

- architectures (list of architectures) 

- binary_packages (list of package names) 

- repository (shorthand of a repository) 

- repositories (list of repositories' shorthand) 

- data (dict used to generate associated PackageData) 

 

If the shorthand of the requested repository is 'default', then 

its default field will be set to True. 

 

:return: the created source package 

:rtype: :class:`~distro_tracker.core.models.SourcePackage` 

""" 

name = kwargs.get('name', 'test-package') 

version = kwargs.get('version', '1') 

 

fields = {} 

fields['source_package_name'] = \ 

SourcePackageName.objects.get_or_create(name=name)[0] 

fields['version'] = version 

fields['dsc_file_name'] = kwargs.get('dsc_file_name', 

'%s_%s.dsc' % (name, version)) 

fields['directory'] = kwargs.get( 

'directory', 'pool/main/%s/%s' % (package_hashdir(name), name)) 

 

if 'maintainer' in kwargs: 

maintainer = kwargs['maintainer'] 

maintainer_email = UserEmail.objects.get_or_create( 

email=maintainer['email'])[0] 

fields['maintainer'] = ContributorName.objects.get_or_create( 

contributor_email=maintainer_email, 

name=maintainer.get('name', ''))[0] 

 

srcpkg = SourcePackage.objects.create(**fields) 

 

for architecture in kwargs.get('architectures', []): 

srcpkg.architectures.add( 

Architecture.objects.get_or_create(name=architecture)[0]) 

 

for uploader in kwargs.get('uploaders', []): 

contributor = ContributorName.objects.get_or_create( 

contributor_email=UserEmail.objects.get_or_create( 

email=uploader)[0])[0] 

srcpkg.uploaders.add(contributor) 

 

for binary in kwargs.get('binary_packages', []): 

srcpkg.binary_packages.add( 

BinaryPackageName.objects.get_or_create(name=binary)[0]) 

 

if 'repository' in kwargs: 

kwargs.setdefault('repositories', [kwargs['repository']]) 

for repo_shorthand in kwargs.get('repositories', []): 

self.add_to_repository(srcpkg, repo_shorthand) 

 

if 'data' in kwargs: 

self.add_package_data(srcpkg.source_package_name, **kwargs['data']) 

 

srcpkg.save() 

return srcpkg 

 

def add_to_repository(self, srcpkg, shorthand='default'): 

""" 

Add a source package to a repository. Creates the repository if it 

doesn't exist. 

 

If the shorthand of the requested repository is 'default', then 

its default field will be set to True. 

 

:param srcpkg: the source package to add to the repository 

:type srcpkg: :class:`~distro_tracker.core.models.SourcePackage` 

:param str shorthand: the shorthand of the repository 

 

:return: the repository entry that has been created 

:rtype: 

:class:`~distro_tracker.core.models.SourcePackageRepositoryEntry` 

""" 

repository, _ = Repository.objects.get_or_create( 

shorthand=shorthand, 

defaults={ 

'name': 'Test repository %s' % shorthand, 

'uri': 'http://localhost/debian', 

'suite': shorthand, 

'codename': shorthand, 

'components': ['main', 'contrib', 'non-free'], 

'default': True if shorthand == 'default' else False, 

} 

) 

return srcpkg.repository_entries.create(repository=repository, 

component='main') 

 

def remove_from_repository(self, srcpkg, shorthand='default'): 

""" 

Remove a source package from a repository. 

 

:param srcpkg: the source package to add to the repository 

:type srcpkg: :class:`~distro_tracker.core.models.SourcePackage` 

:param str shorthand: the shorthand of the repository 

""" 

return srcpkg.repository_entries.filter( 

repository__shorthand=shorthand).delete()[0] 

 

def add_package_data(self, pkgname, **kwargs): 

""" 

Creates PackageData objects associated to the package indicated 

in pkgname. Each named parameter results in PackageData instance 

with the `key` being the name of the parameter and the `value` 

being the value of the named parameter. 

 

:param pkgname: the name of the package to which we want to associate 

data 

:type pkgname: `str` or :class:`~distro_tracker.core.models.PackageName` 

""" 

if not isinstance(pkgname, PackageName): 

pkgname, _ = PackageName.objects.get_or_create(name=str(pkgname)) 

for key, value in kwargs.items(): 

PackageData.objects.create(package=pkgname, key=key, value=value) 

 

 

class SimpleTestCase(TempDirsMixin, TestCaseHelpersMixin, 

django.test.SimpleTestCase): 

pass 

 

 

class TestCase(TempDirsMixin, TestCaseHelpersMixin, DatabaseMixin, 

django.test.TestCase): 

pass 

 

 

@django.test.tag('transaction') 

class TransactionTestCase(TempDirsMixin, TestCaseHelpersMixin, 

DatabaseMixin, django.test.TransactionTestCase): 

pass 

 

 

class LiveServerTestCase(TempDirsMixin, TestCaseHelpersMixin, 

DatabaseMixin, StaticLiveServerTestCase): 

pass 

 

 

class TemplateTestsMixin(object): 

"""Helper methods to tests templates""" 

 

@staticmethod 

def html_contains_link(text, link): 

html = soup(text, 'html.parser') 

for a_tag in html.findAll('a', {'href': True}): 

if a_tag['href'] == link: 

return True 

return False 

 

def assertLinkIsInResponse(self, response, link): 

self.assertTrue(self.html_contains_link(response.content, link)) 

 

def assertLinkIsNotInResponse(self, response, link): 

self.assertFalse(self.html_contains_link(response.content, link)) 

 

 

class UserAuthMixin(object): 

""" 

Helpers methods to manage user authentication. 

One may define additional USERS before call self.setup_users() 

in self.setUp() 

""" 

USERS = { 

'john': {}, 

} 

 

def setup_users(self, login=False): 

""" 

Creates users defined in self.USERS and use the 'login' parameter as 

follows: 

* If False: no user login 

* If True: login with the only user defined 

* If a particular username: login with the user who owns the username 

""" 

self.users = {} 

for username in self.USERS: 

user_data = self._get_user_data(username) 

self.users[username] = User.objects.create_user(**user_data) 

444 ↛ exitline 444 didn't return from function 'setup_users', because the condition on line 444 was never false if login: 

username = None if login is True else login 

self.login(username) 

 

def login(self, username=None): 

""" 

Login with the user that owns the 'username' or with the only available 

user in self.users. If multiple users are available, you must specify 

the username or you will trigger a ValueError exception. 

""" 

if not username: 

455 ↛ 456line 455 didn't jump to line 456, because the condition on line 455 was never true if len(self.users) > 1: 

raise ValueError("multiple users but username not specified") 

username = list(self.users.keys())[0] 

user_data = self._get_user_data(username) 

self.client.login( 

username=user_data['main_email'], 

password=user_data['password'], 

) 

self.current_user = self.users[username] 

return self.current_user 

 

def get_user(self, username=None): 

467 ↛ 468line 467 didn't jump to line 468, because the condition on line 467 was never true if not username: 

return self.current_user 

return self.users[username] 

 

def _get_user_data(self, username): 

user_data = self.USERS[username].copy() 

user_data.setdefault('main_email', '{}@example.com'.format(username)) 

user_data.setdefault('password', '{}password'.format(username)) 

return user_data