| 1 |
# (C) Copyright 2007-2025 Enthought, Inc., Austin, TX |
| 2 |
# All rights reserved. |
| 3 |
# |
| 4 |
# This software is provided without warranty under the terms of the BSD |
| 5 |
# license included in LICENSE.txt and may be redistributed only under |
| 6 |
# the conditions described in the aforementioned license. The license |
| 7 |
# is also available online at http://www.enthought.com/licenses/BSD.txt |
| 8 |
# |
| 9 |
# Thanks for using Enthought open source! |
| 10 |
""" Tests for the 'Service' trait type. """ |
| 11 |
|
| 12 |
# Standard library imports. |
| 13 |
import unittest |
| 14 |
|
| 15 |
# Enthought library imports. |
| 16 |
from traits.api import HasTraits, Instance, TraitError |
| 17 |
|
| 18 |
from envisage.api import Plugin, Service |
| 19 |
from envisage.tests.support import SimpleApplication |
| 20 |
|
| 21 |
|
| 22 |
class ServiceTestCase(unittest.TestCase): |
| 23 |
"""Tests for the 'Service' trait type.""" |
| 24 |
|
| 25 |
def test_service_trait_type(self): |
| 26 |
"""service trait type""" |
| 27 |
|
| 28 |
class Foo(HasTraits): |
| 29 |
pass |
| 30 |
|
| 31 |
class PluginA(Plugin): |
| 32 |
id = "A" |
| 33 |
foo = Instance(Foo, (), service=True) |
| 34 |
|
| 35 |
class PluginB(Plugin): |
| 36 |
id = "B" |
| 37 |
foo = Service(Foo) |
| 38 |
|
| 39 |
a = PluginA() |
| 40 |
b = PluginB() |
| 41 |
|
| 42 |
application = SimpleApplication(plugins=[a, b]) |
| 43 |
application.start() |
| 44 |
|
| 45 |
# Make sure the services were registered. |
| 46 |
self.assertEqual(a.foo, b.foo) |
| 47 |
|
| 48 |
# Stop the application. |
| 49 |
application.stop() |
| 50 |
|
| 51 |
# Make sure the service was unregistered. |
| 52 |
self.assertEqual(None, b.foo) |
| 53 |
|
| 54 |
# You can't set service traits! |
| 55 |
with self.assertRaises(TraitError): |
| 56 |
setattr(b, "foo", "bogus") |
| 57 |
|
| 58 |
def test_service_trait_type_with_no_service_registry(self): |
| 59 |
"""service trait type with no service registry""" |
| 60 |
|
| 61 |
class Foo(HasTraits): |
| 62 |
pass |
| 63 |
|
| 64 |
class Bar(HasTraits): |
| 65 |
foo = Service(Foo) |
| 66 |
|
| 67 |
# We should get an exception because the object does not have an |
| 68 |
# 'service_registry' trait. |
| 69 |
b = Bar() |
| 70 |
with self.assertRaises(ValueError): |
| 71 |
getattr(b, "foo") |
| 72 |
|
| 73 |
def test_service_str_representation(self): |
| 74 |
"""test the string representation of the service""" |
| 75 |
|
| 76 |
class Foo(HasTraits): |
| 77 |
pass |
| 78 |
|
| 79 |
service_repr = "Service(protocol={!r})" |
| 80 |
service = Service(Foo) |
| 81 |
self.assertEqual(service_repr.format(Foo), str(service)) |
| 82 |
self.assertEqual(service_repr.format(Foo), repr(service)) |