def test_sync_anytrait_items_not_event(self):
        """ Test sychronizing trait with name *_items which is a normal trait
        rather than an event trait for listening to list/dict/set mutation.
        """

        class MyPreferencesHelper(PreferencesHelper):
            preferences_path = Str('my_section')

            names_items = Str()

        helper = MyPreferencesHelper(preferences=self.preferences)
        helper.names_items = "Hello"

        self.preferences.save(self.tmpfile)
        new_preferences = Preferences()
        new_preferences.load(self.tmpfile)

        self.assertEqual(
            sorted(new_preferences.keys("my_section")),
            ["names_items"]
        )
        self.assertEqual(
            new_preferences.get("my_section.names_items"),
            str(helper.names_items),
        )
Exemplo n.º 2
0
    def test_save(self):
        """ save """

        p = self.preferences

        # Get the application scope.
        application = p.node("application/")

        tmp = join(self.tmpdir, "test.ini")
        application.filename = tmp

        # Set a value.
        p.set("acme.ui.bgcolor", "red")

        # Save all scopes.
        p.save()

        # Make sure a file was written.
        self.assertTrue(os.path.exists(tmp))

        # Load the 'ini' file into a new preferences node and make sure the
        # preference is in there.
        p = Preferences()
        p.load(tmp)

        self.assertEqual("red", p.get("acme.ui.bgcolor"))

        # Cleanup.
        os.remove(tmp)
Exemplo n.º 3
0
    def test_ability_to_specify_primary_scope(self):

        preferences = ScopedPreferences(
            scopes=[
                Preferences(name="a"),
                Preferences(name="b"),
                Preferences(name="c"),
            ],
            primary_scope_name="b",
        )

        # This should set the prefrrence in the primary scope.
        preferences.set("acme.foo", "bar")

        # Look it up specifically in the primary scope.
        self.assertEqual("bar", preferences.get("b/acme.foo"))
Exemplo n.º 4
0
    def setUp(self):
        """ Prepares the test fixture before each test method is called. """

        self.preferences = set_default_preferences(Preferences())

        # The filename of the example preferences file.
        self.example = os.fspath(files(PKG) / "example.ini")
Exemplo n.º 5
0
    def test_explicit_preferences(self):
        """ explicit preferences """

        p = self.preferences
        p.load(self.example)

        class AcmeUI(HasTraits):
            """ The Acme UI class! """

            # The traits that we want to initialize from preferences.
            bgcolor = Str
            width = Int
            ratio = Float
            visible = Bool

        acme_ui = AcmeUI()
        acme_ui.on_trait_change(listener)

        # Create an empty preferences node and use that in some of the
        # bindings!
        preferences = Preferences()

        # Make some bindings.
        bind_preference(acme_ui, "bgcolor", "acme.ui.bgcolor", preferences)
        bind_preference(acme_ui, "width", "acme.ui.width")
        bind_preference(acme_ui, "ratio", "acme.ui.ratio", preferences)
        bind_preference(acme_ui, "visible", "acme.ui.visible")

        # Make sure the object was initialized properly.
        self.assertEqual("", acme_ui.bgcolor)
        self.assertEqual(50, acme_ui.width)
        self.assertEqual(0.0, acme_ui.ratio)
        self.assertTrue(acme_ui.visible)
Exemplo n.º 6
0
    def init(self, pref_path='', pref_node=''):
        """ Read a configuration file and attempt to bind the server to the
            specified port.
        """
        # Bind to port and write port to lock file
        self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self._sock.bind(('localhost', 0))
        self._port = self._sock.getsockname()[1]
        f = open(LOCK_PATH, 'w')
        f.write(str(self._port))
        f.close()

        # Read configuration file
        if not pref_path:
            return
        if os.path.exists(pref_path):
            prefs = Preferences(filename=pref_path)
            if prefs.node_exists(pref_node):
                spawn_node = prefs.node(pref_node)
                for key in spawn_node.keys():
                    cmd = spawn_node.get(key).strip()
                    if cmd.startswith('python '):
                        cmd = cmd.replace('python', sys.executable, 1)
                    self.spawn_commands[key] = cmd
            else:
                msg = "Server could not locate preference node '%s.'"
                logger.error(msg % pref_node)
        else:
            msg = "Server given non-existent preference path '%s'."
            logger.error(msg % pref_path)
    def test_ability_to_specify_primary_scope(self):

        preferences = ScopedPreferences(scopes=[
            Preferences(name='a'),
            Preferences(name='b'),
            Preferences(name='c')
        ],
                                        primary_scope_name='b')

        # This should set the prefrrence in the primary scope.
        preferences.set('acme.foo', 'bar')

        # Look it up specifically in the primary scope.
        self.assertEqual('bar', preferences.get('b/acme.foo'))

        return
 def setUp(self):
     """Called before each test is run"""
     self.preferences = set_default_preferences(Preferences())
     # The filename of the example preferences file.
     pref_file = resource_filename('mayavi.tests', 'test_preference.ini')
     self.preferences.load(pref_file)
     self.pref = _TestPreference()
     self.mirror = PreferencesMirror()
     self.mirror.preferences = self.pref
Exemplo n.º 9
0
    def setUp(self):
        """ Prepares the test fixture before each test method is called. """

        self.preferences = set_default_preferences(Preferences())

        # The filename of the example preferences file.
        self.example = resource_filename(PKG, 'example.ini')

        return
    def setUp(self):
        """ Prepares the test fixture before each test method is called. """

        self.preferences = Preferences()

        # The filename of the example preferences file.
        self.example = os.fspath(files(PKG) / "example.ini")

        # A temporary directory that can safely be written to.
        self.tmpdir = tempfile.mkdtemp()
    def setUp(self):
        """ Prepares the test fixture before each test method is called. """

        self.preferences = set_default_preferences(Preferences())

        # The filename of the example preferences file.
        self.example = os.fspath(files(PKG) / "example.ini")

        # A temporary directory that can safely be written to.
        self.tmpdir = tempfile.mkdtemp()

        # Path to a temporary file
        self.tmpfile = os.path.join(self.tmpdir, "tmp.ini")

        push_exception_handler(reraise_exceptions=True)
        self.addCleanup(pop_exception_handler)
    def test_save(self):
        """ save """

        p = self.preferences

        # Load the preferences from an 'ini' file.
        p.load(self.example)

        # Make sure it was all loaded!
        self.assertEqual('blue', p.get('acme.ui.bgcolor'))
        self.assertEqual('50', p.get('acme.ui.width'))
        self.assertEqual('1.0', p.get('acme.ui.ratio'))
        self.assertEqual('True', p.get('acme.ui.visible'))
        self.assertEqual('acme ui', p.get('acme.ui.description'))
        self.assertEqual('[1, 2, 3, 4]', p.get('acme.ui.offsets'))
        self.assertEqual("['joe', 'fred', 'jane']", p.get('acme.ui.names'))
        self.assertEqual('splash', p.get('acme.ui.splash_screen.image'))
        self.assertEqual('red', p.get('acme.ui.splash_screen.fgcolor'))

        # Make a change.
        p.set('acme.ui.bgcolor', 'yellow')

        # Save it to another file.
        tmp = join(self.tmpdir, 'tmp.ini')
        p.save(tmp)

        try:
            # Load it into a new node.
            p = Preferences()
            p.load(tmp)

            # Make sure it was all loaded!
            self.assertEqual('yellow', p.get('acme.ui.bgcolor'))
            self.assertEqual('50', p.get('acme.ui.width'))
            self.assertEqual('1.0', p.get('acme.ui.ratio'))
            self.assertEqual('True', p.get('acme.ui.visible'))
            self.assertEqual('acme ui', p.get('acme.ui.description'))
            self.assertEqual('[1, 2, 3, 4]', p.get('acme.ui.offsets'))
            self.assertEqual("['joe', 'fred', 'jane']", p.get('acme.ui.names'))
            self.assertEqual('splash', p.get('acme.ui.splash_screen.image'))
            self.assertEqual('red', p.get('acme.ui.splash_screen.fgcolor'))

        finally:
            # Clean up!
            os.remove(tmp)

        return
    def test_save(self):
        """ save """

        p = self.preferences

        # Load the preferences from an 'ini' file.
        p.load(self.example)

        # Make sure it was all loaded!
        self.assertEqual("blue", p.get("acme.ui.bgcolor"))
        self.assertEqual("50", p.get("acme.ui.width"))
        self.assertEqual("1.0", p.get("acme.ui.ratio"))
        self.assertEqual("True", p.get("acme.ui.visible"))
        self.assertEqual("acme ui", p.get("acme.ui.description"))
        self.assertEqual("[1, 2, 3, 4]", p.get("acme.ui.offsets"))
        self.assertEqual("['joe', 'fred', 'jane']", p.get("acme.ui.names"))
        self.assertEqual("splash", p.get("acme.ui.splash_screen.image"))
        self.assertEqual("red", p.get("acme.ui.splash_screen.fgcolor"))

        # Make a change.
        p.set("acme.ui.bgcolor", "yellow")

        # Save it to another file.
        tmp = join(self.tmpdir, "tmp.ini")
        p.save(tmp)

        try:
            # Load it into a new node.
            p = Preferences()
            p.load(tmp)

            # Make sure it was all loaded!
            self.assertEqual("yellow", p.get("acme.ui.bgcolor"))
            self.assertEqual("50", p.get("acme.ui.width"))
            self.assertEqual("1.0", p.get("acme.ui.ratio"))
            self.assertEqual("True", p.get("acme.ui.visible"))
            self.assertEqual("acme ui", p.get("acme.ui.description"))
            self.assertEqual("[1, 2, 3, 4]", p.get("acme.ui.offsets"))
            self.assertEqual("['joe', 'fred', 'jane']", p.get("acme.ui.names"))
            self.assertEqual("splash", p.get("acme.ui.splash_screen.image"))
            self.assertEqual("red", p.get("acme.ui.splash_screen.fgcolor"))

        finally:
            # Clean up!
            os.remove(tmp)
Exemplo n.º 14
0
    def test_preferences_page_apply_skip_items_traits(self):
        """ Test _items traits from List mutation are skipped. """
        # Regression test for enthought/apptools#129

        class MyPreferencesPage(PreferencesPage):
            preferences_path = "my_ref.pref"
            names = List(Str())

        preferences = Preferences()
        pref_page = MyPreferencesPage(
            preferences=preferences,
            names=["1"],
        )
        pref_page.names.append("2")
        pref_page.apply()

        self.assertEqual(preferences.get("my_ref.pref.names"), str(["1", "2"]))
        self.assertEqual(preferences.keys("my_ref.pref"), ["names"])
    def test_preferences_page_apply(self):
        """ Test applying the preferences """

        # this sets up imitate Mayavi usage.

        class MyPreferencesPage(PreferencesPage):

            # the following set default values for class traits
            category = "Application"

            help_id = ""

            name = "Note"

            preferences_path = "my_ref.pref"

            # custom preferences

            backend = Enum("auto", "simple", "test")

            traits_view = View(Group(Item("backend")))

        preferences = Preferences()
        pref_page = MyPreferencesPage(
            preferences=preferences,
            category="Another Application",
            help_id="this_wont_be_saved",
            name="Different Note",
            # custom preferences
            backend="simple",
        )
        pref_page.apply()

        self.assertEqual(preferences.get("my_ref.pref.backend"), "simple")
        self.assertEqual(preferences.keys("my_ref.pref"), ["backend"])

        # this is not saved by virtue of it being static and never assigned to
        self.assertIsNone(preferences.get("my_ref.pref.traits_view"))

        # These are skipped because this trait is defined on the
        # PreferencesPage.
        self.assertIsNone(preferences.get("my_ref.pref.help_id"))
        self.assertIsNone(preferences.get("my_ref.pref.category"))
        self.assertIsNone(preferences.get("my_ref.pref.name"))
    def test_real_unicode_values(self):
        """ Test with real life unicode values """

        p = self.preferences
        p.load(self.example)

        class AcmeUIPreferencesHelper(PreferencesHelper):
            """ A helper! """

            # The path to the preferences node that contains our preferences.
            preferences_path = "acme.ui"

            # The traits that we want to initialize from preferences.
            bgcolor = Str("blue")
            width = Int(50)
            ratio = Float(1.0)
            visible = Bool(True)
            description = Str("")
            offsets = List(Int, [1, 2, 3, 4])
            names = List(Str, ["joe", "fred", "jane"])

        helper = AcmeUIPreferencesHelper()

        first_unicode_str = "U\xdc\xf2ser"

        helper.description = first_unicode_str
        self.assertEqual(first_unicode_str, helper.description)

        second_unicode_str = "caf\xe9"
        helper.description = second_unicode_str
        self.assertEqual(second_unicode_str, helper.description)
        self.assertEqual(second_unicode_str, p.get("acme.ui.description"))

        # Save it to another file.
        tmp = os.path.join(self.tmpdir, "tmp.ini")
        p.save(tmp)

        # Load it into a new node.
        p = Preferences()
        p.load(tmp)
        self.assertEqual(second_unicode_str, p.get("acme.ui.description"))
        self.assertEqual("True", p.get("acme.ui.visible"))
        self.assertTrue(helper.visible)
    def test_sync_anytrait_items_overload(self):
        """ Test sychronizing trait with name *_items not to be mistaken
        as the event trait for mutating list/dict/set
        """
        class MyPreferencesPage(PreferencesPage):
            preferences_path = Str('my_section')

            names_items = Str()

        preferences = Preferences()
        pref_page = MyPreferencesPage(preferences=preferences)
        pref_page.names_items = "Hello"
        pref_page.apply()

        self.assertEqual(sorted(preferences.keys("my_section")),
                         ["names_items"])
        self.assertEqual(
            preferences.get("my_section.names_items"),
            "Hello",
        )
    def test_flush(self):
        """ flush """

        p = self.preferences

        # A temporary .ini file for this test.
        tmp = join(self.tmpdir, 'tmp.ini')

        # This could be set in the constructor of course, its just here we
        # want to use the instance declared in 'setUp'.
        p.filename = tmp

        try:
            # Load the preferences from an 'ini' file.
            p.load(self.example)

            # Flush it.
            p.flush()

            # Load it into a new node.
            p = Preferences()
            p.load(tmp)

            # Make sure it was all loaded!
            self.assertEqual('blue', p.get('acme.ui.bgcolor'))
            self.assertEqual('50', p.get('acme.ui.width'))
            self.assertEqual('1.0', p.get('acme.ui.ratio'))
            self.assertEqual('True', p.get('acme.ui.visible'))
            self.assertEqual('acme ui', p.get('acme.ui.description'))
            self.assertEqual('[1, 2, 3, 4]', p.get('acme.ui.offsets'))
            self.assertEqual("['joe', 'fred', 'jane']", p.get('acme.ui.names'))
            self.assertEqual('splash', p.get('acme.ui.splash_screen.image'))
            self.assertEqual('red', p.get('acme.ui.splash_screen.fgcolor'))

        finally:
            # Clean up!
            os.remove(tmp)

        return
    def test_mutate_list_of_values(self):
        """ Mutated list should be saved and _items events not to be
        saved in the preferences.
        """
        # Regression test for enthought/apptools#129

        class MyPreferencesHelper(PreferencesHelper):
            preferences_path = Str('my_section')

            list_of_str = List(Str)

        helper = MyPreferencesHelper(list_of_str=["1"])

        # Now modify the list to fire _items event
        helper.list_of_str.append("2")
        self.preferences.save(self.tmpfile)

        new_preferences = Preferences()
        new_preferences.load(self.tmpfile)

        self.assertEqual(
            new_preferences.get("my_section.list_of_str"), str(["1", "2"])
        )
        self.assertEqual(new_preferences.keys("my_section"), ["list_of_str"])
Exemplo n.º 20
0
    def test_preferences_node_changed(self):
        """ preferences node changed """

        p = self.preferences
        p.load(self.example)

        class AcmeUIPreferencesHelper(PreferencesHelper):
            """ A helper! """

            # The path to the preferences node that contains our preferences.
            preferences_path = 'acme.ui'

            # The traits that we want to initialize from preferences.
            bgcolor     = Str
            width       = Int
            ratio       = Float
            visible     = Bool
            description = Unicode
            offsets     = List(Int)
            names       = List(Str)

        helper = AcmeUIPreferencesHelper()

        # We only listen to some of the traits so the testing is easier.
        helper.on_trait_change(width_listener, ['width'])
        helper.on_trait_change(bgcolor_listener, ['bgcolor'])

        # Create a new preference node.
        p1 = Preferences()
        p1.load(self.example)

        p1.set('acme.ui.bgcolor', 'red')
        p1.set('acme.ui.width', 40)

        # Set the new preferences
        helper.preferences = p1

        # Test event handling.
        self.assertEqual(helper, width_listener.obj)
        self.assertEqual('width', width_listener.trait_name)
        self.assertEqual(50, width_listener.old)
        self.assertEqual(40, width_listener.new)

        self.assertEqual(helper, bgcolor_listener.obj)
        self.assertEqual('bgcolor', bgcolor_listener.trait_name)
        self.assertEqual('blue', bgcolor_listener.old)
        self.assertEqual('red', bgcolor_listener.new)

        # Test re-initialization.
        self.assertEqual(helper.bgcolor, 'red')
        self.assertEqual(helper.width, 40)

        # Test event handling.
        p1.set('acme.ui.bgcolor', 'black')
        self.assertEqual(helper, bgcolor_listener.obj)
        self.assertEqual('bgcolor', bgcolor_listener.trait_name)
        self.assertEqual('red', bgcolor_listener.old)
        self.assertEqual('black', bgcolor_listener.new)

        # This should not trigger any new changes since we are setting values
        # on the old preferences node.
        p.set('acme.ui.bgcolor', 'white')
        self.assertEqual(helper, bgcolor_listener.obj)
        self.assertEqual('bgcolor', bgcolor_listener.trait_name)
        self.assertEqual('red', bgcolor_listener.old)
        self.assertEqual('black', bgcolor_listener.new)

        return
    def test_load_and_save(self):
        """ load and save """

        p = self.preferences
        p.load(self.example)

        class AcmeUI(HasTraits):
            """ The Acme UI class! """

            # The traits that we want to initialize from preferences.
            bgcolor = Str('red')
            width = Int(60)
            ratio = Float(2.0)
            visible = Bool(False)

        acme_ui = AcmeUI()

        # Make some bindings.
        bind_preference(acme_ui, 'bgcolor', 'acme.ui.bgcolor')
        bind_preference(acme_ui, 'width', 'acme.ui.width')
        bind_preference(acme_ui, 'ratio', 'acme.ui.ratio')
        bind_preference(acme_ui, 'visible', 'acme.ui.visible')

        # Make sure the helper was initialized properly (with the values in
        # the loaded .ini file *not* the trait defaults!).
        self.assertEqual('blue', acme_ui.bgcolor)
        self.assertEqual(50, acme_ui.width)
        self.assertEqual(1.0, acme_ui.ratio)
        self.assertEqual(True, acme_ui.visible)

        # Make a change to one of the preference values.
        p.set('acme.ui.bgcolor', 'yellow')
        self.assertEqual('yellow', acme_ui.bgcolor)
        self.assertEqual('yellow', p.get('acme.ui.bgcolor'))

        # Save the preferences to a different file.
        tmpdir = tempfile.mkdtemp()
        tmp = join(tmpdir, 'tmp.ini')
        p.save(tmp)

        # Load the preferences again from that file.
        p = set_default_preferences(Preferences())
        p.load(tmp)

        acme_ui = AcmeUI()

        # Make some bindings.
        bind_preference(acme_ui, 'bgcolor', 'acme.ui.bgcolor')
        bind_preference(acme_ui, 'width', 'acme.ui.width')
        bind_preference(acme_ui, 'ratio', 'acme.ui.ratio')
        bind_preference(acme_ui, 'visible', 'acme.ui.visible')

        # Make sure the helper was initialized properly (with the values in
        # the .ini file *not* the trait defaults!).
        self.assertEqual('yellow', acme_ui.bgcolor)
        self.assertEqual(50, acme_ui.width)
        self.assertEqual(1.0, acme_ui.ratio)
        self.assertEqual(True, acme_ui.visible)

        # Clean up!
        os.remove(tmp)
        os.removedirs(tmpdir)

        return
Exemplo n.º 22
0
# Thanks for using Enthought open source!
""" An example of using the preferences manager. """

# Enthought library imports.
from traits.api import Color, Int
from traitsui.api import View

# Local imports.
from apptools.preferences.api import Preferences
from apptools.preferences.api import get_default_preferences
from apptools.preferences.api import set_default_preferences
from apptools.preferences.ui.api import PreferencesManager, PreferencesPage

# Create a preferences collection from a file and make it the default root
# preferences node for all preferences helpers etc.
set_default_preferences(Preferences(filename='example.ini'))


class AcmePreferencesPage(PreferencesPage):
    """ A preference page for the Acme preferences. """

    #### 'IPreferencesPage' interface #########################################

    # The page's category (e.g. 'General/Appearence'). The empty string means
    # that this is a top-level page.
    category = ''

    # The page's help identifier (optional). If a help Id *is* provided then
    # there will be a 'Help' button shown on the preference page.
    help_id = ''
Exemplo n.º 23
0
    def test_load_and_save(self):
        """ load and save """

        p = self.preferences
        p.load(self.example)

        class AcmeUI(HasTraits):
            """ The Acme UI class! """

            # The traits that we want to initialize from preferences.
            bgcolor = Str("red")
            width = Int(60)
            ratio = Float(2.0)
            visible = Bool(False)

        acme_ui = AcmeUI()

        # Make some bindings.
        bind_preference(acme_ui, "bgcolor", "acme.ui.bgcolor")
        bind_preference(acme_ui, "width", "acme.ui.width")
        bind_preference(acme_ui, "ratio", "acme.ui.ratio")
        bind_preference(acme_ui, "visible", "acme.ui.visible")

        # Make sure the helper was initialized properly (with the values in
        # the loaded .ini file *not* the trait defaults!).
        self.assertEqual("blue", acme_ui.bgcolor)
        self.assertEqual(50, acme_ui.width)
        self.assertEqual(1.0, acme_ui.ratio)
        self.assertTrue(acme_ui.visible)

        # Make a change to one of the preference values.
        p.set("acme.ui.bgcolor", "yellow")
        self.assertEqual("yellow", acme_ui.bgcolor)
        self.assertEqual("yellow", p.get("acme.ui.bgcolor"))

        # Save the preferences to a different file.
        tmpdir = tempfile.mkdtemp()
        tmp = join(tmpdir, "tmp.ini")
        p.save(tmp)

        # Load the preferences again from that file.
        p = set_default_preferences(Preferences())
        p.load(tmp)

        acme_ui = AcmeUI()

        # Make some bindings.
        bind_preference(acme_ui, "bgcolor", "acme.ui.bgcolor")
        bind_preference(acme_ui, "width", "acme.ui.width")
        bind_preference(acme_ui, "ratio", "acme.ui.ratio")
        bind_preference(acme_ui, "visible", "acme.ui.visible")

        # Make sure the helper was initialized properly (with the values in
        # the .ini file *not* the trait defaults!).
        self.assertEqual("yellow", acme_ui.bgcolor)
        self.assertEqual(50, acme_ui.width)
        self.assertEqual(1.0, acme_ui.ratio)
        self.assertTrue(acme_ui.visible)

        # Clean up!
        os.remove(tmp)
        os.rmdir(tmpdir)
Exemplo n.º 24
0
from pyface.api import ImageResource
from pyface.timer.api import do_later
from apptools.preferences.api import Preferences

# Internal imports
from hardware import EEGSensor, SAMPLE_RATE, MAX_HISTORY_LENGTH
from matplotlib.figure import Figure
from mpl import MPLFigureEditor

# We package QDarkStyle for convenience. The most current version is
#  at https://pypi.python.org/pypi/QDarkStyle
#  or https://github.com/ColinDuquesnoy/QDarkStyleSheet
# This packages is simply for aesthetics.
import qdarkstyle

preferences = Preferences(filename=os.path.join(
    ETSConfig.get_application_home(True), 'preferences.ini'))

# Custom parameters.
X_WIDTH_S = 6.0
PLOT_STEP = 1


class SensorOperationController(tui.Controller):
    """ UI for controlling the hardware. """

    model = t.Instance(EEGSensor)
    connect = t.Button()
    disconnect = t.Button()

    def _connect_changed(self):
        self.model.connect()