This file is indexed.

/usr/lib/python2.7/dist-packages/pylxd/tests/models/test_container.py is in python-pylxd 2.2.6-0ubuntu1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
import json

import mock

from pylxd import exceptions, models
from pylxd.tests import testing


class TestContainer(testing.PyLXDTestCase):
    """Tests for pylxd.models.Container."""

    def test_all(self):
        """A list of all containers are returned."""
        containers = models.Container.all(self.client)

        self.assertEqual(1, len(containers))

    def test_get(self):
        """Return a container."""
        name = 'an-container'

        an_container = models.Container.get(self.client, name)

        self.assertEqual(name, an_container.name)

    def test_get_not_found(self):
        """LXDAPIException is raised when the container doesn't exist."""
        def not_found(request, context):
            context.status_code = 404
            return json.dumps({
                'type': 'error',
                'error': 'Not found',
                'error_code': 404})
        self.add_rule({
            'text': not_found,
            'method': 'GET',
            'url': r'^http://pylxd.test/1.0/containers/an-missing-container$',  # NOQA
        })

        name = 'an-missing-container'

        self.assertRaises(
            exceptions.LXDAPIException,
            models.Container.get, self.client, name)

    def test_get_error(self):
        """LXDAPIException is raised when the LXD API errors."""
        def not_found(request, context):
            context.status_code = 500
            return json.dumps({
                'type': 'error',
                'error': 'Not found',
                'error_code': 500})
        self.add_rule({
            'text': not_found,
            'method': 'GET',
            'url': r'^http://pylxd.test/1.0/containers/an-missing-container$',  # NOQA
        })

        name = 'an-missing-container'

        self.assertRaises(
            exceptions.LXDAPIException,
            models.Container.get, self.client, name)

    def test_create(self):
        """A new container is created."""
        config = {'name': 'an-new-container'}

        an_new_container = models.Container.create(
            self.client, config, wait=True)

        self.assertEqual(config['name'], an_new_container.name)

    def test_exists(self):
        """A container exists."""
        name = 'an-container'

        self.assertTrue(models.Container.exists(self.client, name))

    def test_not_exists(self):
        """A container exists."""
        def not_found(request, context):
            context.status_code = 404
            return json.dumps({
                'type': 'error',
                'error': 'Not found',
                'error_code': 404})
        self.add_rule({
            'text': not_found,
            'method': 'GET',
            'url': r'^http://pylxd.test/1.0/containers/an-missing-container$',  # NOQA
        })

        name = 'an-missing-container'

        self.assertFalse(models.Container.exists(self.client, name))

    def test_fetch(self):
        """A sync updates the properties of a container."""
        an_container = models.Container(
            self.client, name='an-container')

        an_container.sync()

        self.assertTrue(an_container.ephemeral)

    def test_fetch_not_found(self):
        """LXDAPIException is raised on a 404 for updating container."""
        def not_found(request, context):
            context.status_code = 404
            return json.dumps({
                'type': 'error',
                'error': 'Not found',
                'error_code': 404})
        self.add_rule({
            'text': not_found,
            'method': 'GET',
            'url': r'^http://pylxd.test/1.0/containers/an-missing-container$',  # NOQA
        })

        an_container = models.Container(
            self.client, name='an-missing-container')

        self.assertRaises(exceptions.LXDAPIException, an_container.sync)

    def test_fetch_error(self):
        """LXDAPIException is raised on error."""
        def not_found(request, context):
            context.status_code = 500
            return json.dumps({
                'type': 'error',
                'error': 'An bad error',
                'error_code': 500})
        self.add_rule({
            'text': not_found,
            'method': 'GET',
            'url': r'^http://pylxd.test/1.0/containers/an-missing-container$',  # NOQA
        })

        an_container = models.Container(
            self.client, name='an-missing-container')

        self.assertRaises(exceptions.LXDAPIException, an_container.sync)

    def test_update(self):
        """A container is updated."""
        an_container = models.Container(
            self.client, name='an-container')
        an_container.architecture = 1
        an_container.config = {}
        an_container.created_at = 1
        an_container.devices = {}
        an_container.ephemeral = 1
        an_container.expanded_config = {}
        an_container.expanded_devices = {}
        an_container.profiles = 1
        an_container.status = 1

        an_container.save(wait=True)

        self.assertTrue(an_container.ephemeral)

    def test_rename(self):
        an_container = models.Container(
            self.client, name='an-container')

        an_container.rename('an-renamed-container', wait=True)

        self.assertEqual('an-renamed-container', an_container.name)

    def test_delete(self):
        """A container is deleted."""
        # XXX: rockstar (21 May 2016) - This just executes
        # a code path. There should be an assertion here, but
        # it's not clear how to assert that, just yet.
        an_container = models.Container(
            self.client, name='an-container')

        an_container.delete(wait=True)

    @testing.requires_ws4py
    @mock.patch('pylxd.models.container._StdinWebsocket')
    @mock.patch('pylxd.models.container._CommandWebsocketClient')
    def test_execute(self, _CommandWebsocketClient, _StdinWebsocket):
        """A command is executed on a container."""
        fake_websocket = mock.Mock()
        fake_websocket.data = 'test\n'
        _StdinWebsocket.return_value = fake_websocket
        _CommandWebsocketClient.return_value = fake_websocket

        an_container = models.Container(
            self.client, name='an-container')

        result = an_container.execute(['echo', 'test'])

        self.assertEqual(0, result.exit_code)
        self.assertEqual('test\n', result.stdout)

    def test_execute_no_ws4py(self):
        """If ws4py is not installed, ValueError is raised."""
        from pylxd.models import container
        old_installed = container._ws4py_installed
        container._ws4py_installed = False

        def cleanup():
            container._ws4py_installed = old_installed
        self.addCleanup(cleanup)

        an_container = models.Container(
            self.client, name='an-container')

        self.assertRaises(ValueError, an_container.execute, ['echo', 'test'])

    @testing.requires_ws4py
    def test_execute_string(self):
        """A command passed as string raises a TypeError."""
        an_container = models.Container(
            self.client, name='an-container')

        self.assertRaises(TypeError, an_container.execute, 'apt-get update')

    def test_migrate(self):
        """A container is migrated."""
        from pylxd.client import Client

        client2 = Client(endpoint='http://pylxd2.test')
        an_container = models.Container(
            self.client, name='an-container')

        an_migrated_container = an_container.migrate(client2)

        self.assertEqual('an-container', an_migrated_container.name)
        self.assertEqual(client2, an_migrated_container.client)

    @mock.patch('pylxd.client._APINode.get')
    def test_migrate_local_client(self, get):
        """Migration from local clients is not supported."""
        # Mock out the _APINode for the local instance.
        response = mock.Mock()
        response.json.return_value = {'metadata': {'fake': 'response'}}
        response.status_code = 200
        get.return_value = response

        from pylxd.client import Client

        client2 = Client(endpoint='http+unix://pylxd2.test')
        an_container = models.Container(
            client2, name='an-container')

        self.assertRaises(ValueError, an_container.migrate, self.client)

    def test_publish(self):
        """Containers can be published."""
        self.add_rule({
            'text': json.dumps({
                'type': 'sync',
                'metadata': {
                    'id': 'operation-abc',
                    'metadata': {
                        'fingerprint': 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'  # NOQA
                        }
                    }
                }),
            'method': 'GET',
            'url': r'^http://pylxd.test/1.0/operations/operation-abc$',
        })

        an_container = models.Container(
            self.client, name='an-container')

        image = an_container.publish(wait=True)

        self.assertEqual(
            'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855',
            image.fingerprint)


class TestContainerState(testing.PyLXDTestCase):
    """Tests for pylxd.models.ContainerState."""

    def test_get(self):
        """Return a container."""
        name = 'an-container'

        an_container = models.Container.get(self.client, name)
        state = an_container.state()

        self.assertEqual('Running', state.status)
        self.assertEqual(103, state.status_code)

    def test_start(self):
        """A container is started."""
        an_container = models.Container.get(self.client, 'an-container')

        an_container.start(wait=True)

    def test_stop(self):
        """A container is stopped."""
        an_container = models.Container.get(self.client, 'an-container')

        an_container.stop()

    def test_restart(self):
        """A container is restarted."""
        an_container = models.Container.get(self.client, 'an-container')

        an_container.restart()

    def test_freeze(self):
        """A container is suspended."""
        an_container = models.Container.get(self.client, 'an-container')

        an_container.freeze()

    def test_unfreeze(self):
        """A container is resumed."""
        an_container = models.Container.get(self.client, 'an-container')

        an_container.unfreeze()


class TestContainerSnapshots(testing.PyLXDTestCase):
    """Tests for pylxd.models.Container.snapshots."""

    def setUp(self):
        super(TestContainerSnapshots, self).setUp()
        self.container = models.Container.get(self.client, 'an-container')

    def test_get(self):
        """Return a specific snapshot."""
        snapshot = self.container.snapshots.get('an-snapshot')

        self.assertEqual('an-snapshot', snapshot.name)

    def test_all(self):
        """Return all snapshots."""
        snapshots = self.container.snapshots.all()

        self.assertEqual(1, len(snapshots))
        self.assertEqual('an-snapshot', snapshots[0].name)
        self.assertEqual(self.client, snapshots[0].client)
        self.assertEqual(self.container, snapshots[0].container)

    def test_create(self):
        """Create a snapshot."""
        snapshot = self.container.snapshots.create(
            'an-snapshot', stateful=True, wait=True)

        self.assertEqual('an-snapshot', snapshot.name)


class TestSnapshot(testing.PyLXDTestCase):
    """Tests for pylxd.models.Snapshot."""

    def setUp(self):
        super(TestSnapshot, self).setUp()
        self.container = models.Container.get(self.client, 'an-container')

    def test_rename(self):
        """A snapshot is renamed."""
        snapshot = models.Snapshot(
            self.client, container=self.container,
            name='an-snapshot')

        snapshot.rename('an-renamed-snapshot', wait=True)

        self.assertEqual('an-renamed-snapshot', snapshot.name)

    def test_delete(self):
        """A snapshot is deleted."""
        snapshot = models.Snapshot(
            self.client, container=self.container,
            name='an-snapshot')

        snapshot.delete(wait=True)

        # TODO: add an assertion here

    def test_delete_failure(self):
        """If the response indicates delete failure, raise an exception."""
        def not_found(request, context):
            context.status_code = 404
            return json.dumps({
                'type': 'error',
                'error': 'Not found',
                'error_code': 404})
        self.add_rule({
            'text': not_found,
            'method': 'DELETE',
            'url': r'^http://pylxd.test/1.0/containers/an-container/snapshots/an-snapshot$',  # NOQA
        })

        snapshot = models.Snapshot(
            self.client, container=self.container,
            name='an-snapshot')

        self.assertRaises(exceptions.LXDAPIException, snapshot.delete)

    def test_publish(self):
        """Snapshots can be published."""
        self.add_rule({
            'text': json.dumps({
                'type': 'sync',
                'metadata': {
                    'id': 'operation-abc',
                    'metadata': {
                        'fingerprint': 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'  # NOQA
                        }
                    }
                }),
            'method': 'GET',
            'url': r'^http://pylxd.test/1.0/operations/operation-abc$',
        })

        snapshot = models.Snapshot(
            self.client, container=self.container,
            name='an-snapshot')

        image = snapshot.publish(wait=True)

        self.assertEqual(
            'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855',
            image.fingerprint)


class TestFiles(testing.PyLXDTestCase):
    """Tests for pylxd.models.Container.files."""

    def setUp(self):
        super(TestFiles, self).setUp()
        self.container = models.Container.get(self.client, 'an-container')

    def test_put_delete(self):
        """A file is put on the container and then deleted"""
        data = 'The quick brown fox'

        res = self.container.files.put('/tmp/putted', data)
        self.assertEqual(True, res,
                         msg=('Failed to put file, result: {}'
                              .format(res)))  # NOQA

        # we are mocked, so delete should initially not be available
        self.assertEqual(False, self.container.files.delete_available())
        self.assertRaises(ValueError,
                          self.container.files.delete, '/tmp/putted')
        # Now insert delete
        rule = {
            'text': json.dumps({
                'type': 'sync',
                'metadata': {'auth': 'trusted',
                             'environment': {
                                 'certificate': 'an-pem-cert',
                                 },
                             'api_extensions': ['file_delete']
                             }}),
            'method': 'GET',
            'url': r'^http://pylxd.test/1.0$',
        }
        self.add_rule(rule)
        # Update hostinfo
        self.client.host_info = self.client.api.get().json()['metadata']

        self.assertEqual(True, self.container.files.delete_available())

        res = self.container.files.delete('/tmp/putted')
        self.assertEqual(True, res,
                         msg=('Failed to delete file, result: {}'
                              .format(res)))  # NOQA

    def test_put_mode_uid_gid(self):
        """Should be able to set the mode, uid and gid of a file"""
        # fix up the default POST rule to allow us to see the posted vars
        _capture = {}

        def capture(request, context):
            _capture['headers'] = getattr(request._request, 'headers')
            context.status_code = 200

        rule = {
            'text': capture,
            'method': 'POST',
            'url': (r'^http://pylxd.test/1.0/containers/an-container/files'
                    '\?path=%2Ftmp%2Fputted$'),  # NOQA
        }
        self.add_rule(rule)

        data = 'The quick brown fox'
        # start with an octal mode
        res = self.container.files.put('/tmp/putted', data, mode=0o123,
                                       uid=1, gid=2)
        self.assertEqual(True, res,
                         msg=('Failed to put file, result: {}'
                              .format(res)))  # NOQA
        headers = _capture['headers']
        self.assertEqual(headers['X-LXD-mode'], '0123')
        self.assertEqual(headers['X-LXD-uid'], '1')
        self.assertEqual(headers['X-LXD-gid'], '2')
        # use a str mode this type
        res = self.container.files.put('/tmp/putted', data, mode='456')
        self.assertEqual(True, res,
                         msg=('Failed to put file, result: {}'
                              .format(res)))  # NOQA
        headers = _capture['headers']
        self.assertEqual(headers['X-LXD-mode'], '0456')
        # check that mode='0644' also works (i.e. already has 0 prefix)
        res = self.container.files.put('/tmp/putted', data, mode='0644')
        self.assertEqual(True, res,
                         msg=('Failed to put file, result: {}'
                              .format(res)))  # NOQA
        headers = _capture['headers']
        self.assertEqual(headers['X-LXD-mode'], '0644')
        # check that assertion is raised
        with self.assertRaises(ValueError):
            res = self.container.files.put('/tmp/putted', data, mode=object)

    def test_get(self):
        """A file is retrieved from the container."""
        data = self.container.files.get('/tmp/getted')

        self.assertEqual(b'This is a getted file', data)

    def test_get_not_found(self):
        """LXDAPIException is raised on bogus filenames."""
        def not_found(request, context):
            context.status_code = 500
        rule = {
            'text': not_found,
            'method': 'GET',
            'url': (r'^http://pylxd.test/1.0/containers/an-container/files'
                    '\?path=%2Ftmp%2Fgetted$'),  # NOQA
        }
        self.add_rule(rule)

        self.assertRaises(
            exceptions.LXDAPIException,
            self.container.files.get, '/tmp/getted')

    def test_get_error(self):
        """LXDAPIException is raised on error."""
        def not_found(request, context):
            context.status_code = 503
        rule = {
            'text': not_found,
            'method': 'GET',
            'url': (r'^http://pylxd.test/1.0/containers/an-container/files'
                    '\?path=%2Ftmp%2Fgetted$'),  # NOQA
        }
        self.add_rule(rule)

        self.assertRaises(
            exceptions.LXDAPIException,
            self.container.files.get, '/tmp/getted')