Newer
Older
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
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
#!/usr/bin/env python3
# Copyright 2019 Canonical Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import abc
import base64
import logging
import os
import pickle
import shutil
import subprocess
import sys
import tempfile
import unittest
import importlib.util
from pathlib import Path
from ops.charm import (
CharmBase,
CharmEvents,
HookEvent,
InstallEvent,
StartEvent,
ConfigChangedEvent,
UpgradeCharmEvent,
UpdateStatusEvent,
LeaderSettingsChangedEvent,
RelationJoinedEvent,
RelationChangedEvent,
RelationDepartedEvent,
RelationBrokenEvent,
RelationEvent,
StorageAttachedEvent,
ActionEvent,
CollectMetricsEvent,
)
from .test_helpers import fake_script, fake_script_calls
# This relies on the expected repository structure to find a path to
# source of the charm under test.
TEST_CHARM_DIR = Path(__file__ + '/../charms/test_main').resolve()
logger = logging.getLogger(__name__)
class SymlinkTargetError(Exception):
pass
class EventSpec:
def __init__(self, event_type, event_name, env_var=None,
relation_id=None, remote_app=None, remote_unit=None,
charm_config=None):
self.event_type = event_type
self.event_name = event_name
self.env_var = env_var
self.relation_id = relation_id
self.remote_app = remote_app
self.remote_unit = remote_unit
self.charm_config = charm_config
class TestMain(abc.ABC):
@abc.abstractmethod
def _setup_entry_point(self, directory, entry_point):
"""Set up the given entry point in the given directory.
If not using dispatch, that would be a symlink <dir>/<entry_point>
pointing at src/charm.py; if using dispatch that would be the dispatch
symlink. It could also not be a symlink...
"""
return NotImplemented
@abc.abstractmethod
def _call_event(self, rel_path, env):
"""Set up the environment and call (i.e. run) the given event."""
return NotImplemented
@abc.abstractmethod
def test_setup_event_links(self):
"""Test auto-creation of symlinks caused by initial events.
Depending on the combination of dispatch and non-dispatch, this should
be checking for the creation or the _lack_ of creation, as appropriate.
"""
return NotImplemented
def setUp(self):
self._setup_charm_dir()
_, tmp_file = tempfile.mkstemp()
self._state_file = Path(tmp_file)
self.addCleanup(self._state_file.unlink)
# Relations events are defined dynamically and modify the class attributes.
# We use a subclass temporarily to prevent these side effects from leaking.
class TestCharmEvents(CharmEvents):
pass
CharmBase.on = TestCharmEvents()
def cleanup():
shutil.rmtree(str(self.JUJU_CHARM_DIR))
CharmBase.on = CharmEvents()
self.addCleanup(cleanup)
fake_script(self, 'juju-log', "exit 0")
# set to something other than None for tests that care
self.stdout = None
self.stderr = None
def _setup_charm_dir(self):
self.JUJU_CHARM_DIR = Path(tempfile.mkdtemp()) / 'test_main'
self.hooks_dir = self.JUJU_CHARM_DIR / 'hooks'
charm_path = str(self.JUJU_CHARM_DIR / 'src/charm.py')
self.charm_exec_path = os.path.relpath(charm_path,
str(self.hooks_dir))
shutil.copytree(str(TEST_CHARM_DIR), str(self.JUJU_CHARM_DIR))
charm_spec = importlib.util.spec_from_file_location("charm", charm_path)
self.charm_module = importlib.util.module_from_spec(charm_spec)
charm_spec.loader.exec_module(self.charm_module)
self._prepare_initial_hooks()
def _prepare_initial_hooks(self):
initial_hooks = ('install', 'start', 'upgrade-charm', 'disks-storage-attached')
self.hooks_dir.mkdir()
for hook in initial_hooks:
self._setup_entry_point(self.hooks_dir, hook)
def _prepare_actions(self):
actions_meta = '''
foo-bar:
description: Foos the bar.
title: foo-bar
params:
foo-name:
type: string
description: A foo name to bar.
silent:
type: boolean
description:
default: false
required:
- foo-name
start:
description: Start the unit.'''
actions_dir_name = 'actions'
actions_meta_file = 'actions.yaml'
with (self.JUJU_CHARM_DIR / actions_meta_file).open('w+t') as f:
f.write(actions_meta)
actions_dir = self.JUJU_CHARM_DIR / actions_dir_name
actions_dir.mkdir()
for action_name in ('start', 'foo-bar'):
self._setup_entry_point(actions_dir, action_name)
def _read_and_clear_state(self):
state = None
if self._state_file.stat().st_size:
with self._state_file.open('r+b') as state_file:
state = pickle.load(state_file)
state_file.truncate(0)
return state
def _simulate_event(self, event_spec):
env = {
'PATH': "{}:{}".format(Path(__file__).parent / 'bin', os.environ['PATH']),
'JUJU_CHARM_DIR': str(self.JUJU_CHARM_DIR),
'JUJU_UNIT_NAME': 'test_main/0',
'CHARM_CONFIG': event_spec.charm_config,
}
if issubclass(event_spec.event_type, RelationEvent):
rel_name = event_spec.event_name.split('_')[0]
env.update({
'JUJU_RELATION': rel_name,
'JUJU_RELATION_ID': str(event_spec.relation_id),
})
remote_app = event_spec.remote_app
# For juju < 2.7 app name is extracted from JUJU_REMOTE_UNIT.
if remote_app is not None:
env['JUJU_REMOTE_APP'] = remote_app
remote_unit = event_spec.remote_unit
if remote_unit is None:
remote_unit = ''
env['JUJU_REMOTE_UNIT'] = remote_unit
else:
env.update({
'JUJU_REMOTE_UNIT': '',
'JUJU_REMOTE_APP': '',
})
if issubclass(event_spec.event_type, ActionEvent):
event_filename = event_spec.event_name[:-len('_action')].replace('_', '-')
env.update({
event_spec.env_var: event_filename,
})
if event_spec.env_var == 'JUJU_ACTION_NAME':
event_dir = 'actions'
else:
raise RuntimeError('invalid envar name specified for a action event')
else:
event_filename = event_spec.event_name.replace('_', '-')
event_dir = 'hooks'
self._call_event(Path(event_dir, event_filename), env)
return self._read_and_clear_state()
def test_event_reemitted(self):
# base64 encoding is used to avoid null bytes.
charm_config = base64.b64encode(pickle.dumps({
'STATE_FILE': self._state_file,
}))
# First run "install" to make sure all hooks are set up.
state = self._simulate_event(EventSpec(InstallEvent, 'install', charm_config=charm_config))
self.assertEqual(state['observed_event_types'], [InstallEvent])
state = self._simulate_event(EventSpec(ConfigChangedEvent, 'config-changed',
charm_config=charm_config))
self.assertEqual(state['observed_event_types'], [ConfigChangedEvent])
# Re-emit should pick the deferred config-changed.
state = self._simulate_event(EventSpec(UpdateStatusEvent, 'update-status',
charm_config=charm_config))
self.assertEqual(state['observed_event_types'], [ConfigChangedEvent, UpdateStatusEvent])
def test_no_reemission_on_collect_metrics(self):
# base64 encoding is used to avoid null bytes.
charm_config = base64.b64encode(pickle.dumps({
'STATE_FILE': self._state_file,
}))
fake_script(self, 'add-metric', 'exit 0')
# First run "install" to make sure all hooks are set up.
state = self._simulate_event(EventSpec(InstallEvent, 'install', charm_config=charm_config))
self.assertEqual(state['observed_event_types'], [InstallEvent])
state = self._simulate_event(EventSpec(ConfigChangedEvent, 'config-changed',
charm_config=charm_config))
self.assertEqual(state['observed_event_types'], [ConfigChangedEvent])
# Re-emit should not pick the deferred config-changed because
# collect-metrics runs in a restricted context.
state = self._simulate_event(EventSpec(CollectMetricsEvent, 'collect-metrics',
charm_config=charm_config))
self.assertEqual(state['observed_event_types'], [CollectMetricsEvent])
def test_multiple_events_handled(self):
self._prepare_actions()
charm_config = base64.b64encode(pickle.dumps({
'STATE_FILE': self._state_file,
}))
actions_charm_config = base64.b64encode(pickle.dumps({
'STATE_FILE': self._state_file,
'USE_ACTIONS': True,
}))
fake_script(self, 'action-get', "echo '{}'")
# Sample events with a different amount of dashes used
# and with endpoints from different sections of metadata.yaml
events_under_test = [(
EventSpec(InstallEvent, 'install',
charm_config=charm_config),
{},
), (
EventSpec(StartEvent, 'start',
charm_config=charm_config),
{},
), (
EventSpec(UpdateStatusEvent, 'update_status',
charm_config=charm_config),
{},
), (
EventSpec(LeaderSettingsChangedEvent, 'leader_settings_changed',
charm_config=charm_config),
{},
), (
EventSpec(RelationJoinedEvent, 'db_relation_joined',
relation_id=1,
remote_app='remote', remote_unit='remote/0',
charm_config=charm_config),
{'relation_name': 'db',
'relation_id': 1,
'app_name': 'remote',
'unit_name': 'remote/0'},
), (
EventSpec(RelationChangedEvent, 'mon_relation_changed',
relation_id=2,
remote_app='remote', remote_unit='remote/0',
charm_config=charm_config),
{'relation_name': 'mon',
'relation_id': 2,
'app_name': 'remote',
'unit_name': 'remote/0'},
), (
EventSpec(RelationChangedEvent, 'mon_relation_changed',
relation_id=2,
remote_app='remote', remote_unit=None,
charm_config=charm_config),
{'relation_name': 'mon',
'relation_id': 2,
'app_name': 'remote',
'unit_name': None},
), (
EventSpec(RelationDepartedEvent, 'mon_relation_departed',
relation_id=2,
remote_app='remote', remote_unit='remote/0',
charm_config=charm_config),
{'relation_name': 'mon',
'relation_id': 2,
'app_name': 'remote',
'unit_name': 'remote/0'},
), (
EventSpec(RelationBrokenEvent, 'ha_relation_broken',
relation_id=3,
charm_config=charm_config),
{'relation_name': 'ha',
'relation_id': 3},
), (
# Events without a remote app specified (for Juju < 2.7).
EventSpec(RelationJoinedEvent, 'db_relation_joined',
relation_id=1,
remote_unit='remote/0',
charm_config=charm_config),
{'relation_name': 'db',
'relation_id': 1,
'app_name': 'remote',
'unit_name': 'remote/0'},
), (
EventSpec(RelationChangedEvent, 'mon_relation_changed',
relation_id=2,
remote_unit='remote/0',
charm_config=charm_config),
{'relation_name': 'mon',
'relation_id': 2,
'app_name': 'remote',
'unit_name': 'remote/0'},
), (
EventSpec(RelationDepartedEvent, 'mon_relation_departed',
relation_id=2,
remote_unit='remote/0',
charm_config=charm_config),
{'relation_name': 'mon',
'relation_id': 2,
'app_name': 'remote',
'unit_name': 'remote/0'},
), (
EventSpec(ActionEvent, 'start_action',
env_var='JUJU_ACTION_NAME',
charm_config=actions_charm_config),
{},
), (
EventSpec(ActionEvent, 'foo_bar_action',
env_var='JUJU_ACTION_NAME',
charm_config=actions_charm_config),
{},
)]
logger.debug('Expected events %s', events_under_test)
# First run "install" to make sure all hooks are set up.
self._simulate_event(EventSpec(InstallEvent, 'install', charm_config=charm_config))
# Simulate hook executions for every event.
for event_spec, expected_event_data in events_under_test:
state = self._simulate_event(event_spec)
state_key = 'on_' + event_spec.event_name
handled_events = state.get(state_key, [])
# Make sure that a handler for that event was called once.
self.assertEqual(len(handled_events), 1)
# Make sure the event handled by the Charm has the right type.
handled_event_type = handled_events[0]
self.assertEqual(handled_event_type, event_spec.event_type)
self.assertEqual(state['observed_event_types'], [event_spec.event_type])
if event_spec.event_name in expected_event_data:
self.assertEqual(state[event_spec.event_name + '_data'],
expected_event_data[event_spec.event_name])
def test_event_not_implemented(self):
"""Make sure events without implementation do not cause non-zero exit.
"""
charm_config = base64.b64encode(pickle.dumps({
'STATE_FILE': self._state_file,
}))
# Simulate a scenario where there is a symlink for an event that
# a charm does not know how to handle.
hook_path = self.JUJU_CHARM_DIR / 'hooks/not-implemented-event'
# This will be cleared up in tearDown.
hook_path.symlink_to('install')
try:
self._simulate_event(EventSpec(HookEvent, 'not-implemented-event',
charm_config=charm_config))
except subprocess.CalledProcessError:
self.fail('Event simulation for an unsupported event'
' results in a non-zero exit code returned')
def test_collect_metrics(self):
indicator_file = self.JUJU_CHARM_DIR / 'indicator'
charm_config = base64.b64encode(pickle.dumps({
'STATE_FILE': self._state_file,
'INDICATOR_FILE': indicator_file
}))
fake_script(self, 'add-metric', 'exit 0')
fake_script(self, 'juju-log', 'exit 0')
self._simulate_event(EventSpec(InstallEvent, 'install', charm_config=charm_config))
# Clear the calls during 'install'
fake_script_calls(self, clear=True)
self._simulate_event(EventSpec(CollectMetricsEvent, 'collect_metrics',
charm_config=charm_config))
self.assertEqual(
fake_script_calls(self),
[['juju-log', '--log-level', 'DEBUG', 'Emitting Juju event collect_metrics'],
['add-metric', '--labels', 'bar=4.2', 'foo=42']])
def test_logger(self):
charm_config = base64.b64encode(pickle.dumps({
'STATE_FILE': self._state_file,
'USE_LOG_ACTIONS': True,
}))
fake_script(self, 'action-get', "echo '{}'")
actions_yaml = self.JUJU_CHARM_DIR / 'actions.yaml'
actions_yaml.write_text(
'''
log_critical: {}
log_error: {}
log_warning: {}
log_info: {}
log_debug: {}
''')
test_cases = [(
EventSpec(ActionEvent, 'log_critical_action', env_var='JUJU_ACTION_NAME',
charm_config=charm_config),
['juju-log', '--log-level', 'CRITICAL', 'super critical'],
), (
EventSpec(ActionEvent, 'log_error_action',
env_var='JUJU_ACTION_NAME',
charm_config=charm_config),
['juju-log', '--log-level', 'ERROR', 'grave error'],
), (
EventSpec(ActionEvent, 'log_warning_action',
env_var='JUJU_ACTION_NAME',
charm_config=charm_config),
['juju-log', '--log-level', 'WARNING', 'wise warning'],
), (
EventSpec(ActionEvent, 'log_info_action',
env_var='JUJU_ACTION_NAME',
charm_config=charm_config),
['juju-log', '--log-level', 'INFO', 'useful info'],
)]
# Set up action symlinks.
self._simulate_event(EventSpec(InstallEvent, 'install',
charm_config=charm_config))
for event_spec, calls in test_cases:
self._simulate_event(event_spec)
self.assertIn(calls, fake_script_calls(self, clear=True))
class TestMainWithNoDispatch(TestMain, unittest.TestCase):
def _setup_entry_point(self, directory, entry_point):
path = directory / entry_point
path.symlink_to(self.charm_exec_path)
def _call_event(self, rel_path, env):
event_file = self.JUJU_CHARM_DIR / rel_path
# Note that sys.executable is used to make sure we are using the same
# interpreter for the child process to support virtual environments.
subprocess.run(
[sys.executable, str(event_file)],
check=True, env=env, cwd=str(self.JUJU_CHARM_DIR))
def test_setup_event_links(self):
"""Test auto-creation of symlinks caused by initial events.
"""
all_event_hooks = ['hooks/' + e.replace("_", "-")
for e in self.charm_module.Charm.on.events().keys()]
charm_config = base64.b64encode(pickle.dumps({
'STATE_FILE': self._state_file,
}))
initial_events = {
EventSpec(InstallEvent, 'install', charm_config=charm_config),
EventSpec(StorageAttachedEvent, 'disks-storage-attached', charm_config=charm_config),
EventSpec(StartEvent, 'start', charm_config=charm_config),
EventSpec(UpgradeCharmEvent, 'upgrade-charm', charm_config=charm_config),
}
def _assess_event_links(event_spec):
self.assertTrue(self.hooks_dir / event_spec.event_name in self.hooks_dir.iterdir())
for event_hook in all_event_hooks:
self.assertTrue((self.JUJU_CHARM_DIR / event_hook).exists(),
'Missing hook: ' + event_hook)
self.assertEqual(os.readlink(str(self.JUJU_CHARM_DIR / event_hook)),
self.charm_exec_path)
for initial_event in initial_events:
self._setup_charm_dir()
self._simulate_event(initial_event)
_assess_event_links(initial_event)
# Make sure it is idempotent.
self._simulate_event(initial_event)
_assess_event_links(initial_event)
def test_setup_action_links(self):
charm_config = base64.b64encode(pickle.dumps({
'STATE_FILE': self._state_file,
}))
actions_yaml = self.JUJU_CHARM_DIR / 'actions.yaml'
actions_yaml.write_text('test: {}')
self._simulate_event(EventSpec(InstallEvent, 'install', charm_config=charm_config))
action_hook = self.JUJU_CHARM_DIR / 'actions' / 'test'
self.assertTrue(action_hook.exists())
class TestMainWithDispatch(TestMain, unittest.TestCase):
def _setup_entry_point(self, directory, entry_point):
path = self.JUJU_CHARM_DIR / 'dispatch'
if not path.exists():
path.symlink_to('src/charm.py')
def _call_event(self, rel_path, env):
env["JUJU_DISPATCH_PATH"] = str(rel_path)
dispatch = self.JUJU_CHARM_DIR / 'dispatch'
subprocess.run(
[sys.executable, str(dispatch)],
stdout=self.stdout,
stderr=self.stderr,
check=True, env=env, cwd=str(self.JUJU_CHARM_DIR))
def test_setup_event_links(self):
"""Test auto-creation of symlinks caused by initial events does _not_ happen when using dispatch.
"""
all_event_hooks = ['hooks/' + e.replace("_", "-")
for e in self.charm_module.Charm.on.events().keys()]
charm_config = base64.b64encode(pickle.dumps({
'STATE_FILE': self._state_file,
}))
initial_events = {
EventSpec(InstallEvent, 'install', charm_config=charm_config),
EventSpec(StorageAttachedEvent, 'disks-storage-attached', charm_config=charm_config),
EventSpec(StartEvent, 'start', charm_config=charm_config),
EventSpec(UpgradeCharmEvent, 'upgrade-charm', charm_config=charm_config),
}
def _assess_event_links(event_spec):
self.assertNotIn(self.hooks_dir / event_spec.event_name, self.hooks_dir.iterdir())
for event_hook in all_event_hooks:
self.assertFalse((self.JUJU_CHARM_DIR / event_hook).exists(),
'Spurious hook: ' + event_hook)
for initial_event in initial_events:
self._setup_charm_dir()
self._simulate_event(initial_event)
_assess_event_links(initial_event)
def test_hook_and_dispatch(self):
charm_config = base64.b64encode(pickle.dumps({
'STATE_FILE': self._state_file,
}))
self.fake_script_path = self.hooks_dir
fake_script(self, 'install', 'exit 0')
state = self._simulate_event(EventSpec(InstallEvent, 'install', charm_config=charm_config))
# the script was called, *and*, the .on. was called
self.assertEqual(fake_script_calls(self), [['install', '']])
self.assertEqual(state['observed_event_types'], [InstallEvent])
def test_hook_and_dispatch_with_failing_hook(self):
self.stdout = self.stderr = tempfile.TemporaryFile()
self.addCleanup(self.stdout.close)
charm_config = base64.b64encode(pickle.dumps({
'STATE_FILE': self._state_file,
}))
old_path = self.fake_script_path
self.fake_script_path = self.hooks_dir
fake_script(self, 'install', 'exit 42')
event = EventSpec(InstallEvent, 'install', charm_config=charm_config)
with self.assertRaises(subprocess.CalledProcessError):
self._simulate_event(event)
self.fake_script_path = old_path
self.stdout.seek(0)
self.assertEqual(self.stdout.read(), b'')
calls = fake_script_calls(self)
self.assertEqual(len(calls), 1, 'unexpect call result: {}'.format(calls))
self.assertEqual(len(calls[0]), 4, 'unexpect call result: {}'.format(calls[0]))
self.assertEqual(
calls[0][:3],
['juju-log', '--log-level', 'WARNING']
)
self.assertRegex(calls[0][3], r'hook /\S+/install exited with status 42')
def test_hook_and_dispatch_but_hook_is_dispatch(self):
charm_config = base64.b64encode(pickle.dumps({
'STATE_FILE': self._state_file,
}))
event = EventSpec(InstallEvent, 'install', charm_config=charm_config)
hook_path = self.hooks_dir / 'install'
for ((rel, ind), path) in {
# relative and indirect
(True, True): Path('../dispatch'),
# relative and direct
(True, False): Path(self.charm_exec_path),
# absolute and direct
(False, False): (self.hooks_dir / self.charm_exec_path).resolve(),
# absolute and indirect
(False, True): self.JUJU_CHARM_DIR / 'dispatch',
}.items():
with self.subTest(path=path, rel=rel, ind=ind):
# sanity check
self.assertEqual(path.is_absolute(), not rel)
self.assertEqual(path.name == 'dispatch', ind)
try:
hook_path.symlink_to(path)
state = self._simulate_event(event)
# the .on. was only called once
self.assertEqual(state['observed_event_types'], [InstallEvent])
self.assertEqual(state['on_install'], [InstallEvent])
finally:
hook_path.unlink()
# TODO: this does not work
# class TestMainWithDispatchAsScript(TestMainWithDispatch):
# """Here dispatch is a script that execs the charm.py instead of a symlink.
# """
# def _setup_entry_point(self, directory, entry_point):
# path = self.JUJU_CHARM_DIR / 'dispatch'
# if not path.exists():
# path.write_text('#!/bin/sh\nexec "{}" "{}"\n'.format(
# sys.executable,
# self.JUJU_CHARM_DIR / 'src/charm.py'))
# path.chmod(0o755)
# def _call_event(self, rel_path, env):
# env["JUJU_DISPATCH_PATH"] = str(rel_path)
# dispatch = self.JUJU_CHARM_DIR / 'dispatch'
# subprocess.check_call([str(dispatch)],
# env=env, cwd=str(self.JUJU_CHARM_DIR))
if __name__ == "__main__":
unittest.main()