diff --git a/integrationtests/ui/images/bottom_left_origin.gif b/integrationtests/ui/images/bottom_left_origin.gif deleted file mode 100644 index 12b7daaf6..000000000 Binary files a/integrationtests/ui/images/bottom_left_origin.gif and /dev/null differ diff --git a/integrationtests/ui/images/bottom_right_origin.gif b/integrationtests/ui/images/bottom_right_origin.gif deleted file mode 100644 index 5e6e535c0..000000000 Binary files a/integrationtests/ui/images/bottom_right_origin.gif and /dev/null differ diff --git a/integrationtests/ui/images/top_left_origin.gif b/integrationtests/ui/images/top_left_origin.gif deleted file mode 100644 index b12163c2c..000000000 Binary files a/integrationtests/ui/images/top_left_origin.gif and /dev/null differ diff --git a/integrationtests/ui/images/top_right_origin.gif b/integrationtests/ui/images/top_right_origin.gif deleted file mode 100644 index 66ea28d60..000000000 Binary files a/integrationtests/ui/images/top_right_origin.gif and /dev/null differ diff --git a/integrationtests/ui/table_editor_focus_bug.py b/integrationtests/ui/table_editor_focus_bug.py deleted file mode 100644 index 57152b282..000000000 --- a/integrationtests/ui/table_editor_focus_bug.py +++ /dev/null @@ -1,77 +0,0 @@ -# Copyright (c) 2007, Enthought, Inc. -# License: BSD Style. - - -from traits.api import HasTraits, Str, List -from traitsui.api import Group, Item, TableEditor, View -from traitsui.table_column \ - import ObjectColumn - -class Word(HasTraits): - word = Str - -class Foo(HasTraits): - - # arbitrary string containing spaces - input = Str - - # input split on space - parsed = List - - - def _input_changed(self): - words = self.input.split() - - for word in self.parsed[:]: - if word.word in words: - words.remove(word.word) - else: - self.parsed.remove(word) - - - for word in words: - self.parsed.append(Word(word=word)) - - return - - - table_editor = TableEditor( - columns = [ ObjectColumn( name='word') ], - editable=True ) - - - help = Str("""Type in the 'input' box before clicking the Parsed tab. -The first non-whitespace character will cause changes to the parsed trait -and therefore changes to the table rows. That is expected. - -BUG: the table grabs the focus from 'input' and thus subsequent typing goes -into one of the table cells. - -If you click the 'Parsed' tab, to view the table, and then the 'Inputs' tab -the focus will stay with the 'input' box. -""") - - traits_view = View( - Group( Item( 'help', style='readonly'), - Item( 'input' ), - label='Input'), - Group( Item( 'parsed', editor=table_editor), - label='Parsed' ), - dock = 'tab', - resizable=True, - width=320, - height=240 - ) - -if __name__ == '__main__': - - # simple test of the model - foo = Foo() - foo.input = 'these words in the list' - assert( [word.word for word in foo.parsed] == ['these', 'words', 'in', 'the', 'list'] ) - foo.input = 'these dudes in the bar' - assert( [word.word for word in foo.parsed] == ['these', 'in', 'the', 'dudes', 'bar'] ) - - foo.configure_traits( kind='modal' ) - print foo.input, [word.word for word in foo.parsed] - diff --git a/integrationtests/ui/test_array_editor.py b/integrationtests/ui/test_array_editor.py deleted file mode 100644 index 0a3197d0f..000000000 --- a/integrationtests/ui/test_array_editor.py +++ /dev/null @@ -1,51 +0,0 @@ -#------------------------------------------------------------------------------- -# -# ArrayEditor test case -# -# Written by: David C. Morrill -# -# Date: 01/10/2006 -# -# (c) Copyright 2006 by Enthought, Inc. -# License: BSD Style. -# -#------------------------------------------------------------------------------- - -#------------------------------------------------------------------------------- -# Imports: -#------------------------------------------------------------------------------- - -from traits.api \ - import HasPrivateTraits, Array - -from traitsui.api \ - import View, ArrayEditor - -#------------------------------------------------------------------------------- -# 'Test' class: -#------------------------------------------------------------------------------- - -class Test ( HasPrivateTraits ): - - #--------------------------------------------------------------------------- - # Trait definitions: - #--------------------------------------------------------------------------- - - three = Array( int, (3,3) ) - four = Array( float, (4,4), editor = ArrayEditor( width = -50 ) ) - - #--------------------------------------------------------------------------- - # Traits view definitions: - #--------------------------------------------------------------------------- - - view = View( 'three', '_', 'three', '_', 'three~', '_', - 'four', '_', 'four', '_', 'four~', - title = 'ArrayEditor Test Case', - resizable = True ) - -#------------------------------------------------------------------------------- -# Run the test case: -#------------------------------------------------------------------------------- - -if __name__ == '__main__': - Test().configure_traits() diff --git a/integrationtests/ui/test_buttons.py b/integrationtests/ui/test_buttons.py deleted file mode 100644 index 30332c6a4..000000000 --- a/integrationtests/ui/test_buttons.py +++ /dev/null @@ -1,90 +0,0 @@ -# Copyright (c) 2007, Enthought, Inc. -# License: BSD Style. - -from traits.api \ - import * - -from traitsui.api \ - import * - -from traitsui.menu \ - import * - -#------------------------------------------------------------------------------- -# 'Person' class: -#------------------------------------------------------------------------------- - -class Person ( Handler ): - - #--------------------------------------------------------------------------- - # Trait definitions: - #--------------------------------------------------------------------------- - - name = Str - age = Int - phone = Regex( value = '000-0000', regex = '\d\d\d[-]\d\d\d\d' ) - notes = Str - - #--------------------------------------------------------------------------- - # Handles the 'Annoy' button being clicked: - #--------------------------------------------------------------------------- - - def _annoy_clicked ( self, info ): - self.edit_traits( view = View( title = 'Annoying', - kind = 'modal', - buttons = [ 'OK' ] ) ) - -#------------------------------------------------------------------------------- -# Run the tests: -#------------------------------------------------------------------------------- - -if __name__ == '__main__': - AnnoyButton = Action( name = 'Annoy', - tooltip = 'Click me to be annoyed', - enabled_when = 'age >= 40' ) - - person = Person( name = 'Bill', age = 42, phone = '555-1212' ) - - fields = Group( 'name', 'age', 'phone', 'notes~' ) - - person.notes = ("Should have 6 standard 'live' buttons: Undo, Redo, " - "Revert, OK, Cancel, Help") - person.configure_traits( view = View( fields, - kind = 'livemodal', - buttons = LiveButtons ) ) - - person.notes = ("Should have 5 standard 'modal' buttons: Apply, Revert, " - "OK, Cancel, Help") - person.configure_traits( view = View( fields, - buttons = ModalButtons ) ) - - person.notes = "Should have 2 standard buttons: OK, Cancel" - person.configure_traits( - view = View( fields, - buttons = [ OKButton, CancelButton ] ) ) - - person.notes = "Should have 1 standard button: OK (enabled when age >= 40)" - person.configure_traits( - view = View( fields, - buttons = [ Action( name = 'OK', - enabled_when = 'age >= 40' ) ] ) ) - - person.notes = "Should have 1 standard button: OK (visible when age >= 40)" - person.configure_traits( - view = View( fields, - buttons = [ Action( name = 'OK', - visible_when = 'age >= 40' ) ] ) ) - - person.notes = ("Should have 2 standard buttons: OK, Help (defined when " - "age >= 50)") - person.configure_traits( - view = View( fields, - buttons = [ 'OK', Action( name = 'Help', - defined_when = 'age >= 50' ) ] ) ) - - person.notes = ("Should have 1 user and 5 standard buttons: Annoy (enabled " - "when age >= 40), Apply, Revert, OK, Cancel, Help") - person.configure_traits( - view = View( fields, - buttons = [ AnnoyButton ] + ModalButtons ) ) - diff --git a/integrationtests/ui/test_check_list_editor.py b/integrationtests/ui/test_check_list_editor.py deleted file mode 100644 index 132fad1a3..000000000 --- a/integrationtests/ui/test_check_list_editor.py +++ /dev/null @@ -1,67 +0,0 @@ -#------------------------------------------------------------------------------- -# -# CheckListEditor test case for Traits UI -# -# Written by: David C. Morrill -# -# Date: 06/29/2005 -# -# (c) Copyright 2005 by Enthought, Inc. -# License: BSD Style. -# -#------------------------------------------------------------------------------- - -#------------------------------------------------------------------------------- -# Imports: -#------------------------------------------------------------------------------- - -from traits.api \ - import Enum, List - -from traitsui.api \ - import Handler, View, Item, CheckListEditor - -#------------------------------------------------------------------------------- -# Constants: -#------------------------------------------------------------------------------- - -colors = [ 'red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet' ] - -numbers = [ 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', - 'nine', 'ten' ] - -#------------------------------------------------------------------------------- -# 'CheckListTest' class: -#------------------------------------------------------------------------------- - -class CheckListTest ( Handler ): - - #--------------------------------------------------------------------------- - # Trait definitions: - #--------------------------------------------------------------------------- - - case = Enum( 'Colors', 'Numbers' ) - value = List( editor = CheckListEditor( values = colors, cols = 5 ) ) - - #--------------------------------------------------------------------------- - # Event handlers: - #--------------------------------------------------------------------------- - - def object_case_changed ( self, info ): - if self.case == 'Colors': - info.value.factory.values = colors - else: - info.value.factory.values = numbers - -#------------------------------------------------------------------------------- -# Run the tests: -#------------------------------------------------------------------------------- - -if __name__ == '__main__': - clt = CheckListTest() - clt.configure_traits( - view = View( 'case', '_', Item( 'value', id = 'value' ) ) ) - print 'value:', clt.value - clt.configure_traits( - view = View( 'case', '_', Item( 'value@', id = 'value' ) ) ) - print 'value:', clt.value diff --git a/integrationtests/ui/test_check_list_editor2.py b/integrationtests/ui/test_check_list_editor2.py deleted file mode 100644 index 8c50864b7..000000000 --- a/integrationtests/ui/test_check_list_editor2.py +++ /dev/null @@ -1,69 +0,0 @@ -#------------------------------------------------------------------------------- -# -# CheckListEditor test case for Traits UI -# -# Written by: David C. Morrill -# -# Date: 06/29/2005 -# -# (c) Copyright 2005 by Enthought, Inc. -# License: BSD Style. -# -#------------------------------------------------------------------------------- - -#------------------------------------------------------------------------------- -# Imports: -#------------------------------------------------------------------------------- - -from traits.api \ - import Enum, List, Str - -from traitsui.api \ - import Handler, View, Item, CheckListEditor - -#------------------------------------------------------------------------------- -# 'CheckListTest' class: -#------------------------------------------------------------------------------- - -class CheckListTest ( Handler ): - - #--------------------------------------------------------------------------- - # Trait definitions: - #--------------------------------------------------------------------------- - - value = List( editor = CheckListEditor( name = 'values', cols = 5 ) ) - values = List( Str ) - values_text = Str( 'red orange yellow green blue indigo violet' ) - - #--------------------------------------------------------------------------- - # Traits view definitions: - #--------------------------------------------------------------------------- - - simple_view = View( 'value', 'values_text@' ) - custom_view = View( 'value@', 'values_text@' ) - - #--------------------------------------------------------------------------- - # 'Initializes the object: - #--------------------------------------------------------------------------- - - def __init__ ( self, **traits ): - super( CheckListTest, self ).__init__( **traits ) - self._values_text_changed() - - #--------------------------------------------------------------------------- - # Event handlers: - #--------------------------------------------------------------------------- - - def _values_text_changed ( self ): - self.values = self.values_text.split() - -#------------------------------------------------------------------------------- -# Run the tests: -#------------------------------------------------------------------------------- - -if __name__ == '__main__': - clt = CheckListTest() - clt.configure_traits( view = 'simple_view' ) - print 'value:', clt.value - clt.configure_traits( view = 'custom_view' ) - print 'value:', clt.value diff --git a/integrationtests/ui/test_code_editor.py b/integrationtests/ui/test_code_editor.py deleted file mode 100644 index 055fb6dbb..000000000 --- a/integrationtests/ui/test_code_editor.py +++ /dev/null @@ -1,91 +0,0 @@ -#------------------------------------------------------------------------------- -# -# Test using a KeyBindings object with the traits Codeditor -# -# Written by: David C. Morrill -# -# Date: 09/22/2005 -# -# (c) Copyright 2005 by Enthought, Inc. -# License: BSD Style. -# -#------------------------------------------------------------------------------- - -#------------------------------------------------------------------------------- -# Imports: -#------------------------------------------------------------------------------- - -from traits.api \ - import HasPrivateTraits, Code, Str - -from traitsui.api \ - import View, Item, Handler, CodeEditor - -from traitsui.key_bindings \ - import KeyBinding, KeyBindings - -#------------------------------------------------------------------------------- -# Define a KeyBindings object: -#------------------------------------------------------------------------------- - -key_bindings = KeyBindings( - - KeyBinding( binding1 = 'Ctrl-s', - description = 'Save to a file', - method_name = 'save_file' ), - - KeyBinding( binding1 = 'Ctrl-r', - description = 'Run script', - method_name = 'run_script' ), - - KeyBinding( binding1 = 'Ctrl-q', - description = 'Edit key bindings', - method_name = 'edit_bindings' ) -) - -#------------------------------------------------------------------------------- -# 'CodeHandler' class: -#------------------------------------------------------------------------------- - -class CodeHandler ( Handler ): - - def save_file ( self, info ): - info.object.status = "save file" - - def run_script ( self, info ): - info.object.status = "run script" - - def edit_bindings ( self, info ): - info.object.status = "edit bindings" - key_bindings.edit_traits() - -#------------------------------------------------------------------------------- -# 'TestCode' class: -#------------------------------------------------------------------------------- - -class TestCode ( HasPrivateTraits ): - - code = Code - status = Str - - view = View( - [ Item( 'code', - style = 'custom', - resizable = True, - editor = CodeEditor( key_bindings = key_bindings ) ), - 'status~', - '|<>' ], - id = 'traitsui.tests.test_code_editor.TestCode', - title = 'Sample Code Editor', - width = 0.4, - height = 0.4, - resizable = True, - handler = CodeHandler() ) - -#------------------------------------------------------------------------------- -# Run the test: -#------------------------------------------------------------------------------- - -if __name__ == '__main__': - TestCode().configure_traits() - diff --git a/integrationtests/ui/test_enum_dynamic.py b/integrationtests/ui/test_enum_dynamic.py deleted file mode 100644 index 53166c6e5..000000000 --- a/integrationtests/ui/test_enum_dynamic.py +++ /dev/null @@ -1,27 +0,0 @@ -# Copyright (c) 2007, Enthought, Inc. -# License: BSD Style. - -from traits.api import * -from traitsui.api import * - -def evaluate_value(v): - print 'evaluate_value', v - return str(v) - -class Team ( HasTraits ): - - captain = Str( 'Dick' ) - players = List( [ 'Tom', 'Dick', 'Harry', 'Sally' ], Str ) - - captain_editor = EnumEditor( name = 'players', evaluate=evaluate_value ) - - view = View( Item( 'captain', editor = captain_editor), - '_', - 'players@', - height=200 ) - -if __name__ == '__main__': - team = Team() - team.configure_traits() - team.print_traits() - diff --git a/integrationtests/ui/test_enum_editor.py b/integrationtests/ui/test_enum_editor.py deleted file mode 100644 index 72a572f71..000000000 --- a/integrationtests/ui/test_enum_editor.py +++ /dev/null @@ -1,56 +0,0 @@ -#------------------------------------------------------------------------------ -# Copyright (c) 2005, Enthought, Inc. -# All rights reserved. -# -# This software is provided without warranty under the terms of the BSD -# license included in /LICENSE.txt and may be redistributed only -# under the conditions described in the aforementioned license. The license -# is also available online at http://www.enthought.com/licenses/BSD.txt -# Thanks for using Enthought open source! -# -# Author: David C. Morrill -# Date: 04/06/2005 -# Description: Test the EnumEditor trait editor. -#------------------------------------------------------------------------------ - -#------------------------------------------------------------------------------- -# Imports: -#------------------------------------------------------------------------------- - -from traits.api \ - import HasTraits, Trait, Enum, Range - -from traitsui.api \ - import EnumEditor - -#------------------------------------------------------------------------------- -# Trait definitions: -#------------------------------------------------------------------------------- - -values = [ 'one', 'two', 'three', 'four' ] -enum = Enum( *values ) -range = Range( 1, 4 ) - -#------------------------------------------------------------------------------- -# 'TestEnumEditor' class: -#------------------------------------------------------------------------------- - -class TestEnumEditor ( HasTraits ): - - #--------------------------------------------------------------------------- - # Trait definitions: - #--------------------------------------------------------------------------- - - value = Trait( 1, enum, range, - editor = EnumEditor( values = values, - evaluate = int ) ) - -#------------------------------------------------------------------------------- -# Run the test: -#------------------------------------------------------------------------------- - -if __name__ == '__main__': - test = TestEnumEditor() - test.configure_traits() - test.print_traits() - diff --git a/integrationtests/ui/test_html_editor.py b/integrationtests/ui/test_html_editor.py deleted file mode 100644 index f5e658c8c..000000000 --- a/integrationtests/ui/test_html_editor.py +++ /dev/null @@ -1,84 +0,0 @@ -#------------------------------------------------------------------------------- -# -# Test case for the HTMLEditor. -# -# Written by: David C. Morrill -# -# Date: 09/22/2005 -# -# (c) Copyright 2005 by Enthought, Inc. -# License: BSD Style. -# -#------------------------------------------------------------------------------- - -#------------------------------------------------------------------------------- -# Imports: -#------------------------------------------------------------------------------- - -from traits.api \ - import HasPrivateTraits, Code - -from traitsui.api \ - import View, Group, Item, HTMLEditor - -#------------------------------------------------------------------------------- -# Constants: -#------------------------------------------------------------------------------- - -sample = """This is a code block: - - def foo ( bar ): - print 'bar:', bar - -This is an unordered list: - - An - - unordered - - list - -This is an ordered list: - * One - * Two - * Three - -Lists can be nested: - * One - * 1.1 - * 1.2 - * Two - * 2.1 - * 2.2 -""" - -#------------------------------------------------------------------------------- -# 'TestHTML' class: -#------------------------------------------------------------------------------- - -class TestHTML ( HasPrivateTraits ): - - #--------------------------------------------------------------------------- - # Trait definitions: - #--------------------------------------------------------------------------- - - # Text string to display as HTML: - html = Code( sample ) - - #--------------------------------------------------------------------------- - # Traits view definitions: - #--------------------------------------------------------------------------- - - view = View( Group( - [ Item( 'html#@', editor = HTMLEditor() ), '|<>' ], - [ '{Enter formatted text and/or HTML below:}@', - 'html#@', '|<>' ], - '|<>', layout = 'split' ), - title = 'HTML Editor Test', - resizable = True, - width = 0.4, - height = 0.6 ) - -#------------------------------------------------------------------------------- -# Run the test: -#------------------------------------------------------------------------------- - -if __name__ == '__main__': - TestHTML().configure_traits() diff --git a/integrationtests/ui/test_instance_drag.py b/integrationtests/ui/test_instance_drag.py deleted file mode 100644 index bd61e1ffd..000000000 --- a/integrationtests/ui/test_instance_drag.py +++ /dev/null @@ -1,240 +0,0 @@ -#------------------------------------------------------------------------------ -# Copyright (c) 2005, Enthought, Inc. -# All rights reserved. -# -# This software is provided without warranty under the terms of the BSD -# license included in /LICENSE.txt and may be redistributed only -# under the conditions described in the aforementioned license. The license -# is also available online at http://www.enthought.com/licenses/BSD.txt -# Thanks for using Enthought open source! -# -# Author: David C. Morrill -# Date: 12/04/2004 -# Description: Test case for the traits tree editor. -#------------------------------------------------------------------------------ - -#------------------------------------------------------------------------------- -# Imports: -#------------------------------------------------------------------------------- - -from traits.api \ - import HasTraits, Str, Regex, List, Instance - -from traitsui.api \ - import TreeEditor, TreeNode, View, Group, Item, Handler, InstanceEditor - -from traitsui.instance_choice \ - import InstanceDropChoice - -from traitsui.menu \ - import Menu, Action, Separator - -from traitsui.wx.tree_editor \ - import NewAction, CopyAction, CutAction, PasteAction, DeleteAction, \ - RenameAction - -#------------------------------------------------------------------------------- -# 'Employee' class: -#------------------------------------------------------------------------------- - -class Employee ( HasTraits ): - name = Str( '' ) - title = Str - phone = Regex( regex = r'\d\d\d-\d\d\d\d' ) - - view = View( 'title', 'phone' ) - - def default_title ( self ): - self.title = 'Senior Engineer' - -#------------------------------------------------------------------------------- -# 'Department' class: -#------------------------------------------------------------------------------- - -class Department ( HasTraits ): - name = Str( '' ) - employees = List( Employee ) - - view = View( [ 'employees', '|<>' ] ) - -#------------------------------------------------------------------------------- -# 'Company' class: -#------------------------------------------------------------------------------- - -class Company ( HasTraits ): - name = Str( '' ) - departments = List( Department ) - employees = List( Employee ) - -#------------------------------------------------------------------------------- -# 'Partner' class: -#------------------------------------------------------------------------------- - -class Partner ( HasTraits ): - name = Str( '' ) - company = Instance( Company ) - eom = Instance( Employee ) - dom = Instance( Department ) - -#------------------------------------------------------------------------------- -# Create a hierarchy: -#------------------------------------------------------------------------------- - -jason = Employee( - name = 'Jason', - title = 'Sr. Engineer', - phone = '536-1057' ) - -mike = Employee( - name = 'Mike', - title = 'Sr. Engineer', - phone = '536-1057' ) - -dave = Employee( - name = 'Dave', - title = 'Sr. Engineer', - phone = '536-1057' ) - -martin = Employee( - name = 'Martin', - title = 'Sr. Engineer', - phone = '536-1057' ) - -duncan = Employee( - name = 'Duncan', - title = 'Sr. Engineer' ) - -partner = Partner( - name = 'eric', - company = Company( - name = 'Enthought, Inc.', - departments = [ - Department( - name = 'Business', - employees = [ jason, mike ] - ), - Department( - name = 'Scientific', - employees = [ dave, martin, duncan ] - ) - ], - employees = [ dave, martin, mike, duncan, jason ] - ) -) - -#------------------------------------------------------------------------------- -# Define the tree trait editor: -#------------------------------------------------------------------------------- - -no_view = View() - -tree_editor = TreeEditor( - editable = False, - nodes = [ - TreeNode( node_for = [ Company ], - auto_open = True, - children = '', - label = 'name', - view = View( [ 'name', '|<' ] ) ), - TreeNode( node_for = [ Company ], - auto_open = True, - children = 'departments', - label = '=Departments', - view = no_view, - add = [ Department ] ), - TreeNode( node_for = [ Company ], - auto_open = True, - children = 'employees', - label = '=Employees', - view = no_view, - add = [ Employee ] ), - TreeNode( node_for = [ Department ], - auto_open = True, - children = 'employees', - label = 'name', - menu = Menu( NewAction, - Separator(), - DeleteAction, - Separator(), - RenameAction, - Separator(), - CopyAction, - CutAction, - PasteAction ), - view = View( [ 'name', '|<' ] ), - add = [ Employee ] ), - TreeNode( node_for = [ Employee ], - auto_open = True, - label = 'name', - menu = Menu( NewAction, - Separator(), - Action( name = 'Default title', - action = 'object.default_title' ), - Action( name = 'Department', - action = 'handler.employee_department(editor,object)' ), - Separator(), - CopyAction, - CutAction, - PasteAction, - Separator(), - DeleteAction, - Separator(), - RenameAction ), - view = View( [ 'name', 'title', 'phone', '|<' ] ) ) - ] -) - -#------------------------------------------------------------------------------- -# 'TreeHandler' class: -#------------------------------------------------------------------------------- - -class TreeHandler ( Handler ): - - def employee_department ( self, editor, object ): - dept = editor.get_parent( object ) - print '%s works in the %s department.' % ( object.name, dept.name ) - -#------------------------------------------------------------------------------- -# Define the View to use: -#------------------------------------------------------------------------------- - -view = View( - Group( - [ Item( 'company', - editor = tree_editor, - resizable = True ), - '|<>' ], - Group( - [ '{Employee of the Month}@', - Item( 'eom@', - editor = InstanceEditor( values = [ - InstanceDropChoice( klass = Employee, - selectable = True ) ] ), - resizable = True ), - '|<>' ], - [ '{Department of the Month}@', - Item( 'dom@', - editor = InstanceEditor( values = [ - InstanceDropChoice( klass = Department ) ] ), - resizable = True ), - '|<>' ], - show_labels = False, - layout = 'split' ), - orientation = 'horizontal', - show_labels = False, - layout = 'split' ), - title = 'Company Structure', - handler = TreeHandler(), - buttons = [ 'OK', 'Cancel' ], - resizable = True, - width = .5, - height = .5 -) - -#------------------------------------------------------------------------------- -# Edit it: -#------------------------------------------------------------------------------- - -if __name__ == '__main__': - partner.configure_traits( view = view ) - diff --git a/integrationtests/ui/test_instance_editor.py b/integrationtests/ui/test_instance_editor.py deleted file mode 100644 index 1faeb8d58..000000000 --- a/integrationtests/ui/test_instance_editor.py +++ /dev/null @@ -1,73 +0,0 @@ -# Copyright (c) 2007, Enthought, Inc. -# License: BSD Style. - -from traits.api import * -from traitsui.api import * -from traitsui.instance_choice import InstanceChoice - -#------------------------------------------------------------------------------- -# 'Person' class: -#------------------------------------------------------------------------------- - -class Person ( HasStrictTraits ): - - #--------------------------------------------------------------------------- - # Trait definitions: - #--------------------------------------------------------------------------- - - name = Str - age = Int - phone = Regex( value = '000-0000', regex = '\d\d\d[-]\d\d\d\d' ) - - #--------------------------------------------------------------------------- - # Traits view definition: - #--------------------------------------------------------------------------- - - traits_view = View( 'name', 'age', 'phone' ) - -#------------------------------------------------------------------------------- -# Sample data: -#------------------------------------------------------------------------------- - -people = [ - Person( name = 'Dave', age = 39, phone = '555-1212' ), - Person( name = 'Mike', age = 28, phone = '555-3526' ), - Person( name = 'Joe', age = 34, phone = '555-6943' ), - Person( name = 'Tom', age = 22, phone = '555-7586' ), - Person( name = 'Dick', age = 63, phone = '555-3895' ), - Person( name = 'Harry', age = 46, phone = '555-3285' ), - Person( name = 'Sally', age = 43, phone = '555-8797' ), - Person( name = 'Fields', age = 31, phone = '555-3547' ) -] - -#------------------------------------------------------------------------------- -# 'Team' class: -#------------------------------------------------------------------------------- - -class Team ( HasStrictTraits ): - - #--------------------------------------------------------------------------- - # Trait definitions: - #--------------------------------------------------------------------------- - - name = Str - captain = Instance( Person ) - roster = List( Person ) - - #--------------------------------------------------------------------------- - # Traits view definitions: - #--------------------------------------------------------------------------- - - traits_view = View( 'name', '_', - Item( 'captain@', - editor = InstanceEditor( name = 'roster' ) ), - buttons = [ 'Undo', 'OK', 'Cancel' ] ) - -#------------------------------------------------------------------------------- -# Run the test: -#------------------------------------------------------------------------------- - -if __name__ == '__main__': - Team( name = 'Vultures', - captain = people[0], - roster = people ).configure_traits() diff --git a/integrationtests/ui/test_instance_editor2.py b/integrationtests/ui/test_instance_editor2.py deleted file mode 100644 index 16b9b370a..000000000 --- a/integrationtests/ui/test_instance_editor2.py +++ /dev/null @@ -1,77 +0,0 @@ -# Copyright (c) 2007, Enthought, Inc. -# License: BSD Style. - -from traits.api import * -from traitsui.api import * -from traitsui.instance_choice \ - import InstanceChoice, InstanceFactoryChoice - -#------------------------------------------------------------------------------- -# 'Person' class: -#------------------------------------------------------------------------------- - -class Person ( HasStrictTraits ): - - #--------------------------------------------------------------------------- - # Trait definitions: - #--------------------------------------------------------------------------- - - name = Str - age = Int - phone = Regex( value = '000-0000', regex = '\d\d\d[-]\d\d\d\d' ) - - #--------------------------------------------------------------------------- - # Traits view definition: - #--------------------------------------------------------------------------- - - traits_view = View( 'name', 'age', 'phone' ) - -#------------------------------------------------------------------------------- -# Sample data: -#------------------------------------------------------------------------------- - -people = [ - Person( name = 'Dave', age = 39, phone = '555-1212' ), - Person( name = 'Mike', age = 28, phone = '555-3526' ), - Person( name = 'Joe', age = 34, phone = '555-6943' ), - Person( name = 'Tom', age = 22, phone = '555-7586' ), - Person( name = 'Dick', age = 63, phone = '555-3895' ), - Person( name = 'Harry', age = 46, phone = '555-3285' ), - Person( name = 'Sally', age = 43, phone = '555-8797' ), - Person( name = 'Fields', age = 31, phone = '555-3547' ) -] - -#------------------------------------------------------------------------------- -# 'Team' class: -#------------------------------------------------------------------------------- - -class Team ( HasStrictTraits ): - - #--------------------------------------------------------------------------- - # Trait definitions: - #--------------------------------------------------------------------------- - - name = Str - captain = Instance( Person ) - roster = List( Person ) - - #--------------------------------------------------------------------------- - # Traits view definitions: - #--------------------------------------------------------------------------- - - traits_view = View( 'name', '_', - Item( 'captain@', - editor = InstanceEditor( name = 'roster', - values = [ - InstanceFactoryChoice( - klass = Person, - name = 'Non player' ) ] ) ) ) - -#------------------------------------------------------------------------------- -# Run the test: -#------------------------------------------------------------------------------- - -if __name__ == '__main__': - Team( name = 'Vultures', - captain = people[0], - roster = people ).configure_traits() diff --git a/integrationtests/ui/test_instance_editor3.py b/integrationtests/ui/test_instance_editor3.py deleted file mode 100644 index 36744ea1a..000000000 --- a/integrationtests/ui/test_instance_editor3.py +++ /dev/null @@ -1,73 +0,0 @@ -# Copyright (c) 2007, Enthought, Inc. -# License: BSD Style. - -from traits.api import * -from traitsui.api import * -from traitsui.instance_choice import InstanceChoice - -#------------------------------------------------------------------------------- -# 'Person' class: -#------------------------------------------------------------------------------- - -class Person ( HasStrictTraits ): - - #--------------------------------------------------------------------------- - # Trait definitions: - #--------------------------------------------------------------------------- - - name = Str - age = Int - phone = Regex( value = '000-0000', regex = '\d\d\d[-]\d\d\d\d' ) - - #--------------------------------------------------------------------------- - # Traits view definition: - #--------------------------------------------------------------------------- - - traits_view = View( 'name', 'age', 'phone' ) - -#------------------------------------------------------------------------------- -# Sample data: -#------------------------------------------------------------------------------- - -people = [ - Person( name = 'Dave', age = 39, phone = '555-1212' ), - Person( name = 'Mike', age = 28, phone = '555-3526' ), - Person( name = 'Joe', age = 34, phone = '555-6943' ), - Person( name = 'Tom', age = 22, phone = '555-7586' ), - Person( name = 'Dick', age = 63, phone = '555-3895' ), - Person( name = 'Harry', age = 46, phone = '555-3285' ), - Person( name = 'Sally', age = 43, phone = '555-8797' ), - Person( name = 'Fields', age = 31, phone = '555-3547' ) -] - -#------------------------------------------------------------------------------- -# 'Team' class: -#------------------------------------------------------------------------------- - -class Team ( HasStrictTraits ): - - #--------------------------------------------------------------------------- - # Trait definitions: - #--------------------------------------------------------------------------- - - name = Str - captain = Instance( Person ) - roster = List( Person ) - - #--------------------------------------------------------------------------- - # Traits view definitions: - #--------------------------------------------------------------------------- - - traits_view = View( 'name', '_', - Item( 'captain@', - editor = InstanceEditor( name = 'roster' ) ), '_', - 'roster' ) - -#------------------------------------------------------------------------------- -# Run the test: -#------------------------------------------------------------------------------- - -if __name__ == '__main__': - Team( name = 'Vultures', - captain = people[0], - roster = people ).configure_traits() diff --git a/integrationtests/ui/test_instance_editor4.py b/integrationtests/ui/test_instance_editor4.py deleted file mode 100644 index c89edf8fd..000000000 --- a/integrationtests/ui/test_instance_editor4.py +++ /dev/null @@ -1,74 +0,0 @@ -# Copyright (c) 2007, Enthought, Inc. -# License: BSD Style. - -from traits.api import * -from traitsui.api import * -from traitsui.instance_choice import InstanceChoice - -#------------------------------------------------------------------------------- -# 'Person' class: -#------------------------------------------------------------------------------- - -class Person ( HasStrictTraits ): - - #--------------------------------------------------------------------------- - # Trait definitions: - #--------------------------------------------------------------------------- - - name = Str - age = Int - phone = Regex( value = '000-0000', regex = '\d\d\d[-]\d\d\d\d' ) - - #--------------------------------------------------------------------------- - # Traits view definition: - #--------------------------------------------------------------------------- - - traits_view = View( 'name', 'age', 'phone' ) - -#------------------------------------------------------------------------------- -# Sample data: -#------------------------------------------------------------------------------- - -people = [ - Person( name = 'Dave', age = 39, phone = '555-1212' ), - Person( name = 'Mike', age = 28, phone = '555-3526' ), - Person( name = 'Joe', age = 34, phone = '555-6943' ), - Person( name = 'Tom', age = 22, phone = '555-7586' ), - Person( name = 'Dick', age = 63, phone = '555-3895' ), - Person( name = 'Harry', age = 46, phone = '555-3285' ), - Person( name = 'Sally', age = 43, phone = '555-8797' ), - Person( name = 'Fields', age = 31, phone = '555-3547' ) -] - -#------------------------------------------------------------------------------- -# 'Team' class: -#------------------------------------------------------------------------------- - -class Team ( HasStrictTraits ): - - #--------------------------------------------------------------------------- - # Trait definitions: - #--------------------------------------------------------------------------- - - name = Str - captain = Instance( Person ) - roster = List( Person ) - - #--------------------------------------------------------------------------- - # Traits view definitions: - #--------------------------------------------------------------------------- - - traits_view = View( 'name', '_', - Item( 'captain@', - editor = InstanceEditor( name = 'roster', - editable = False ) ), - '_', 'roster' ) - -#------------------------------------------------------------------------------- -# Run the test: -#------------------------------------------------------------------------------- - -if __name__ == '__main__': - Team( name = 'Vultures', - captain = people[0], - roster = people ).configure_traits() diff --git a/integrationtests/ui/test_instance_editor5.py b/integrationtests/ui/test_instance_editor5.py deleted file mode 100644 index c682cff0f..000000000 --- a/integrationtests/ui/test_instance_editor5.py +++ /dev/null @@ -1,82 +0,0 @@ -# Copyright (c) 2007, Enthought, Inc. -# License: BSD Style. - -from traits.api import * -from traitsui.api import * -from traitsui.instance_choice \ - import InstanceChoice, InstanceFactoryChoice - -#------------------------------------------------------------------------------- -# 'Person' class: -#------------------------------------------------------------------------------- - -class Person ( HasStrictTraits ): - - #--------------------------------------------------------------------------- - # Trait definitions: - #--------------------------------------------------------------------------- - - name = Str - age = Int - phone = Regex( value = '000-0000', regex = '\d\d\d[-]\d\d\d\d' ) - - #--------------------------------------------------------------------------- - # Traits view definition: - #--------------------------------------------------------------------------- - - traits_view = View( 'name~', 'age~', 'phone~' ) - edit_view = View( 'name', 'age', 'phone' ) - -#------------------------------------------------------------------------------- -# Sample data: -#------------------------------------------------------------------------------- - -people = [ - Person( name = 'Dave', age = 39, phone = '555-1212' ), - Person( name = 'Mike', age = 28, phone = '555-3526' ), - Person( name = 'Joe', age = 34, phone = '555-6943' ), - Person( name = 'Tom', age = 22, phone = '555-7586' ), - Person( name = 'Dick', age = 63, phone = '555-3895' ), - Person( name = 'Harry', age = 46, phone = '555-3285' ), - Person( name = 'Sally', age = 43, phone = '555-8797' ), - Person( name = 'Fields', age = 31, phone = '555-3547' ) -] - -#------------------------------------------------------------------------------- -# 'Team' class: -#------------------------------------------------------------------------------- - -class Team ( HasStrictTraits ): - - #--------------------------------------------------------------------------- - # Trait definitions: - #--------------------------------------------------------------------------- - - name = Str - captain = Instance( Person ) - roster = List( Person ) - - #--------------------------------------------------------------------------- - # Traits view definitions: - #--------------------------------------------------------------------------- - - traits_view = View( [ [ 'name', '_', - Item( 'captain@', - editor = InstanceEditor( name = 'roster', - editable = False, - values = [ - InstanceFactoryChoice( - klass = Person, - name = 'Non player', - view = 'edit_view' ) ] ) ), - '_' ], - [ 'captain@', '|<>' ] ] ) - -#------------------------------------------------------------------------------- -# Run the test: -#------------------------------------------------------------------------------- - -if __name__ == '__main__': - Team( name = 'Vultures', - captain = people[0], - roster = people ).configure_traits() diff --git a/integrationtests/ui/test_instance_editor6.py b/integrationtests/ui/test_instance_editor6.py deleted file mode 100644 index 71ca0ae09..000000000 --- a/integrationtests/ui/test_instance_editor6.py +++ /dev/null @@ -1,81 +0,0 @@ -# Copyright (c) 2007, Enthought, Inc. -# License: BSD Style. - -from traits.api import * -from traitsui.api import * -from traitsui.instance_choice \ - import InstanceChoice, InstanceFactoryChoice - -#------------------------------------------------------------------------------- -# 'Person' class: -#------------------------------------------------------------------------------- - -class Person ( HasStrictTraits ): - - #--------------------------------------------------------------------------- - # Trait definitions: - #--------------------------------------------------------------------------- - - name = Str - age = Int - phone = Regex( value = '000-0000', regex = '\d\d\d[-]\d\d\d\d' ) - - #--------------------------------------------------------------------------- - # Traits view definition: - #--------------------------------------------------------------------------- - - traits_view = View( 'name', 'age', 'phone', - buttons = [ 'OK', 'Cancel' ] ) - -#------------------------------------------------------------------------------- -# Sample data: -#------------------------------------------------------------------------------- - -people = [ - Person( name = 'Dave', age = 39, phone = '555-1212' ), - Person( name = 'Mike', age = 28, phone = '555-3526' ), - Person( name = 'Joe', age = 34, phone = '555-6943' ), - Person( name = 'Tom', age = 22, phone = '555-7586' ), - Person( name = 'Dick', age = 63, phone = '555-3895' ), - Person( name = 'Harry', age = 46, phone = '555-3285' ), - Person( name = 'Sally', age = 43, phone = '555-8797' ), - Person( name = 'Fields', age = 31, phone = '555-3547' ) -] - -#------------------------------------------------------------------------------- -# 'Team' class: -#------------------------------------------------------------------------------- - -class Team ( HasStrictTraits ): - - #--------------------------------------------------------------------------- - # Trait definitions: - #--------------------------------------------------------------------------- - - name = Str - captain = Instance( Person ) - roster = List( Person ) - - #--------------------------------------------------------------------------- - # Traits view definitions: - #--------------------------------------------------------------------------- - - traits_view = View( [ 'name', '_', - Item( 'captain', - editor = InstanceEditor( name = 'roster', - label = 'Edit...', - values = [ - InstanceFactoryChoice( - klass = Person, - name = 'Non player', - view = 'edit_view' ) ] ) ) ], - buttons = [ 'OK', 'Cancel' ] ) - -#------------------------------------------------------------------------------- -# Run the test: -#------------------------------------------------------------------------------- - -if __name__ == '__main__': - Team( name = 'Vultures', - captain = people[0], - roster = people ).configure_traits() diff --git a/integrationtests/ui/test_large_range_editor.py b/integrationtests/ui/test_large_range_editor.py deleted file mode 100644 index 74b9218e0..000000000 --- a/integrationtests/ui/test_large_range_editor.py +++ /dev/null @@ -1,42 +0,0 @@ -# Copyright (c) 2007, Enthought, Inc. -# License: BSD Style. - -from traits.api import HasTraits, Float, List -from traitsui.api import View, Item, RangeEditor - -# Tests the Large Range Slider editor. It also tests the case where the -# editor is embedded in a list. -class TestRangeEditor(HasTraits): - x = Float - low = Float(123.123) - high = Float(1123.123) - list = List(Float( - editor = RangeEditor(low_name='low', - high_name = 'high', - # These force the large range - # slider to be used. - low=100.0, - high=10000.123) - ) - ) - view = View(Item(name='x', - editor = RangeEditor(low_name='low', - high_name = 'high', - # These force the large range - # slider to be used. - low=100.0, - high=10000.123) - ), - Item('list'), - resizable=True - ) - -def test(): - a = TestRangeEditor() - a.x = 500 - a.list.append(500) - a.edit_traits() # Just close the resulting dialog. - assert a.x == 500 - assert a.list[0] == 500 - -test() diff --git a/integrationtests/ui/test_list_traits_ui.py b/integrationtests/ui/test_list_traits_ui.py deleted file mode 100644 index b513add74..000000000 --- a/integrationtests/ui/test_list_traits_ui.py +++ /dev/null @@ -1,134 +0,0 @@ -#------------------------------------------------------------------------------- -# -# TableEditor test case for Traits UI -# -# Written by: David C. Morrill -# -# Date: 11/11/2005 -# -# (c) Copyright 2005 by Enthought, Inc. -# License: BSD Style. -# -#------------------------------------------------------------------------------- - -#------------------------------------------------------------------------------- -# Imports: -#------------------------------------------------------------------------------- - -from traits.api \ - import HasStrictTraits, Str, Int, Regex, List, Instance - -from traitsui.api \ - import View, Item, VSplit, TableEditor, ListEditor - -from traitsui.table_column \ - import ObjectColumn - -from traitsui.table_filter \ - import TableFilter, RuleTableFilter, RuleFilterTemplate, \ - MenuFilterTemplate, EvalFilterTemplate - -#------------------------------------------------------------------------------- -# 'Person' class: -#------------------------------------------------------------------------------- - -class Person ( HasStrictTraits ): - - #--------------------------------------------------------------------------- - # Trait definitions: - #--------------------------------------------------------------------------- - - name = Str - age = Int - phone = Regex( value = '000-0000', regex = '\d\d\d[-]\d\d\d\d' ) - - #--------------------------------------------------------------------------- - # Traits view definition: - #--------------------------------------------------------------------------- - - traits_view = View( 'name', 'age', 'phone', - width = 0.18, - buttons = [ 'OK', 'Cancel' ] ) - -#------------------------------------------------------------------------------- -# Sample data: -#------------------------------------------------------------------------------- - -people = [ - Person( name = 'Dave', age = 39, phone = '555-1212' ), - Person( name = 'Mike', age = 28, phone = '555-3526' ), - Person( name = 'Joe', age = 34, phone = '555-6943' ), - Person( name = 'Tom', age = 22, phone = '555-7586' ), - Person( name = 'Dick', age = 63, phone = '555-3895' ), - Person( name = 'Harry', age = 46, phone = '555-3285' ), - Person( name = 'Sally', age = 43, phone = '555-8797' ), - Person( name = 'Fields', age = 31, phone = '555-3547' ) -] - -#------------------------------------------------------------------------------- -# Table editor definition: -#------------------------------------------------------------------------------- - -filters = [ EvalFilterTemplate, MenuFilterTemplate, RuleFilterTemplate ] - -table_editor = TableEditor( - columns = [ ObjectColumn( name = 'name' ), - ObjectColumn( name = 'age' ), - ObjectColumn( name = 'phone' ) ], - editable = True, - deletable = True, - sortable = True, - sort_model = True, - filters = filters, - search = RuleTableFilter(), - row_factory = Person -) - -#------------------------------------------------------------------------------- -# 'ListTraitTest' class: -#------------------------------------------------------------------------------- - -class ListTraitTest ( HasStrictTraits ): - - #--------------------------------------------------------------------------- - # Trait definitions: - #--------------------------------------------------------------------------- - - people = List( Person ) - - #--------------------------------------------------------------------------- - # Traits view definitions: - #--------------------------------------------------------------------------- - - traits_view = View( - VSplit( - Item( 'people', - id = 'table', - editor = table_editor ), - Item( 'people@', - id = 'list', - editor = ListEditor( style = 'custom', - rows = 5 ) ), - Item( 'people@', - id = 'notebook', - editor = ListEditor( use_notebook = True, - deletable = True, - export = 'DockShellWindow', - page_name = '.name' ) ), - id = 'splitter', - show_labels = False ), - title = 'List Trait Editor Test', - id = 'traitsui.tests.list_traits_ui_test', - dock = 'horizontal', - width = .4, - height = .6, - resizable = True, - kind = 'live' ) - -#------------------------------------------------------------------------------- -# Run the tests: -#------------------------------------------------------------------------------- - -if __name__ == '__main__': - ListTraitTest( people = people ).configure_traits() - diff --git a/integrationtests/ui/test_numeric_editor.py b/integrationtests/ui/test_numeric_editor.py deleted file mode 100644 index ecf5fe391..000000000 --- a/integrationtests/ui/test_numeric_editor.py +++ /dev/null @@ -1,126 +0,0 @@ -#------------------------------------------------------------------------------- -# -# NumericEditor test case for Traits UI -# -# Written by: David C. Morrill -# -# Date: 11/29/2005 -# -# (c) Copyright 2005 by Enthought, Inc. -# License: BSD Style. -# -#------------------------------------------------------------------------------- - -#------------------------------------------------------------------------------- -# Imports: -#------------------------------------------------------------------------------- - -from traits.api \ - import HasPrivateTraits, Array, Instance - -from traitsui.api \ - import View, Item, HGroup - -from traitsui.table_column \ - import NumericColumn - -from traitsui.wx.numeric_editor \ - import ToolkitEditorFactory as NumericEditor - -from blockcanvas.model.api \ - import ANumericModel, NumericArrayModel, ReductionModel, SelectionModel, \ - NumericItem, ExpressionFilter, IndexFilter - -from numpy \ - import array, sin, arange - -#------------------------------------------------------------------------------- -# Defines the numeric editor: -#------------------------------------------------------------------------------- - -number_editor = NumericEditor( - extendable = True, - new_columns = 'last', - configurable = True, - columns = [ NumericColumn( name = 'model_indices', - label = 'i' ), - NumericColumn( name = 'x', - label = 'x', - format = '%.2f' ), - NumericColumn( name = 'sinx', - label = 'sin(x)', - format = '%.3f' ), - NumericColumn( name = 'xsinx', - label = 'x*sin(x)', - format = '%.3f' ) ], - other_columns = [], - choose_selection_filter = True, - edit_selection_filter = True, - edit_selection_colors = False, - selection_filter = None, - selection_filter_name = '', - user_selection_filter = IndexFilter(), - choose_reduction_filter = True, - edit_reduction_filter = True, - reduction_filter = None, - reduction_filter_name = '', - deletable = True, - sortable = True, - sort_model = False, - editable = True, - auto_size = False, - show_lines = True, - menu = None, - show_column_labels = True, - #line_color = 0xC4C0A9, - #cell_font = Font, - #cell_color = Color( 'black' ) - #cell_bg_color = Color( 'white' ) - #cell_read_only_bg_color = Color( 0xF8F7F1 ) - #label_font = Font - #label_color = Color( 'black' ) - #label_bg_color = Color( 0xD7D2BF ) - #selection_bg_color = Color( 0x0D22DF ) - #selection_color = Color( 'white' ) - #column_label_height = Int( 25 ) - #row_label_width = Int( 82 ) - #on_select = Callable - #on_dclick = Callable -) - -#------------------------------------------------------------------------------- -# 'BunchANumbersApp' class: -#------------------------------------------------------------------------------- - -class BunchANumbersApp ( HasPrivateTraits ): - - #--------------------------------------------------------------------------- - # Trait definitions: - #--------------------------------------------------------------------------- - - model = Instance( ANumericModel ) - - #--------------------------------------------------------------------------- - # Traits view definitions: - #--------------------------------------------------------------------------- - - view = View( - HGroup( Item( 'model', editor = number_editor, - id = 'model' ), -# Item( 'model', editor = number_editor ), - show_labels = False ), - title = 'Numeric Editor Test', - id = 'traitsui.tests.numeric_editor_test', - width = 0.28, - height = 0.6, - resizable = True ) - -#------------------------------------------------------------------------------- -# Run the test: -#------------------------------------------------------------------------------- - -if __name__ == '__main__': - x = arange( 0.0, 20.005, 0.1 ) - model = NumericArrayModel( x = x, sinx = sin( x ), xsinx = x * sin( x ) ) - BunchANumbersApp( model = model ).configure_traits() - diff --git a/integrationtests/ui/test_set_dynamic.py b/integrationtests/ui/test_set_dynamic.py deleted file mode 100644 index 2bcad2d0e..000000000 --- a/integrationtests/ui/test_set_dynamic.py +++ /dev/null @@ -1,19 +0,0 @@ -# Copyright (c) 2007, Enthought, Inc. -# License: BSD Style. - -from traits.api import * -from traitsui.api import * - -class Team ( HasTraits ): - - batting_order = List( Str ) - roster = List( [ 'Tom', 'Dick', 'Harry', 'Sally' ], Str ) - - view = View( Item( 'batting_order', editor = SetEditor( name = 'roster', - ordered = True ) ), - '_', 'roster@', - height=500, - resizable=True) - -if __name__ == '__main__': - Team().configure_traits() diff --git a/integrationtests/ui/test_shell_editor.py b/integrationtests/ui/test_shell_editor.py deleted file mode 100644 index 4faaca91e..000000000 --- a/integrationtests/ui/test_shell_editor.py +++ /dev/null @@ -1,52 +0,0 @@ -#------------------------------------------------------------------------------- -# -# Traits UI Python ShellEditor test. -# -# Written by: David C. Morrill -# -# Date: 10/13/2005 -# -# (c) Copyright 2005 by Enthought, Inc. -# License: BSD Style. -# -#------------------------------------------------------------------------------- - -from traits.api import * -from traitsui.api import * -from traitsui.menu import * - -#------------------------------------------------------------------------------- -# 'ShellTest' class: -#------------------------------------------------------------------------------- - -class ShellTest ( HasPrivateTraits ): - - #--------------------------------------------------------------------------- - # Trait definitions: - #--------------------------------------------------------------------------- - - name = Str - age = Int - weight = Float - shell_1 = Str - shell_2 = Dict - - #--------------------------------------------------------------------------- - # Traits view definitions: - #--------------------------------------------------------------------------- - - view = View( 'name', 'age', 'weight', '_', - Item( 'shell_1', editor = ShellEditor() ), - Item( 'shell_2', editor = ShellEditor() ), - id = 'traitsui.tests.shell_editor_test', - resizable = True, - width = 0.3, - height = 0.3 ) - -#------------------------------------------------------------------------------- -# Run the test: -#------------------------------------------------------------------------------- - -if __name__ == '__main__': - ShellTest().configure_traits() - diff --git a/integrationtests/ui/test_table_editor.py b/integrationtests/ui/test_table_editor.py deleted file mode 100644 index 3b1fd456f..000000000 --- a/integrationtests/ui/test_table_editor.py +++ /dev/null @@ -1,233 +0,0 @@ -#------------------------------------------------------------------------------- -# -# TableEditor test case for Traits UI -# -# Written by: David C. Morrill -# -# Date: 07/05/2005 -# -# (c) Copyright 2005 by Enthought, Inc. -# Copyright (c) 2007, Enthought, Inc. -# License: BSD Style. -# -#------------------------------------------------------------------------------- - -#------------------------------------------------------------------------------- -# Imports: -#------------------------------------------------------------------------------- - -from traits.api \ - import HasStrictTraits, Str, Int, Regex, List, Instance - -from traitsui.api \ - import View, Group, Item, TableEditor, EnumEditor - -from traitsui.table_column \ - import ObjectColumn - -from traitsui.table_filter \ - import TableFilter, RuleTableFilter, RuleFilterTemplate, \ - MenuFilterTemplate, EvalFilterTemplate - -#------------------------------------------------------------------------------- -# 'Person' class: -#------------------------------------------------------------------------------- - - - - -class Person ( HasStrictTraits ): - - #--------------------------------------------------------------------------- - # Trait definitions: - #--------------------------------------------------------------------------- - - name = Str - age = Int - phone = Regex( value = '000-0000', regex = '\d\d\d[-]\d\d\d\d' ) - state = Str - - #--------------------------------------------------------------------------- - # Traits view definition: - #--------------------------------------------------------------------------- - - traits_view = View( 'name', 'age', 'phone', 'state', - title = 'Create new person', - width = 0.18, - buttons = [ 'OK', 'Cancel' ] ) - -#------------------------------------------------------------------------------- -# Sample data: -#------------------------------------------------------------------------------- - -people = [ - Person( name = 'Dave', age = 39, phone = '555-1212' ), - Person( name = 'Mike', age = 28, phone = '555-3526' ), - Person( name = 'Joe', age = 34, phone = '555-6943' ), - Person( name = 'Tom', age = 22, phone = '555-7586' ), - Person( name = 'Dick', age = 63, phone = '555-3895' ), - Person( name = 'Harry', age = 46, phone = '555-3285' ), - Person( name = 'Sally', age = 43, phone = '555-8797' ), - Person( name = 'Fields', age = 31, phone = '555-3547' ) -] - -#------------------------------------------------------------------------------- -# 'AgeFilter' class: -#------------------------------------------------------------------------------- - -class AgeFilter ( TableFilter ): - - #--------------------------------------------------------------------------- - # Trait definitions: - #--------------------------------------------------------------------------- - - name = "Age filter" - _name = "Age filter" - - age = Int( 0 ) - - #--------------------------------------------------------------------------- - # Traits view definitions: - #--------------------------------------------------------------------------- - - #filter_view = Group( 'age{Age >=}' ) - - #--------------------------------------------------------------------------- - # Returns whether an object passes the filter or not: - #--------------------------------------------------------------------------- - - def filter ( self, person ): - """ Returns whether an object passes the filter or not. - """ - return (person.age >= self.age) - - #--------------------------------------------------------------------------- - # Returns a user readable description of what the filter does: - #--------------------------------------------------------------------------- - - def description ( self ): - """ Returns a user readable description of what the filter does. - """ - return 'Age >= %d' % self.age - - def _age_changed(self, old, new): - self.name = self.description() - print 'AgeFilter _age_changed', self.name - -#------------------------------------------------------------------------------- -# 'NameFilter' class: -#------------------------------------------------------------------------------- - -class NameFilter ( TableFilter ): - - #--------------------------------------------------------------------------- - # Trait definitions: - #--------------------------------------------------------------------------- - - mname = Str - - #--------------------------------------------------------------------------- - # Traits view definitions: - #--------------------------------------------------------------------------- - - filter_view = Group( 'mname{Name contains}' ) - - #--------------------------------------------------------------------------- - # Returns whether an object passes the filter or not: - #--------------------------------------------------------------------------- - - def filter ( self, person ): - """ Returns whether an object passes the filter or not. - """ - return (person.name.lower().find( self.mname.lower() ) >= 0) - - #--------------------------------------------------------------------------- - # Returns a user readable description of what the filter does: - #--------------------------------------------------------------------------- - - def description ( self ): - """ Returns a user readable description of what the filter does. - """ - return "Name contains '%s'" % self.mname - -#------------------------------------------------------------------------------- -# Table editor definition: -#------------------------------------------------------------------------------- - -filters = [ AgeFilter( age = 30 ), NameFilter( mname = 'd' ), EvalFilterTemplate, MenuFilterTemplate, RuleFilterTemplate, - ] - -def evaluate_value(v): - print 'evaluate_value', v - return str(v) -#------------------------------------------------------------------------------- -# 'TableTest' class: -#------------------------------------------------------------------------------- - -class TableTest ( HasStrictTraits ): - - #--------------------------------------------------------------------------- - # Trait definitions: - #--------------------------------------------------------------------------- - - #people = Instance( Person ) - people = List( Person ) - - #--------------------------------------------------------------------------- - # Traits view definitions: - #--------------------------------------------------------------------------- - - _valid_states = List(["AL", "AR", "AZ", "AK"]) - - _state_editor = EnumEditor( - name = "_valid_states", - evaluate = evaluate_value, - object = 'table_editor_object' - ) - - - table_editor = TableEditor( - columns = [ ObjectColumn( name = 'name' ), - ObjectColumn( name = 'age' ), - ObjectColumn( name = 'phone' ), - ObjectColumn( name = 'state', - editor=_state_editor), ], - editable = True, - deletable = True, - sortable = True, - sort_model = True, - show_lines = True, - orientation = 'vertical', - show_column_labels = True, - edit_view = View( [ 'name', 'age', 'phone', 'state', '|[]' ], - resizable = True ), - filter = None, - filters = filters, - row_factory = Person - ) - - - traits_view = View( - [ Item( 'people', - id = 'people', - editor = table_editor ), - '|[]<>' ], - title = 'Table Editor Test', - id = 'traitsui.tests.table_editor_test', - dock = 'horizontal', - width = .4, - height = .3, - resizable = True, - kind = 'live' ) - - -#------------------------------------------------------------------------------- -# Run the tests: -#------------------------------------------------------------------------------- - -if __name__ == '__main__': - tt = TableTest( people = people ) - tt.configure_traits() - for p in tt.people: - p.print_traits() - print '--------------' diff --git a/integrationtests/ui/test_table_editor2.py b/integrationtests/ui/test_table_editor2.py deleted file mode 100644 index f0917c767..000000000 --- a/integrationtests/ui/test_table_editor2.py +++ /dev/null @@ -1,110 +0,0 @@ -#------------------------------------------------------------------------------- -# -# TableEditor test case for Traits UI -# -# Written by: David C. Morrill -# -# Date: 07/05/2005 -# -# (c) Copyright 2005 by Enthought, Inc. -# License: BSD Style. -# -#------------------------------------------------------------------------------- - -#------------------------------------------------------------------------------- -# Imports: -#------------------------------------------------------------------------------- - -from traits.api \ - import HasStrictTraits, Str, Int, Regex, List - -from traitsui.api \ - import View - -#------------------------------------------------------------------------------- -# 'Person' class: -#------------------------------------------------------------------------------- - -class Person ( HasStrictTraits ): - - #--------------------------------------------------------------------------- - # Trait definitions: - #--------------------------------------------------------------------------- - - name = Str - age = Int - phone = Regex( value = '000-0000', regex = '\d\d\d[-]\d\d\d\d' ) - - #--------------------------------------------------------------------------- - # Traits view definition: - #--------------------------------------------------------------------------- - - traits_view = View( 'name', 'age', 'phone', - title = 'Create new person', - width = 0.18, - buttons = [ 'OK', 'Cancel' ] ) - -#------------------------------------------------------------------------------- -# 'WorkingPerson' class -#------------------------------------------------------------------------------- - -class WorkingPerson ( Person ): - - #--------------------------------------------------------------------------- - # Trait definitions: - #--------------------------------------------------------------------------- - - job = Str - - #--------------------------------------------------------------------------- - # Traits view definition: - #--------------------------------------------------------------------------- - - traits_view = View( 'name', 'age', 'phone', 'job', - title = 'Create new working person.........', - width = 0.18, - buttons = [ 'OK', 'Cancel' ] ) - -#------------------------------------------------------------------------------- -# Sample data: -#------------------------------------------------------------------------------- - -people = [ - Person( name = 'Dave', age = 39, phone = '555-1212' ), - Person( name = 'Mike', age = 28, phone = '555-3526' ), - WorkingPerson( name = 'Joe', age = 34, phone = '555-6943', job = 'Fireman' ), - Person( name = 'Tom', age = 22, phone = '555-7586' ), - Person( name = 'Dick', age = 63, phone = '555-3895' ), - Person( name = 'Harry', age = 46, phone = '555-3285' ), - WorkingPerson( name = 'Sally', age = 43, phone = '555-8797', job = 'Soldier' ), - Person( name = 'Fields', age = 31, phone = '555-3547' ) -] - -#------------------------------------------------------------------------------- -# 'TableTest' class: -#------------------------------------------------------------------------------- - -class TableTest ( HasStrictTraits ): - - #--------------------------------------------------------------------------- - # Trait definitions: - #--------------------------------------------------------------------------- - - people = List( Person ) - - #--------------------------------------------------------------------------- - # Traits view definitions: - #--------------------------------------------------------------------------- - - traits_view = View( [ 'people#', '|<>' ], resizable = True ) - -#------------------------------------------------------------------------------- -# Run the tests: -#------------------------------------------------------------------------------- - -if __name__ == '__main__': - tt = TableTest( people = people ) - tt.configure_traits() - for p in tt.people: - p.print_traits() - print '--------------' diff --git a/integrationtests/ui/test_table_editor_color.py b/integrationtests/ui/test_table_editor_color.py deleted file mode 100644 index 1a918315c..000000000 --- a/integrationtests/ui/test_table_editor_color.py +++ /dev/null @@ -1,91 +0,0 @@ -#------------------------------------------------------------------------------- -# -# TableEditor test case for Traits UI -# -# Written by: David C. Morrill -# -# Date: 07/05/2005 -# -# (c) Copyright 2005 by Enthought, Inc. -# License: BSD Style. -# -#------------------------------------------------------------------------------- - -#------------------------------------------------------------------------------- -# Imports: -#------------------------------------------------------------------------------- - -from traits.api \ - import HasTraits, List - -from traitsui.api \ - import View, Item, TableEditor - -from traitsui.wx.color_column \ - import ColorColumn - -from enable.api \ - import ColorTrait - -class Thingy ( HasTraits ): - color = ColorTrait( 'black' ) - -#------------------------------------------------------------------------------- -# Sample data: -#------------------------------------------------------------------------------- - -colors = [ - Thingy( color = 'red'), - Thingy( color = 'orange'), - Thingy( color = 'yellow'), - Thingy( color = 'green'), - Thingy( color = 'blue'), - Thingy( color = 'indigo'), - Thingy( color = 'violet'), - Thingy( color = 'black'), - Thingy( color = 'white'), -] - -class TableTest ( HasTraits ): - - #--------------------------------------------------------------------------- - # Trait definitions: - #--------------------------------------------------------------------------- - - colors = List( Thingy ) - - table_editor = TableEditor( - columns = [ ColorColumn( name = 'color' ), - ], - - editable = True, - deletable = True, - sortable = True, # - sort_model = True, - show_lines = True, # - orientation = 'vertical', - show_column_labels = True, # - row_factory = Thingy - ) - - - traits_view = View( - [ Item( 'colors', - id = 'colors', - editor = table_editor ), - '|[]<>' ], - title = 'Table Editor Test', - id = 'traitsui.tests.table_editor_color_test', - dock = 'horizontal', - width = .4, - height = .3, - resizable = True, - kind = 'live' ) - -#------------------------------------------------------------------------------- -# Run the tests: -#------------------------------------------------------------------------------- - -if __name__ == '__main__': - tt = TableTest( colors = colors ) - tt.configure_traits() diff --git a/integrationtests/ui/test_table_list_editor.py b/integrationtests/ui/test_table_list_editor.py deleted file mode 100644 index e228ed7fd..000000000 --- a/integrationtests/ui/test_table_list_editor.py +++ /dev/null @@ -1,94 +0,0 @@ -#------------------------------------------------------------------------------- -# -# TableEditor test case for Traits UI which tests editing of lists instead of -# editing of objects. -# -# Written by: David C. Morrill -# -# Date: 07/06/2005 -# -# (c) Copyright 2005 by Enthought, Inc. -# Copyright (c) 2007, Enthought, Inc. -# License: BSD Style. -# -#------------------------------------------------------------------------------- - -#------------------------------------------------------------------------------- -# Imports: -#------------------------------------------------------------------------------- - -from traits.api \ - import HasStrictTraits, List - -from traitsui.api \ - import View, Item, TableEditor - -from traitsui.table_column \ - import ListColumn - -from traitsui.table_filter \ - import TableFilter - -#------------------------------------------------------------------------------- -# Sample data: -#------------------------------------------------------------------------------- - -people = [ - [ 'Dave', 39, '555-1212' ], - [ 'Mike', 28, '555-3526' ], - [ 'Joe', 34, '555-6943' ], - [ 'Tom', 22, '555-7586' ], - [ 'Dick', 63, '555-3895' ], - [ 'Harry', 46, '555-3285' ], - [ 'Sally', 43, '555-8797' ], - [ 'Fields', 31, '555-3547' ] -] - -#------------------------------------------------------------------------------- -# Table editor definition: -#------------------------------------------------------------------------------- - -table_editor = TableEditor( - columns = [ ListColumn( index = 0, label = 'Name' ), - ListColumn( index = 1, label = 'Age' ), - ListColumn( index = 2, label = 'Phone' ) ], - editable = False, - show_column_labels = True, # -) - -#------------------------------------------------------------------------------- -# 'TableTest' class: -#------------------------------------------------------------------------------- - -class TableTest ( HasStrictTraits ): - - #--------------------------------------------------------------------------- - # Trait definitions: - #--------------------------------------------------------------------------- - - people = List - - #--------------------------------------------------------------------------- - # Traits view definitions: - #--------------------------------------------------------------------------- - - traits_view = View( [ Item( 'people', - editor = table_editor, - resizable = True ), - '|[]<>' ], - title = 'Table Editor Test', - width = .17, - height = .23, - buttons = [ 'OK', 'Cancel' ], - kind = 'live' ) - -#------------------------------------------------------------------------------- -# Run the tests: -#------------------------------------------------------------------------------- - -if __name__ == '__main__': - tt = TableTest( people = people ) - tt.configure_traits() - for p in tt.people: - print p - print '--------------' diff --git a/integrationtests/ui/test_ui.py b/integrationtests/ui/test_ui.py deleted file mode 100644 index eda5b7606..000000000 --- a/integrationtests/ui/test_ui.py +++ /dev/null @@ -1,212 +0,0 @@ -#------------------------------------------------------------------------------ -# Copyright (c) 2005, Enthought, Inc. -# All rights reserved. -# -# This software is provided without warranty under the terms of the BSD -# license included in /LICENSE.txt and may be redistributed only -# under the conditions described in the aforementioned license. The license -# is also available online at http://www.enthought.com/licenses/BSD.txt -# Thanks for using Enthought open source! -# -# Author: David C. Morrill Date: 11/02/2004 Description: Test case for Traits -# User Interface -# ------------------------------------------------------------------------------ - -#------------------------------------------------------------------------------- -# Imports: -#------------------------------------------------------------------------------- - -import wx - -from traits.api \ - import Trait, HasTraits, Str, Int, Range, List, Event, File, Directory, \ - Bool, Color, Font, Enum - -from traitsui.api \ - import View, Handler, Item, CheckListEditor, ButtonEditor, FileEditor, \ - DirectoryEditor, ImageEnumEditor - -#------------------------------------------------------------------------------- -# Constants: -#------------------------------------------------------------------------------- - -origin_values = [ 'top left', 'top right', 'bottom left', 'bottom right' ] - -#------------------------------------------------------------------------------- -# 'Instance' class: -#------------------------------------------------------------------------------- - -class Instance ( HasTraits ): - - #--------------------------------------------------------------------------- - # Trait definitions: - #--------------------------------------------------------------------------- - - integer_text = Int( 1 ) - enumeration = Enum( 'one', 'two', 'three', 'four', 'five', 'six', - cols = 3 ) - float_range = Range( 0.0, 10.0, 10.0 ) - int_range = Range( 1, 5 ) - boolean = Bool( True ) - - view = View( 'integer_text', 'enumeration', 'float_range', - 'int_range', 'boolean' ) - -#------------------------------------------------------------------------------- -# 'TraitsTest' class -#------------------------------------------------------------------------------- - -class TraitsTest ( HasTraits ): - - #--------------------------------------------------------------------------- - # Trait definitions: - #--------------------------------------------------------------------------- - - integer_text = Int( 1 ) - enumeration = Enum( 'one', 'two', 'three', 'four', 'five', 'six', - cols = 3 ) - float_range = Range( 0.0, 10.0, 10.0 ) - int_range = Range( 1, 6 ) - int_range2 = Range( 1, 50 ) - compound = Trait( 1, Range( 1, 6 ), - 'one', 'two', 'three', 'four', 'five', 'six' ) - boolean = Bool( True ) - instance = Trait( Instance() ) - color = Color - font = Font - check_list = List( editor = CheckListEditor( - values = [ 'one', 'two', 'three', 'four' ], - cols = 4 ) ) - list = List( Str, [ 'East of Eden', 'The Grapes of Wrath', - 'Of Mice and Men' ] ) - button = Event( 0, editor = ButtonEditor( label = 'Click' ) ) - file = File - directory = Directory - image_enum = Trait( editor = ImageEnumEditor( values = origin_values, - suffix = '_origin', - cols = 4, - klass = Instance ), - *origin_values ) - - #--------------------------------------------------------------------------- - # View definitions: - #--------------------------------------------------------------------------- - - view = View( - ( '|{Enum}', - ( '|<[Enumeration]', 'enumeration[Simple]', '_', - 'enumeration[Custom]@', '_', - 'enumeration[Text]*', '_', - 'enumeration[Readonly]~' ), - ( '|<[Check List]', 'check_list[Simple]', '_', - 'check_list[Custom]@', '_', - 'check_list[Text]*', '_', - 'check_list[Readonly]~' ) - ), - ( '|{Range}', - ( '|<[Float Range]', 'float_range[Simple]', '_', - 'float_range[Custom]@', '_', - 'float_range[Text]*', '_', - 'float_range[Readonly]~' ), - ( '|<[Int Range]', 'int_range[Simple]', '_', - 'int_range[Custom]@', '_', - 'int_range[Text]*', '_', - 'int_range[Readonly]~' ), - ( '|<[Int Range 2]', 'int_range2[Simple]', '_', - 'int_range2[Custom]@', '_', - 'int_range2[Text]*', '_', - 'int_range2[Readonly]~' ) - ), - ( '|{Misc}', - ( '|<[Integer Text]', 'integer_text[Simple]', '_', - 'integer_text[Custom]@', '_', - 'integer_text[Text]*', '_', - 'integer_text[Readonly]~' ), - ( '|<[Compound]', 'compound[Simple]', '_', - 'compound[Custom]@', '_', - 'compound[Text]*', '_', - 'compound[Readonly]~' ), - ( '|<[Boolean]', 'boolean[Simple]', '_', - 'boolean[Custom]@', '_', - 'boolean[Text]*', '_', - 'boolean[Readonly]~' ) - ), - ( '|{Color/Font}', - ( '|<[Color]', 'color[Simple]', '_', - 'color[Custom]@', '_', - 'color[Text]*', '_', - 'color[Readonly]~' ), - ( '|<[Font]', 'font[Simple]', '_', - 'font[Custom]@', '_', - 'font[Text]*', '_', - 'font[Readonly]~' ) - ), - ( '|{List}', - ( '|<[List]', 'list[Simple]', '_', - 'list[Custom]@', '_', - 'list[Text]*', '_', - 'list[Readonly]~' ) - ), - ( '|{Button}', - ( '|<[Button]', 'button[Simple]', '_', - 'button[Custom]@' ), -# 'button[Text]*', -# 'button[Readonly]~' ), - ( '|<[Image Enum]', 'image_enum[Simple]', '_', - 'image_enum[Custom]@', '_', - 'image_enum[Text]*', '_', - 'image_enum[Readonly]~' ), - ( '|<[Instance]', 'instance[Simple]', '_', - 'instance[Custom]@', '_', - 'instance[Text]*', '_', - 'instance[Readonly]~' ), - ), - ( '|{File}', - - ( '|<[File]', 'file[Simple]', '_', - 'file[Custom]@', '_', - 'file[Text]*', '_', - 'file[Readonly]~', ), - ( '|<[Directory]', 'directory[Simple]', '_', - 'directory[Custom]@', '_', - 'directory[Text]*', '_', - 'directory[Readonly]~' ) - ), - buttons = [ 'Apply', 'Revert', 'Undo', 'OK' ] - ) - -#------------------------------------------------------------------------------- -# 'TraitSheetApp' class: -#------------------------------------------------------------------------------- - -class TraitSheetApp ( wx.App ): - - #--------------------------------------------------------------------------- - # Initialize the object: - #--------------------------------------------------------------------------- - - def __init__ ( self, object ): - self.object = object - wx.InitAllImageHandlers() - wx.App.__init__( self, 1, 'debug.log' ) - self.MainLoop() - - #--------------------------------------------------------------------------- - # Handle application initialization: - #--------------------------------------------------------------------------- - - def OnInit ( self ): - ui = self.object.edit_traits( kind = 'modal' ) - ui = self.object.edit_traits( kind = 'wizard' ) - ui = self.object.edit_traits( kind = 'nonmodal' ) - ui = self.object.edit_traits( kind = 'live' ) - self.SetTopWindow( ui.control ) - return True - -#------------------------------------------------------------------------------- -# Main program: -#------------------------------------------------------------------------------- - -if __name__ == '__main__': - TraitSheetApp( TraitsTest() ) - diff --git a/integrationtests/ui/test_ui2.py b/integrationtests/ui/test_ui2.py deleted file mode 100644 index ca2bdd778..000000000 --- a/integrationtests/ui/test_ui2.py +++ /dev/null @@ -1,192 +0,0 @@ -#------------------------------------------------------------------------------ -# Copyright (c) 2005, Enthought, Inc. -# All rights reserved. -# -# This software is provided without warranty under the terms of the BSD -# license included in /LICENSE.txt and may be redistributed only -# under the conditions described in the aforementioned license. The license -# is also available online at http://www.enthought.com/licenses/BSD.txt -# Thanks for using Enthought open source! -# -# Author: David C. Morrill Date: 11/02/2004 Description: Test case for Traits -# User Interface -# ------------------------------------------------------------------------------ - -#------------------------------------------------------------------------------- -# Imports: -#------------------------------------------------------------------------------- - -import wx - -from kiva.traits.kiva_font_trait \ - import KivaFont - -from enable.traits.api \ - import RGBAColor - -from traits.api \ - import Trait, HasTraits, Str, Int, Range, List, Event, Bool - -from traitsui.api \ - import View, Handler, Item, CheckListEditor, ButtonEditor, FileEditor, \ - DirectoryEditor, ImageEnumEditor - -#------------------------------------------------------------------------------- -# Constants: -#------------------------------------------------------------------------------- - -origin_values = [ 'top left', 'top right', 'bottom left', 'bottom right' ] - -#------------------------------------------------------------------------------- -# 'PersonHandler' class: -#------------------------------------------------------------------------------- - -class PersonHandler ( Handler ): - - def object_zip_changed ( self, info ): - obj = info.object - enabled = (obj.zip >= 10000) - info.street.enabled = enabled - info.city.enabled = enabled - info.state.enabled = enabled - if obj.zip == 78664: - obj.street = '901 Morning View Place' - obj.city = 'Round Rock' - obj.state = 'Texas' - - def object_call_changed ( self, info ): - print 'You called?' - -#------------------------------------------------------------------------------- -# 'WizardHandler' class: -#------------------------------------------------------------------------------- - -class WizardHandler ( Handler ): - - def object_sex_changed ( self, info ): - if info.object.sex == 'Female': - info.p1.next = 'p3' - else: - info.p1.next = 'p2' - info.p2.next = None - - def object_name_changed ( self, info ): - info.p2.enabled = info.p3.enabled = (info.object.name != '') - if not info.p2.enabled: - info.p2.msg = info.p3.msg = 'You must enter a valid name.' - -#------------------------------------------------------------------------------- -# 'Employer' class: -#------------------------------------------------------------------------------- - -class Employer ( HasTraits ): - - #--------------------------------------------------------------------------- - # Trait definitions: - #--------------------------------------------------------------------------- - - company = Str - boss = Str - - view = View( 'company', 'boss' ) - -#------------------------------------------------------------------------------- -# 'Person' class -#------------------------------------------------------------------------------- - -class Person ( HasTraits ): - - #--------------------------------------------------------------------------- - # Trait definitions: - #--------------------------------------------------------------------------- - - name = Str( 'David Morrill' ) - age = Int( 39 ) - sex = Trait( 'Male', 'Female' ) - coolness = Range( 0.0, 10.0, 10.0 ) - number = Trait( 1, Range( 1, 6 ), - 'one', 'two', 'three', 'four', 'five', 'six' ) - human = Bool( True ) - employer = Trait( Employer( company = 'Enthought, Inc.', boss = 'eric' ) ) - eye_color = RGBAColor - set = List( editor = CheckListEditor( - values = [ 'one', 'two', 'three', 'four' ], - cols = 4 ) ) - font = KivaFont - street = Str - city = Str - state = Str - zip = Int( 78663 ) - password = Str - books = List( Str, [ 'East of Eden', 'The Grapes of Wrath', - 'Of Mice and Men' ] ) - call = Event( 0, editor = ButtonEditor( label = 'Click to call' ) ) - info = Str( editor = FileEditor() ) - location = Str( editor = DirectoryEditor() ) - origin = Trait( editor = ImageEnumEditor( values = origin_values, - suffix = '_origin', - cols = 4, - klass = Employer ), - *origin_values ) - - nm = Item( 'name', enabled_when = 'object.age >= 21' ) - pw = Item( 'password', defined_when = 'object.zip == 78664' ) - view = View( ( ( nm, 'age', 'coolness', - '_', 'eye_color', 'eye_color@', 'eye_color*', 'eye_color~', - '_', 'font', 'font@', 'font*', 'font~', - '_', 'set', 'set@', 'set*', 'set~', - '_', 'sex', 'sex@', 'sex*', 'sex~', - '_', 'human', 'human@', 'human*', 'human~', - '_', 'number', 'number@', 'number*', 'number~', - '_', 'books', '_', 'books@', '_', 'books*', '_', 'books~', - '_', 'info', 'location', 'origin', 'origin@', 'call', - 'employer', 'employer[]@', 'employer*', 'employer~', - pw, - '|<[Person:]' ), - ( ' ', 'street', 'city', 'state', 'zip', '|<[Address:]' ), - ( nm, nm, nm, nm, nm, nm, nm, nm, nm, nm, nm, nm, nm, nm, - '|<[Names:]' ), - '|' ), - title = 'Traits 2 User Interface Test', - handler = PersonHandler(), - buttons = [ 'Apply', 'Revert', 'Undo', 'OK' ], - height = 0.5 ) - - wizard = View( ( '|p1:', 'name', 'age', 'sex' ), - ( '|p2:', 'street', 'city', 'state', 'zip' ), - ( '|p3:', 'eye_color', 'origin', 'human' ), - handler = WizardHandler() ) - -#------------------------------------------------------------------------------- -# 'TraitSheetApp' class: -#------------------------------------------------------------------------------- - -class TraitSheetApp ( wx.App ): - - #--------------------------------------------------------------------------- - # Initialize the object: - #--------------------------------------------------------------------------- - - def __init__ ( self, object ): - self.object = object - wx.InitAllImageHandlers() - wx.App.__init__( self, 1, 'debug.log' ) - self.MainLoop() - object.print_traits() - - #--------------------------------------------------------------------------- - # Handle application initialization: - #--------------------------------------------------------------------------- - - def OnInit ( self ): - #ui = self.object.edit_traits( 'view', kind = 'live' ) - ui = self.object.edit_traits( 'wizard', kind = 'wizard' ) - self.SetTopWindow( ui.control ) - return True - -#------------------------------------------------------------------------------- -# Main program: -#------------------------------------------------------------------------------- - -TraitSheetApp( Person() ) - diff --git a/integrationtests/ui/test_ui3.py b/integrationtests/ui/test_ui3.py deleted file mode 100644 index 288c7f3fd..000000000 --- a/integrationtests/ui/test_ui3.py +++ /dev/null @@ -1,92 +0,0 @@ -#------------------------------------------------------------------------------ -# Copyright (c) 2005, Enthought, Inc. -# All rights reserved. -# -# This software is provided without warranty under the terms of the BSD -# license included in /LICENSE.txt and may be redistributed only -# under the conditions described in the aforementioned license. The license -# is also available online at http://www.enthought.com/licenses/BSD.txt -# Thanks for using Enthought open source! -# -# Author: David C. Morrill -# Date: 11/02/2004 -# Description: Test case for Traits User Interface -#------------------------------------------------------------------------------ - -#------------------------------------------------------------------------------- -# Imports: -#------------------------------------------------------------------------------- - -import wx - -from traits.api import Trait, HasTraits, Str, Int -from traitsui.api import View, Group -from traits.api import Color - -#------------------------------------------------------------------------------- -# Model/View classes: -#------------------------------------------------------------------------------- - -class Employer ( HasTraits ): - company = Str - boss = Str - - view = View( 'company', 'boss' ) - -class Person ( HasTraits ): - name = Str( 'David Morrill' ) - age = Int( 39 ) - - view = View( 'name', '', 'age', kind = 'modal' ) - -class ExtraPerson ( Person ): - sex = Trait( 'Male', 'Female' ) - eye_color = Color - - extra = Group( 'sex', 'eye_color' ) - -class LocatedPerson ( Person ): - street = Str - city = Str - state = Str - zip = Int( 78663 ) - - extra = Group( 'street', 'city', 'state', 'zip' ) - -class EmployedPerson ( LocatedPerson ): - employer = Trait( Employer( company = 'Enthought, Inc.', boss = 'eric' ) ) - - extra = Group( 'employer', '' ) - -#------------------------------------------------------------------------------- -# 'TraitSheetApp' class: -#------------------------------------------------------------------------------- - -class TraitSheetApp ( wx.App ): - - #--------------------------------------------------------------------------- - # Initialize the object: - #--------------------------------------------------------------------------- - - def __init__ ( self ): - wx.InitAllImageHandlers() - wx.App.__init__( self, 1, 'debug.log' ) - self.MainLoop() - - #--------------------------------------------------------------------------- - # Handle application initialization: - #--------------------------------------------------------------------------- - - def OnInit ( self ): - Person().edit_traits() - ExtraPerson().edit_traits() - LocatedPerson().edit_traits() - EmployedPerson().edit_traits() - return True - -#------------------------------------------------------------------------------- -# Main program: -#------------------------------------------------------------------------------- - -TraitSheetApp() - diff --git a/integrationtests/ui/test_ui4.py b/integrationtests/ui/test_ui4.py deleted file mode 100644 index af4dd1775..000000000 --- a/integrationtests/ui/test_ui4.py +++ /dev/null @@ -1,100 +0,0 @@ -#------------------------------------------------------------------------------ -# Copyright (c) 2005, Enthought, Inc. -# All rights reserved. -# -# This software is provided without warranty under the terms of the BSD -# license included in /LICENSE.txt and may be redistributed only -# under the conditions described in the aforementioned license. The license -# is also available online at http://www.enthought.com/licenses/BSD.txt -# Thanks for using Enthought open source! -# -# Author: David C. Morrill -# Date: 11/02/2004 -# Description: Test case for Traits User Interface -#------------------------------------------------------------------------------ - -#------------------------------------------------------------------------------- -# Imports: -#------------------------------------------------------------------------------- - -import wx - -from traits.api import Trait, HasTraits, Str, Int -from traitsui.api import View, Group -from traits.api import Color - -#------------------------------------------------------------------------------- -# Model classes: -#------------------------------------------------------------------------------- - -class Employer ( HasTraits ): - company = Str( 'Enthought, Inc.' ) - boss = Str( 'eric' ) - - view = View( 'company', 'boss' ) - -class Person ( HasTraits ): - name = Str( 'David Morrill' ) - age = Int( 39 ) - -class ExtraPerson ( Person ): - sex = Trait( 'Male', 'Female' ) - eye_color = Color - -class LocatedPerson ( Person ): - street = Str - city = Str - state = Str - zip = Int( 78663 ) - -class EmployedPerson ( LocatedPerson ): - employer = Trait( Employer() ) - -#------------------------------------------------------------------------------- -# View classes: -#------------------------------------------------------------------------------- - -class PersonView ( HasTraits ): - view = View( 'name', '', 'age', kind = 'modal' ) - -class ExtraPersonView ( PersonView ): - extra = Group( 'sex', 'eye_color' ) - -class LocatedPersonView ( PersonView ): - extra = Group( 'street', 'city', 'state', 'zip' ) - -class EmployedPersonView ( LocatedPersonView ): - extra = Group( 'employer', '' ) - -#------------------------------------------------------------------------------- -# 'TraitSheetApp' class: -#------------------------------------------------------------------------------- - -class TraitSheetApp ( wx.App ): - - #--------------------------------------------------------------------------- - # Initialize the object: - #--------------------------------------------------------------------------- - - def __init__ ( self ): - wx.InitAllImageHandlers() - wx.App.__init__( self, 1, 'debug.log' ) - self.MainLoop() - - #--------------------------------------------------------------------------- - # Handle application initialization: - #--------------------------------------------------------------------------- - - def OnInit ( self ): - PersonView().edit_traits( context = Person() ) - ExtraPersonView().edit_traits( context = ExtraPerson() ) - LocatedPersonView().edit_traits( context = LocatedPerson() ) - EmployedPersonView().edit_traits( context = EmployedPerson() ) - return True - -#------------------------------------------------------------------------------- -# Main program: -#------------------------------------------------------------------------------- - -TraitSheetApp() - diff --git a/integrationtests/ui/test_ui5.py b/integrationtests/ui/test_ui5.py deleted file mode 100644 index 339663e92..000000000 --- a/integrationtests/ui/test_ui5.py +++ /dev/null @@ -1,233 +0,0 @@ -#------------------------------------------------------------------------------ -# -# Copyright (c) 2005, Enthought, Inc. -# All rights reserved. -# -# This software is provided without warranty under the terms of the BSD -# license included in /LICENSE.txt and may be redistributed only -# under the conditions described in the aforementioned license. The license -# is also available online at http://www.enthought.com/licenses/BSD.txt -# -# Thanks for using Enthought open source! -# -# Author: David C. Morrill -# Date: 11/02/2004 -# -# ------------------------------------------------------------------------------ - -""" Traits Test case -""" - -#------------------------------------------------------------------------------- -# Imports: -#------------------------------------------------------------------------------- - -import wx - -from traits.api \ - import Trait, HasTraits, Str, Int, Range, List, Event, File, Directory, Bool - -from traitsui.api \ - import View, Handler, Item, CheckListEditor, ButtonEditor, FileEditor, \ - DirectoryEditor, ImageEnumEditor - -from traits.api \ - import Color, Font - -#------------------------------------------------------------------------------- -# Constants: -#------------------------------------------------------------------------------- - -origin_values = [ 'top left', 'top right', 'bottom left', 'bottom right' ] - -#------------------------------------------------------------------------------- -# 'Instance' class: -#------------------------------------------------------------------------------- - -class Instance ( HasTraits ): - - #--------------------------------------------------------------------------- - # Trait definitions: - #--------------------------------------------------------------------------- - - integer_text = Int( 1 ) - enumeration = Trait( 'one', 'two', 'three', 'four', 'five', 'six', - cols = 3 ) - float_range = Range( 0.0, 10.0, 10.0 ) - int_range = Range( 1, 5 ) - boolean = Bool( True ) - - view = View( 'integer_text', 'enumeration', 'float_range', - 'int_range', 'boolean' ) - -#------------------------------------------------------------------------------- -# 'TraitsTestHandler' class: -#------------------------------------------------------------------------------- - -class TraitsTestHandler ( Handler ): - - def object_enabled_changed ( self, info ): - enabled = info.object.enabled - for i in range( 1, 63 ): - getattr( info, 'f%d' % i ).enabled = enabled - -#------------------------------------------------------------------------------- -# 'TraitsTest' class -#------------------------------------------------------------------------------- - -class TraitsTest ( HasTraits ): - - #--------------------------------------------------------------------------- - # Trait definitions: - #--------------------------------------------------------------------------- - - enabled = Bool( True ) - integer_text = Int( 1 ) - enumeration = Trait( 'one', 'two', 'three', 'four', 'five', 'six', - cols = 3 ) - float_range = Range( 0.0, 10.0, 10.0 ) - int_range = Range( 1, 6 ) - int_range2 = Range( 1, 50 ) - compound = Trait( 1, Range( 1, 6 ), - 'one', 'two', 'three', 'four', 'five', 'six' ) - boolean = Bool( True ) - instance = Trait( Instance() ) - color = Color( 'cyan' ) - font = Font() - check_list = List( editor = CheckListEditor( - values = [ 'one', 'two', 'three', 'four' ], - cols = 4 ) ) - list = List( Str, [ 'East of Eden', 'The Grapes of Wrath', - 'Of Mice and Men' ] ) - button = Event( 0, editor = ButtonEditor( label = 'Click' ) ) - file = File() - directory = Directory() - image_enum = Trait( editor = ImageEnumEditor( values = origin_values, - suffix = '_origin', - cols = 4, - klass = Instance ), - *origin_values ) - - #--------------------------------------------------------------------------- - # View definitions: - #--------------------------------------------------------------------------- - - view = View( - ( '|{Enum}', - ( 'enabled', ), - ( '|<[Enumeration]', 'f1:enumeration[Simple]', '_', - 'f2:enumeration[Custom]@', '_', - 'f3:enumeration[Text]*', '_', - 'f4:enumeration[Readonly]~' ), - ( '|<[Check List]', 'f5:check_list[Simple]', '_', - 'f6:check_list[Custom]@', '_', - 'f7:check_list[Text]*', '_', - 'f8:check_list[Readonly]~' ) - ), - ( '|{Range}', - ( '|<[Float Range]', 'f9:float_range[Simple]', '_', - 'f10:float_range[Custom]@', '_', - 'f11:float_range[Text]*', '_', - 'f12:float_range[Readonly]~' ), - ( '|<[Int Range]', 'f13:int_range[Simple]', '_', - 'f14:int_range[Custom]@', '_', - 'f15:int_range[Text]*', '_', - 'f16:int_range[Readonly]~' ), - ( '|<[Int Range 2]', 'f17:int_range2[Simple]', '_', - 'f18:int_range2[Custom]@', '_', - 'f19:int_range2[Text]*', '_', - 'f20:int_range2[Readonly]~' ) - ), - ( '|{Misc}', - ( '|<[Integer Text]', 'f21:integer_text[Simple]', '_', - 'f22:integer_text[Custom]@', '_', - 'f23:integer_text[Text]*', '_', - 'f24:integer_text[Readonly]~' ), - ( '|<[Compound]', 'f25:compound[Simple]', '_', - 'f26:compound[Custom]@', '_', - 'f27:compound[Text]*', '_', - 'f28:compound[Readonly]~' ), - ( '|<[Boolean]', 'f29:boolean[Simple]', '_', - 'f30:boolean[Custom]@', '_', - 'f31:boolean[Text]*', '_', - 'f32:boolean[Readonly]~' ) - ), - ( '|{Color/Font}', - ( '|<[Color]', 'f33:color[Simple]', '_', - 'f34:color[Custom]@', '_', - 'f35:color[Text]*', '_', - 'f36:color[Readonly]~' ), - ( '|<[Font]', 'f37:font[Simple]', '_', - 'f38:font[Custom]@', '_', - 'f39:font[Text]*', '_', - 'f40:font[Readonly]~' ) - ), - ( '|{List}', - ( '|<[List]', 'f41:list[Simple]', '_', - 'f42:list[Custom]@', '_', - 'f43:list[Text]*', '_', - 'f44:list[Readonly]~' ) - ), - ( '|{Button}', - ( '|<[Button]', 'f45:button[Simple]', '_', - 'f46:button[Custom]@' ), -# 'button[Text]*', -# 'button[Readonly]~' ), - ( '|<[Image Enum]', 'f47:image_enum[Simple]', '_', - 'f48:image_enum[Custom]@', '_', - 'f49:image_enum[Text]*', '_', - 'f50:image_enum[Readonly]~' ), - ( '|<[Instance]', 'f51:instance[Simple]', '_', - 'f52:instance[Custom]@', '_', - 'f53:instance[Text]*', '_', - 'f54:instance[Readonly]~' ), - ), - ( '|{File}', - - ( '|<[File]', 'f55:file[Simple]', '_', - 'f56:file[Custom]@', '_', - 'f57:file[Text]*', '_', - 'f58:file[Readonly]~', ), - ( '|<[Directory]', 'f59:directory[Simple]', '_', - 'f60:directory[Custom]@', '_', - 'f61:directory[Text]*', '_', - 'f62:directory[Readonly]~' ) - ), - buttons = [ 'Apply', 'Revert', 'Undo', 'OK' ], - handler = TraitsTestHandler() - ) - -#------------------------------------------------------------------------------- -# 'TraitSheetApp' class: -#------------------------------------------------------------------------------- - -class TraitSheetApp ( wx.App ): - - #--------------------------------------------------------------------------- - # Initialize the object: - #--------------------------------------------------------------------------- - - def __init__ ( self, object ): - self.object = object - wx.InitAllImageHandlers() - wx.App.__init__( self, 1, 'debug.log' ) - self.MainLoop() - - #--------------------------------------------------------------------------- - # Handle application initialization: - #--------------------------------------------------------------------------- - - def OnInit ( self ): - ui = self.object.edit_traits( kind = 'live' ) - ui = self.object.edit_traits( kind = 'modal' ) - ui = self.object.edit_traits( kind = 'nonmodal' ) - ui = self.object.edit_traits( kind = 'wizard' ) - self.SetTopWindow( ui.control ) - return True - -#------------------------------------------------------------------------------- -# Main program: -#------------------------------------------------------------------------------- - -TraitSheetApp( TraitsTest() ) - diff --git a/integrationtests/ui/tree_editor_test.py b/integrationtests/ui/tree_editor_test.py deleted file mode 100644 index 503ae9377..000000000 --- a/integrationtests/ui/tree_editor_test.py +++ /dev/null @@ -1,210 +0,0 @@ -#------------------------------------------------------------------------------ -# Copyright (c) 2005, Enthought, Inc. -# All rights reserved. -# -# This software is provided without warranty under the terms of the BSD -# license included in /LICENSE.txt and may be redistributed only -# under the conditions described in the aforementioned license. The license -# is also available online at http://www.enthought.com/licenses/BSD.txt -# Thanks for using Enthought open source! -# -# Author: David C. Morrill -# Date: 12/04/2004 -# Description: Test case for the traits tree editor. -#------------------------------------------------------------------------------ - -#------------------------------------------------------------------------------- -# Imports: -#------------------------------------------------------------------------------- - -from traits.api import HasTraits, Str, Regex, List, Instance -from traitsui.api import TreeEditor, TreeNode, View, Item, VSplit, \ - HGroup, Handler -from traitsui.menu import Menu, Action, Separator -from traitsui.wx.tree_editor import NewAction, CopyAction, \ - CutAction, PasteAction, DeleteAction, RenameAction - -#------------------------------------------------------------------------------- -# 'Employee' class: -#------------------------------------------------------------------------------- - -class Employee ( HasTraits ): - name = Str( '' ) - title = Str - phone = Regex( regex = r'\d\d\d-\d\d\d\d' ) - - def default_title ( self ): - self.title = 'Senior Engineer' - -#------------------------------------------------------------------------------- -# 'Department' class: -#------------------------------------------------------------------------------- - -class Department ( HasTraits ): - name = Str( '' ) - employees = List( Employee ) - -#------------------------------------------------------------------------------- -# 'Company' class: -#------------------------------------------------------------------------------- - -class Company ( HasTraits ): - name = Str( '' ) - departments = List( Department ) - employees = List( Employee ) - -#------------------------------------------------------------------------------- -# 'Partner' class: -#------------------------------------------------------------------------------- - -class Partner ( HasTraits ): - name = Str( '' ) - company = Instance( Company ) - -#------------------------------------------------------------------------------- -# Create a hierarchy: -#------------------------------------------------------------------------------- - -jason = Employee( - name = 'Jason', - title = 'Sr. Engineer', - phone = '536-1057' ) - -mike = Employee( - name = 'Mike', - title = 'Sr. Engineer', - phone = '536-1057' ) - -dave = Employee( - name = 'Dave', - title = 'Sr. Engineer', - phone = '536-1057' ) - -martin = Employee( - name = 'Martin', - title = 'Sr. Engineer', - phone = '536-1057' ) - -duncan = Employee( - name = 'Duncan', - title = 'Sr. Engineer' ) - -partner = Partner( - name = 'eric', - company = Company( - name = 'Enthought, Inc.', - departments = [ - Department( - name = 'Business', - employees = [ jason, mike ] - ), - Department( - name = 'Scientific', - employees = [ dave, martin, duncan ] - ) - ], - employees = [ dave, martin, mike, duncan, jason ] - ) -) - -#------------------------------------------------------------------------------- -# Define the tree trait editor: -#------------------------------------------------------------------------------- - -no_view = View() - -tree_editor = TreeEditor( - nodes = [ - TreeNode( node_for = [ Company ], - auto_open = True, - children = '', - label = 'name', - view = View( [ 'name', '|<' ] ) ), - TreeNode( node_for = [ Company ], - auto_open = True, - children = 'departments', - label = '=Departments', - view = no_view, - add = [ Department ] ), - TreeNode( node_for = [ Company ], - auto_open = True, - children = 'employees', - label = '=Employees', - view = no_view, - add = [ Employee ] ), - TreeNode( node_for = [ Department ], - auto_open = True, - children = 'employees', - label = 'name', - menu = Menu( NewAction, - Separator(), - DeleteAction, - Separator(), - RenameAction, - Separator(), - CopyAction, - CutAction, - PasteAction ), - view = View( [ 'name', '|<' ] ), - add = [ Employee ] ), - TreeNode( node_for = [ Employee ], - auto_open = True, - label = 'name', - menu = Menu( NewAction, - Separator(), - Action( name = 'Default title', - action = 'object.default_title' ), - Action( name = 'Department', - action = 'handler.employee_department(editor,object)' ), - Separator(), - CopyAction, - CutAction, - PasteAction, - Separator(), - DeleteAction, - Separator(), - RenameAction ), - view = View( VSplit( HGroup( '3', 'name' ), - HGroup( '9', 'title' ), - HGroup( 'phone' ), - id = 'vsplit' ), - id = 'traitsui.test.tree_editor_test.employee', - dock = 'vertical' ) ) - ] -) - -#------------------------------------------------------------------------------- -# 'TreeHandler' class: -#------------------------------------------------------------------------------- - -class TreeHandler ( Handler ): - - def employee_department ( self, editor, object ): - dept = editor.get_parent( object ) - print '%s works in the %s department.' % ( object.name, dept.name ) - -#------------------------------------------------------------------------------- -# Define the View to use: -#------------------------------------------------------------------------------- - -view = View( [ Item( name = 'company', - id = 'company', - editor = tree_editor, - resizable = True ), '|<>' ], - title = 'Company Structure', - id = 'traitsui.tests.tree_editor_test', - dock = 'horizontal', - drop_class = HasTraits, - handler = TreeHandler(), - buttons = [ 'Undo', 'OK', 'Cancel' ], - resizable = True, - width = .3, - height = .3 ) - -#------------------------------------------------------------------------------- -# Edit it: -#------------------------------------------------------------------------------- - -if __name__ == '__main__': - partner.configure_traits( view = view ) - diff --git a/traits/tests/check_timing.py b/traits/tests/check_timing.py index 771a5467f..7a96640b1 100644 --- a/traits/tests/check_timing.py +++ b/traits/tests/check_timing.py @@ -1,4 +1,3 @@ -#------------------------------------------------------------------------------ # Copyright (c) 2005, Enthought, Inc. # All rights reserved. # @@ -12,225 +11,188 @@ # Date: 03/03/2003 # Description: Perform timing tests on various trait styles to determine the # amount of overhead that traits add. -#------------------------------------------------------------------------------ - -#------------------------------------------------------------------------------- -# Imports: -#------------------------------------------------------------------------------- from __future__ import absolute_import from time import time from ..api import Any, DelegatesTo, HasTraits, Int, Range -#------------------------------------------------------------------------------- -# Constants: -#------------------------------------------------------------------------------- - # Number of iterations to perform: n = 1000000 -# Loop overhead time (actual value determined first time a measurement is made): +# Loop overhead time (actual value determined first time a measurement is made) t0 = -1.0 -#------------------------------------------------------------------------------- -# Measure how long it takes to execute a specified function: -#------------------------------------------------------------------------------- -def measure ( func ): +# Measure how long it takes to execute a specified function: +def measure(func): now = time() func() return time() - now -#------------------------------------------------------------------------------- -# 'Old style' Python attribute get/set: -#------------------------------------------------------------------------------- +# 'Old style' Python attribute get/set: class old_style_value: - def measure ( self, reference_get=1.0, reference_set=1.0 ): + def measure(self, reference_get=1.0, reference_set=1.0): global t0 self.init() if t0 < 0.0: - t0 = measure( self.null ) - t1 = measure( self.do_get ) - t2 = measure( self.do_set ) + t0 = measure(self.null) + t1 = measure(self.do_get) + t2 = measure(self.do_set) scale = 1.0e6 / n - get_time = max( t1 - t0, 0.0 ) * scale - set_time = max( t2 - t0, 0.0 ) * scale + get_time = max(t1 - t0, 0.0) * scale + set_time = max(t2 - t0, 0.0) * scale return get_time, set_time - def null ( self ): + def null(self): for i in range(n): pass - def init ( self ): + def init(self): self.value = -1 - def do_set ( self ): + def do_set(self): for i in range(n): self.value = i - def do_get ( self ): + def do_get(self): for i in range(n): self.value -#------------------------------------------------------------------------------- -# 'New style' Python attribute get/set: -#------------------------------------------------------------------------------- -class new_style_value ( object ): +# 'New style' Python attribute get/set: +class new_style_value(object): - def measure ( self ): + def measure(self): global t0 self.init() if t0 < 0.0: - t0 = measure( self.null ) - t1 = measure( self.do_get ) - t2 = measure( self.do_set ) + t0 = measure(self.null) + t1 = measure(self.do_get) + t2 = measure(self.do_set) scale = 1.0e6 / n - get_time = max( t1 - t0, 0.0 ) * scale - set_time = max( t2 - t0, 0.0 ) * scale + get_time = max(t1 - t0, 0.0) * scale + set_time = max(t2 - t0, 0.0) * scale return get_time, set_time - def null ( self ): + def null(self): for i in range(n): pass - def init ( self ): + def init(self): self.value = -1 - def do_set ( self ): + def do_set(self): for i in range(n): self.value = i - def do_get ( self ): + def do_get(self): for i in range(n): self.value -#------------------------------------------------------------------------------- -# Python 'property' get/set: -#------------------------------------------------------------------------------- -class property_value ( new_style_value ): +# Python 'property' get/set: +class property_value(new_style_value): - def get_value ( self ): + def get_value(self): return self._value - def set_value ( self, value ): + def set_value(self, value): self._value = value - value = property( get_value, set_value ) + value = property(get_value, set_value) -#------------------------------------------------------------------------------- -# Python 'global' get/set: -#------------------------------------------------------------------------------- -class global_value ( new_style_value ): +# Python 'global' get/set: +class global_value(new_style_value): - def init ( self ): + def init(self): global gvalue gvalue = -1 - def do_set ( self ): + def do_set(self): global gvalue for i in range(n): gvalue = i - def do_get ( self ): + def do_get(self): global gvalue for i in range(n): gvalue -#------------------------------------------------------------------------------- -# Trait that can have any value: -#------------------------------------------------------------------------------- -class any_value ( HasTraits, new_style_value ): +# Trait that can have any value: +class any_value(HasTraits, new_style_value): value = Any -#------------------------------------------------------------------------------- -# Trait that can only have 'float' values: -#------------------------------------------------------------------------------- -class int_value ( any_value ): +# Trait that can only have 'float' values: +class int_value(any_value): value = Int -#------------------------------------------------------------------------------- + # Trait that can only have 'range' values: -#------------------------------------------------------------------------------- +class range_value(any_value): -class range_value ( any_value ): + value = Range(-1, 2000000000) - value = Range( -1, 2000000000 ) -#------------------------------------------------------------------------------- # Executes method when float trait is changed: -#------------------------------------------------------------------------------- +class change_value(int_value): -class change_value ( int_value ): - - def _value_changed ( self, old, new ): + def _value_changed(self, old, new): pass -#------------------------------------------------------------------------------- -# Notifies handler when float trait is changed: -#------------------------------------------------------------------------------- -class monitor_value ( int_value ): +# Notifies handler when float trait is changed: +class monitor_value(int_value): - def init ( self ): - self.on_trait_change( self.on_value_change, 'value' ) + def init(self): + self.on_trait_change(self.on_value_change, 'value') - def on_value_change ( self, object, trait_name, old, new ): + def on_value_change(self, object, trait_name, old, new): pass -#------------------------------------------------------------------------------- -# Float trait is delegated to another object: -#------------------------------------------------------------------------------- -class delegate_value ( HasTraits, new_style_value ): +# Float trait is delegated to another object: +class delegate_value(HasTraits, new_style_value): - value = DelegatesTo( 'delegate' ) + value = DelegatesTo('delegate') delegate = Any - def init ( self ): + def init(self): self.delegate = int_value() -#------------------------------------------------------------------------------- -# Float trait is delegated through one object to another object: -#------------------------------------------------------------------------------- -class delegate_2_value ( delegate_value ): +# Float trait is delegated through one object to another object: +class delegate_2_value(delegate_value): - def init ( self ): + def init(self): delegate = delegate_value() delegate.init() self.delegate = delegate -#------------------------------------------------------------------------------- -# Float trait is delegated through two objects to another object: -#------------------------------------------------------------------------------- -class delegate_3_value ( delegate_value ): +# Float trait is delegated through two objects to another object: +class delegate_3_value(delegate_value): - def init ( self ): + def init(self): delegate = delegate_2_value() delegate.init() self.delegate = delegate -#------------------------------------------------------------------------------- -# Run the timing measurements: -#------------------------------------------------------------------------------- +# Run the timing measurements: def report(name, get_time, set_time, ref_get_time, ref_set_time): """ Return string containing a benchmark report. @@ -243,15 +205,15 @@ def report(name, get_time, set_time, ref_get_time, ref_set_time): template = ( '{name:^30}: Get {get_time:02.3f} us (x {get_speed_up:02.3f}), ' 'Set {set_time:02.3f} us (x {set_speed_up:02.3f})' - ) + ) report = template.format( - name = name, - get_time = get_time, - get_speed_up = ref_get_time / get_time, - set_time = set_time, - set_speed_up = ref_set_time / set_time, - ) + name=name, + get_time=get_time, + get_speed_up=ref_get_time / get_time, + set_time=set_time, + set_speed_up=ref_set_time / set_time, + ) return report @@ -265,7 +227,6 @@ def run_benchmark(klass, ref_get_time, ref_set_time): def main(): - ref_get_time, ref_set_time = new_style_value().measure() benchmarks = [ diff --git a/traits/tests/test_abc.py b/traits/tests/test_abc.py index b7d335f8a..169de8bc8 100644 --- a/traits/tests/test_abc.py +++ b/traits/tests/test_abc.py @@ -1,10 +1,11 @@ """ Test the ABC functionality. """ +import abc +import warnings from traits.testing.unittest_tools import unittest -import warnings -from ..api import HasTraits +from ..api import ABCHasTraits, ABCMetaHasTraits, HasTraits, Int, Float class TestNew(unittest.TestCase): @@ -22,79 +23,74 @@ def test_new(self): # Should not raise DeprecationWarning. HasTraits(x=10) -try: - import abc - from ..api import ABCHasTraits, ABCMetaHasTraits, HasTraits, Int, Float +class AbstractFoo(ABCHasTraits): + x = Int(10) + y = Float(20.0) - class AbstractFoo(ABCHasTraits): - x = Int(10) - y = Float(20.0) + @abc.abstractmethod + def foo(self): + raise NotImplementedError() - @abc.abstractmethod - def foo(self): - raise NotImplementedError() + @abc.abstractproperty + def bar(self): + raise NotImplementedError() - @abc.abstractproperty - def bar(self): - raise NotImplementedError() - class ConcreteFoo(AbstractFoo): - def foo(self): - return 'foo' +class ConcreteFoo(AbstractFoo): + def foo(self): + return 'foo' - @property - def bar(self): - return 'bar' + @property + def bar(self): + return 'bar' - class FooLike(HasTraits): - x = Int(10) - y = Float(20.0) - def foo(self): - return 'foo' +class FooLike(HasTraits): + x = Int(10) + y = Float(20.0) - @property - def bar(self): - return 'bar' + def foo(self): + return 'foo' - AbstractFoo.register(FooLike) + @property + def bar(self): + return 'bar' - class AbstractBar(object): - __metaclass__ = abc.ABCMeta +AbstractFoo.register(FooLike) - @abc.abstractmethod - def bar(self): - raise NotImplementedError() +class AbstractBar(object): + __metaclass__ = abc.ABCMeta - class TestABC(unittest.TestCase): - def test_basic_abc(self): - self.assertRaises(TypeError, AbstractFoo) - concrete = ConcreteFoo() - self.assertEquals(concrete.foo(), 'foo') - self.assertEquals(concrete.bar, 'bar') - self.assertEquals(concrete.x, 10) - self.assertEquals(concrete.y, 20.0) - self.assertTrue(isinstance(concrete, AbstractFoo)) + @abc.abstractmethod + def bar(self): + raise NotImplementedError() - def test_registered(self): - foolike = FooLike() - self.assertTrue(isinstance(foolike, AbstractFoo)) - def test_post_hoc_mixing(self): - class TraitedBar(HasTraits, AbstractBar): - __metaclass__ = ABCMetaHasTraits - x = Int(10) +class TestABC(unittest.TestCase): + def test_basic_abc(self): + self.assertRaises(TypeError, AbstractFoo) + concrete = ConcreteFoo() + self.assertEquals(concrete.foo(), 'foo') + self.assertEquals(concrete.bar, 'bar') + self.assertEquals(concrete.x, 10) + self.assertEquals(concrete.y, 20.0) + self.assertTrue(isinstance(concrete, AbstractFoo)) - def bar(self): - return 'bar' + def test_registered(self): + foolike = FooLike() + self.assertTrue(isinstance(foolike, AbstractFoo)) - traited = TraitedBar() - self.assertTrue(isinstance(traited, AbstractBar)) - self.assertEquals(traited.x, 10) + def test_post_hoc_mixing(self): + class TraitedBar(HasTraits, AbstractBar): + __metaclass__ = ABCMetaHasTraits + x = Int(10) + def bar(self): + return 'bar' -except ImportError: - pass + traited = TraitedBar() + self.assertTrue(isinstance(traited, AbstractBar)) + self.assertEquals(traited.x, 10) diff --git a/traits/tests/test_anytrait_static_notifiers.py b/traits/tests/test_anytrait_static_notifiers.py index c8949cbcb..dc4c41e14 100644 --- a/traits/tests/test_anytrait_static_notifiers.py +++ b/traits/tests/test_anytrait_static_notifiers.py @@ -4,22 +4,26 @@ from traits import trait_notifiers - anycalls_0 = [] + + class AnytraitStaticNotifiers0(HasTraits): ok = Float + def _anytrait_changed(): anycalls_0.append(True) class AnytraitStaticNotifiers0Fail(HasTraits): fail = Float + def _anytrait_changed(): raise Exception('error') class AnytraitStaticNotifiers1(HasTraits): ok = Float + def _anytrait_changed(self): if not hasattr(self, 'anycalls'): self.anycalls = [] @@ -28,12 +32,14 @@ def _anytrait_changed(self): class AnytraitStaticNotifiers1Fail(HasTraits): fail = Float + def _anytrait_changed(self): raise Exception('error') class AnytraitStaticNotifiers2(HasTraits): ok = Float + def _anytrait_changed(self, name): if not hasattr(self, 'anycalls'): self.anycalls = [] @@ -42,12 +48,14 @@ def _anytrait_changed(self, name): class AnytraitStaticNotifiers2Fail(HasTraits): fail = Float + def _anytrait_changed(self, name): raise Exception('error') class AnytraitStaticNotifiers3(HasTraits): ok = Float + def _anytrait_changed(self, name, new): if not hasattr(self, 'anycalls'): self.anycalls = [] @@ -56,12 +64,14 @@ def _anytrait_changed(self, name, new): class AnytraitStaticNotifiers3Fail(HasTraits): fail = Float + def _anytrait_changed(self, name, new): raise Exception('error') class AnytraitStaticNotifiers4(HasTraits): ok = Float + def _anytrait_changed(self, name, old, new): if not hasattr(self, 'anycalls'): self.anycalls = [] @@ -70,6 +80,7 @@ def _anytrait_changed(self, name, old, new): class AnytraitStaticNotifiers4Fail(HasTraits): fail = Float + def _anytrait_changed(self, name, old, new): raise Exception('error') diff --git a/traits/tests/test_array.py b/traits/tests/test_array.py index 297bd327f..e809bcbea 100644 --- a/traits/tests/test_array.py +++ b/traits/tests/test_array.py @@ -18,17 +18,16 @@ from ..api import Array, Bool, HasTraits - -class Foo( HasTraits ): +class Foo(HasTraits): a = Array() event_fired = Bool(False) def _a_changed(self): self.event_fired = True -class ArrayTestCase( unittest.TestCase ): - """ Test cases for delegated traits. """ +class ArrayTestCase(unittest.TestCase): + """ Test cases for delegated traits. """ def test_zero_to_one_element(self): """ Test that an event fires when an Array trait changes from zero to @@ -43,9 +42,8 @@ def test_zero_to_one_element(self): f.a = concatenate((f.a, array([100]))) # Confirm that the static trait handler was invoked. - self.assertEqual( f.event_fired, True ) + self.assertEqual(f.event_fired, True) return #### EOF ###################################################################### - diff --git a/traits/tests/test_category.py b/traits/tests/test_category.py index ce9c8c821..e022f17a9 100644 --- a/traits/tests/test_category.py +++ b/traits/tests/test_category.py @@ -18,62 +18,67 @@ from ..api import HasTraits, Category, Str -class Base( HasTraits ) : + +class Base(HasTraits): y = Str("Base y") z = Str("Base z") -class BaseExtra( Category, Base ) : + +class BaseExtra(Category, Base): x = Str("BaseExtra x") -class BasePlus( Category, Base ) : + +class BasePlus(Category, Base): p = Str("BasePlus p") # z = Str("BasePlus z") overrides not allowed. -class BasePlusPlus( BasePlus ) : + +class BasePlusPlus(BasePlus): pp = Str("BasePlusPlus pp") -class CategoryTestCase( unittest.TestCase ) : + +class CategoryTestCase(unittest.TestCase): """ Test cases for traits category """ - def setUp( self ) : + def setUp(self): self.base = Base() return - def test_base_category(self) : + def test_base_category(self): """ Base class with traits """ - self.assertEqual( self.base.y, "Base y", msg="y != 'Base y'" ) - self.assertEqual( self.base.z, "Base z", msg="z != 'Base z'" ) + self.assertEqual(self.base.y, "Base y", msg="y != 'Base y'") + self.assertEqual(self.base.z, "Base z", msg="z != 'Base z'") return - def test_extra_extension_category(self) : + def test_extra_extension_category(self): """ Base class extended with a category subclass """ - self.assertEqual( self.base.x, "BaseExtra x", msg="x != 'BaseExtra x'" ) + self.assertEqual(self.base.x, "BaseExtra x", msg="x != 'BaseExtra x'") return - def test_plus_extension_category(self) : + def test_plus_extension_category(self): """ Base class extended with two category subclasses """ - self.assertEqual( self.base.x, "BaseExtra x", msg="x != 'BaseExtra x'" ) - self.assertEqual( self.base.p, "BasePlus p", msg="p != 'BasePlus p'" ) + self.assertEqual(self.base.x, "BaseExtra x", msg="x != 'BaseExtra x'") + self.assertEqual(self.base.p, "BasePlus p", msg="p != 'BasePlus p'") return - def test_subclass_extension_category(self) : + def test_subclass_extension_category(self): """ Category subclass does not extend base class. This test demonstrates that traits allows subclassing of a category class, but that the traits from the subclass are not actually added to the base class of the Category. Seems like the declaration of the subclass (BasePlusPlus) should fail. """ - try : + try: x = self.base.pp - self.fail( msg="base.pp should have thrown AttributeError " - "as Category subclassing is not supported." ) - except AttributeError : + self.fail(msg="base.pp should have thrown AttributeError " + "as Category subclassing is not supported.") + except AttributeError: pass basepp = BasePlusPlus() return - def test_subclass_instance_category(self) : + def test_subclass_instance_category(self): """ Category subclass instantiation not supported. This test demonstrates that traits allows subclassing of a category class, that subclass can be instantiated, but the traits of the parent @@ -81,14 +86,15 @@ class are not inherited. Seems like the declaration of the subclass (BasePlusPlus) should fail. """ bpp = BasePlusPlus() - self.assertEqual( bpp.pp, "BasePlusPlus pp", - msg="pp != 'BasePlusPlus pp'" ) - - try : - self.assertEqual( bpp.p, "BasePlus p", msg="p != 'BasePlus p'" ) - self.fail( msg="bpp.p should have thrown SystemError as " - "instantiating a subclass of a category is not supported." ) - except SystemError : + self.assertEqual(bpp.pp, "BasePlusPlus pp", + msg="pp != 'BasePlusPlus pp'") + + try: + self.assertEqual(bpp.p, "BasePlus p", msg="p != 'BasePlus p'") + self.fail(msg="bpp.p should have thrown SystemError as " + "instantiating a subclass of a category is not " + "supported.") + except SystemError: pass return diff --git a/traits/tests/test_clone.py b/traits/tests/test_clone.py index 3f1490297..317b99062 100644 --- a/traits/tests/test_clone.py +++ b/traits/tests/test_clone.py @@ -1,4 +1,3 @@ -#------------------------------------------------------------------------------ # Copyright (c) 2005, Enthought, Inc. # All rights reserved. # @@ -10,7 +9,6 @@ # # Author: David C. Morrill # Description: -#------------------------------------------------------------------------------ from __future__ import absolute_import @@ -18,25 +16,33 @@ from ..api import HasTraits, Instance, Str, Any, Property + class Foo(HasTraits): s = Str + class ClassWithAny(HasTraits): x = Property _x = Any + def _get_x(self): return self._x - def _set_x(self,x): + + def _set_x(self, x): self._x = x + class ClassWithInstance(HasTraits): x = Property _x = Instance(Foo) + def _get_x(self): return self._x - def _set_x(self,x): + + def _set_x(self, x): self._x = x + class ClassWithClassAttribute(HasTraits): name = 'class defined name' foo = Str @@ -45,6 +51,7 @@ class ClassWithClassAttribute(HasTraits): class BazAny(HasTraits): other = Any + class BarAny(HasTraits): other = Any @@ -66,6 +73,7 @@ class BazInstance(HasTraits): # not be cloned. ref = Instance(Foo, copy='ref') + class BarInstance(HasTraits): # used as circular reference back to owning BazInstance # NOTE: Setting copy to 'ref' will mean that when BarInstance is cloned, @@ -87,11 +95,10 @@ class BarInstance(HasTraits): ref = Instance(Foo, copy='ref') - -class CloneTestCase( unittest.TestCase ) : +class CloneTestCase(unittest.TestCase): """ Test cases for traits clone """ - def test_any(self) : + def test_any(self): b = ClassWithAny() f = Foo() @@ -99,12 +106,12 @@ def test_any(self) : b.x = f - bc = b.clone_traits( traits='all', copy='deep') - self.assertNotEqual( id(bc.x), id(f), 'Foo x not cloned') + bc = b.clone_traits(traits='all', copy='deep') + self.assertNotEqual(id(bc.x), id(f), 'Foo x not cloned') return - def test_instance(self) : + def test_instance(self): b = ClassWithInstance() f = Foo() @@ -113,7 +120,7 @@ def test_instance(self) : b.x = f bc = b.clone_traits(traits='all', copy='deep') - self.assertNotEqual( id(bc.x), id(f), 'Foo x not cloned') + self.assertNotEqual(id(bc.x), id(f), 'Foo x not cloned') return @@ -122,26 +129,27 @@ def test_class_attribute_missing(self): attributes. A change to the value of a class attribute via one instance causes the attribute to be removed from other instances. - AttributeError: 'ClassWithClassAttribute' object has no attribute 'name' + AttributeError: 'ClassWithClassAttribute' object has no attribute + 'name' """ s = 'class defined name' c = ClassWithClassAttribute() - self.assertEqual( s, c.name ) + self.assertEqual(s, c.name) c2 = ClassWithClassAttribute() - self.assertEqual( s, c.name ) - self.assertEqual( s, c2.name ) + self.assertEqual(s, c.name) + self.assertEqual(s, c2.name) s2 = 'name class attribute changed via clone' c2.name = s2 - self.assertEqual( s2, c2.name ) + self.assertEqual(s2, c2.name) - # this is failing with - # AttributeError: 'ClassWithClassAttribute' object has no attribute 'name' - self.assertEqual( s, c.name ) + # this is failing with AttributeError: 'ClassWithClassAttribute' + # object has no attribute 'name' + self.assertEqual(s, c.name) return @@ -157,10 +165,9 @@ def test_Any_circular_references(self): bar_copy = bar.clone_traits() - self.failIf( bar_copy is bar ) - self.failUnless( bar_copy.other is baz) - self.failUnless( bar_copy.other.other is bar) - + self.failIf(bar_copy is bar) + self.failUnless(bar_copy.other is baz) + self.failUnless(bar_copy.other.other is bar) def test_Any_circular_references_deep(self): @@ -172,10 +179,10 @@ def test_Any_circular_references_deep(self): bar_copy = bar.clone_traits(copy='deep') - self.failIf( bar_copy is bar ) - self.failIf( bar_copy.other is baz) - self.failIf( bar_copy.other.other is bar) - self.failUnless( bar_copy.other.other is bar_copy) + self.failIf(bar_copy is bar) + self.failIf(bar_copy.other is baz) + self.failIf(bar_copy.other.other is bar) + self.failUnless(bar_copy.other.other is bar_copy) def test_Instance_circular_references(self): @@ -200,35 +207,34 @@ def test_Instance_circular_references(self): baz_copy = baz.clone_traits() # Check Baz and Baz attributes.... - self.failIf( baz_copy is baz ) - self.failIf( baz_copy.other is bar) - self.failIf( baz_copy.unique is baz.unique ) - self.failIf( baz_copy.shared is baz.shared ) - self.failUnless( baz_copy.ref is ref ) + self.failIf(baz_copy is baz) + self.failIf(baz_copy.other is bar) + self.failIf(baz_copy.unique is baz.unique) + self.failIf(baz_copy.shared is baz.shared) + self.failUnless(baz_copy.ref is ref) # Check Bar and Bar attributes.... bar_copy = baz_copy.other # Check the Bar owned object - self.failIf( bar_copy.unique is bar.unique ) + self.failIf(bar_copy.unique is bar.unique) # Check the Bar reference to an object 'outside' the cloned graph. - self.failUnless( bar_copy.ref is ref ) + self.failUnless(bar_copy.ref is ref) # Check references to objects that where cloned, they should reference # the new clones not the original objects, except when copy is set # to 'ref' (as in the case of the 'other' trait). # When copy is set to ref, the trait does not get cloned. Therefore, # baz_copy.other.other is baz (and not baz_copy). - self.failIf( bar_copy.other is baz_copy ) - self.failUnless( bar_copy.other is baz ) + self.failIf(bar_copy.other is baz_copy) + self.failUnless(bar_copy.other is baz) # 'shared' does not have copy set to 'ref', and so bar_copy.shared # should reference the new clone. # should reference the new clones - self.failIf( bar_copy.shared is baz.shared ) - self.failUnless( bar_copy.shared is baz_copy.shared ) - + self.failIf(bar_copy.shared is baz.shared) + self.failUnless(bar_copy.shared is baz_copy.shared) def test_Instance_circular_references_deep(self): @@ -253,37 +259,37 @@ def test_Instance_circular_references_deep(self): baz_copy = baz.clone_traits(copy='deep') # Check Baz and Baz attributes.... - self.failIf( baz_copy is baz ) - self.failIf( baz_copy.other is bar ) - self.failIf( baz_copy.unique is baz.unique ) - self.failIf( baz_copy.shared is baz.shared ) + self.failIf(baz_copy is baz) + self.failIf(baz_copy.other is bar) + self.failIf(baz_copy.unique is baz.unique) + self.failIf(baz_copy.shared is baz.shared) # baz_copy.ref is checked below with bar_copy.ref. # Check Bar and Bar attributes.... bar_copy = baz_copy.other # Check the Bar owned object - self.failIf( bar_copy.unique is bar.unique ) + self.failIf(bar_copy.unique is bar.unique) # Since the two original 'ref' links were to a shared object, # the cloned links should be to a shared object. Also, the shared # object should be the original 'ref' object, since copy was set to # 'ref'. - self.failUnless( baz_copy.ref is bar_copy.ref ) - self.failUnless( bar_copy.ref is ref ) + self.failUnless(baz_copy.ref is bar_copy.ref) + self.failUnless(bar_copy.ref is ref) # Check references to objects that where cloned, they should reference # the new clones not the original objects, except when copy is set # to 'ref' (as in the case of the 'other' trait). That is, the 'deep' # flag on clone_traits should not override the 'copy' metadata on # the trait. - self.failIf( bar_copy.other is baz_copy ) - self.failUnless( bar_copy.other is baz ) + self.failIf(bar_copy.other is baz_copy) + self.failUnless(bar_copy.other is baz) # 'shared' does not have copy set to 'ref', and so bar_copy.shared # should reference the new clone. - self.failIf( bar_copy.shared is baz.shared ) - self.failUnless( bar_copy.shared is baz_copy.shared ) + self.failIf(bar_copy.shared is baz.shared) + self.failUnless(bar_copy.shared is baz_copy.shared) # # support running this test individually, from the command-line as a script diff --git a/traits/tests/test_container_events.py b/traits/tests/test_container_events.py index 69e30d47a..cf6f34fc4 100644 --- a/traits/tests/test_container_events.py +++ b/traits/tests/test_container_events.py @@ -1,4 +1,4 @@ -#------------------------------------------------------------------------------- +#------------------------------------------------------------------------------ # # Copyright (c) 2007, Enthought, Inc. # All rights reserved. @@ -10,7 +10,7 @@ # # Thanks for using Enthought open source! # -#------------------------------------------------------------------------------- +#------------------------------------------------------------------------------ """ Tests for Dict and List items_changed events @@ -20,15 +20,17 @@ from traits.testing.unittest_tools import unittest -from ..api import HasTraits, Dict, List +from ..api import HasTraits, Dict + class ListEventTestCase(unittest.TestCase): # TODO: Implement this! pass + class MyClass(HasTraits): """ A dummy HasTraits class with a Dict """ - d = Dict({"a": "apple", "b": "banana", "c": "cherry", "d": "durian" }) + d = Dict({"a": "apple", "b": "banana", "c": "cherry", "d": "durian"}) def __init__(self, callback): "The callback is called with the TraitDictEvent instance" @@ -40,9 +42,11 @@ def _d_items_changed(self, event): self.callback(event) return + class MyOtherClass(HasTraits): """ A dummy HasTraits class with a Dict """ - d = Dict({"a": "apple", "b": "banana", "c": "cherry", "d": "durian" }) + d = Dict({"a": "apple", "b": "banana", "c": "cherry", "d": "durian"}) + class Callback: """ @@ -71,19 +75,19 @@ class DictEventTestCase(unittest.TestCase): def test_setitem(self): # overwriting an existing item - cb = Callback(self, changed={"c":"cherry"}) + cb = Callback(self, changed={"c": "cherry"}) foo = MyClass(cb) foo.d["c"] = "coconut" self.assert_(cb.called) # adding a new item - cb = Callback(self, added={"g":"guava"}) + cb = Callback(self, added={"g": "guava"}) bar = MyClass(cb) bar.d["g"] = "guava" self.assert_(cb.called) return def test_delitem(self): - cb = Callback(self, removed={"b":"banana"}) + cb = Callback(self, removed={"b": "banana"}) foo = MyClass(cb) del foo.d["b"] self.assert_(cb.called) @@ -98,8 +102,8 @@ def test_clear(self): return def test_update(self): - update_dict = {"a":"artichoke", "f": "fig"} - cb = Callback(self, changed={"a":"apple"}, added={"f":"fig"}) + update_dict = {"a": "artichoke", "f": "fig"} + cb = Callback(self, changed={"a": "apple"}, added={"f": "fig"}) foo = MyClass(cb) foo.d.update(update_dict) self.assert_(cb.called) @@ -113,7 +117,7 @@ def test_setdefault(self): self.assert_(not cb.called) # Test adding a new value - cb = Callback(self, added={"f":"fig"}) + cb = Callback(self, added={"f": "fig"}) bar = MyClass(cb) self.assert_(bar.d.setdefault("f", "fig") == "fig") self.assert_(cb.called) @@ -137,7 +141,7 @@ def test_popitem(self): foo = MyClass(None) foo.d.clear() foo.d["x"] = "xylophone" - cb = Callback(self, removed={"x":"xylophone"}) + cb = Callback(self, removed={"x": "xylophone"}) foo.callback = cb self.assert_(foo.d.popitem() == ("x", "xylophone")) self.assert_(cb.called) @@ -146,24 +150,23 @@ def test_popitem(self): def test_dynamic_listener(self): foo = MyOtherClass() # Test adding - func = Callback(self, added={"g":"guava"}) + func = Callback(self, added={"g": "guava"}) foo.on_trait_change(func.__call__, "d_items") foo.d["g"] = "guava" foo.on_trait_change(func.__call__, "d_items", remove=True) self.assert_(func.called) # Test removing - func2 = Callback(self, removed={"a":"apple"}) + func2 = Callback(self, removed={"a": "apple"}) foo.on_trait_change(func2.__call__, "d_items") del foo.d["a"] foo.on_trait_change(func2.__call__, "d_items", remove=True) self.assert_(func2.called) # Test changing - func3 = Callback(self, changed={"b":"banana"}) + func3 = Callback(self, changed={"b": "banana"}) foo.on_trait_change(func3.__call__, "d_items") foo.d["b"] = "broccoli" foo.on_trait_change(func3.__call__, "d_items", remove=True) self.assert_(func3.called) return - diff --git a/traits/tests/test_copy_traits.py b/traits/tests/test_copy_traits.py index 4f06365d9..5268299aa 100644 --- a/traits/tests/test_copy_traits.py +++ b/traits/tests/test_copy_traits.py @@ -1,5 +1,3 @@ -#------------------------------------------------------------------------------- -# # Copyright (c) 2007, Enthought, Inc. # All rights reserved. # @@ -7,11 +5,6 @@ # license included in /LICENSE.txt and may be redistributed only # under the conditions described in the aforementioned license. The license # is also available online at http://www.enthought.com/licenses/BSD.txt -# -# Thanks for using Enthought open source! -# -# -#------------------------------------------------------------------------------- from __future__ import absolute_import @@ -23,36 +16,41 @@ class Shared(HasTraits): s = Str('new instance of Shared') + class Foo(HasTraits): s = Str('new instance of Foo') shared = Instance(Shared) + class Bar(HasTraits): s = Str('new instance of Bar') foo = Instance(Foo) shared = Instance(Shared) + class Baz(HasTraits): s = Str('new instance of Baz') bar = Instance(Bar) shared = Instance(Shared) -class CopyTraitsBase( unittest.TestCase ): + +class CopyTraitsBase(unittest.TestCase): """ Validate that copy_traits """ __test__ = False + def setUp(self): print '\n**CopyTraitsBase.setUp ', - super(CopyTraitsBase,self).setUp() + super(CopyTraitsBase, self).setUp() self.shared = Shared(s='shared') self.foo = Foo(shared=self.shared, s='foo') self.bar = Bar(shared=self.shared, foo=self.foo, s='bar') self.baz = Baz(shared=self.shared, bar=self.bar, s='baz') - self.shared2 = Shared( s='shared2' ) - self.foo2 = Foo( shared=self.shared2, s='foo2' ) - self.bar2 = Bar( shared=self.shared2, foo=self.foo2, s='bar2' ) - self.baz2 = Baz( shared=self.shared2, bar=self.bar2, s='baz2' ) + self.shared2 = Shared(s='shared2') + self.foo2 = Foo(shared=self.shared2, s='foo2') + self.bar2 = Bar(shared=self.shared2, foo=self.foo2, s='bar2') + self.baz2 = Baz(shared=self.shared2, bar=self.bar2, s='baz2') return @@ -77,11 +75,12 @@ def set_shared_copy(self, value): # self.baz2.base_trait('shared').copy = value #self.print_copy() -class TestCopyTraitsSetup( CopyTraitsBase ): +class TestCopyTraitsSetup(CopyTraitsBase): __test__ = True + def setUp(self): - super(TestCopyTraitsSetup,self).setUp() + super(TestCopyTraitsSetup, self).setUp() print '\nshared', self.shared print 'foo', self.foo print 'bar', self.bar @@ -94,21 +93,20 @@ def setUp(self): return def test_setup(self): - self.failUnless( self.foo is self.bar.foo ) - self.failUnless( self.bar is self.baz.bar ) - self.failUnless( self.foo.shared is self.shared ) - self.failUnless( self.bar.shared is self.shared ) - self.failUnless( self.baz.shared is self.shared ) - - self.failUnless( self.foo2 is self.bar2.foo ) - self.failUnless( self.bar2 is self.baz2.bar ) - self.failUnless( self.foo2.shared is self.shared2 ) - self.failUnless( self.bar2.shared is self.shared2 ) - self.failUnless( self.baz2.shared is self.shared2 ) + self.failUnless(self.foo is self.bar.foo) + self.failUnless(self.bar is self.baz.bar) + self.failUnless(self.foo.shared is self.shared) + self.failUnless(self.bar.shared is self.shared) + self.failUnless(self.baz.shared is self.shared) + + self.failUnless(self.foo2 is self.bar2.foo) + self.failUnless(self.bar2 is self.baz2.bar) + self.failUnless(self.foo2.shared is self.shared2) + self.failUnless(self.bar2.shared is self.shared2) + self.failUnless(self.baz2.shared is self.shared2) return - class CopyTraits: def test_baz2_s(self): @@ -132,17 +130,17 @@ def test_baz2_bar(self): # First hand Instance trait is different and # is not the same object as the source. - self.failIf( self.baz2.bar is None) - self.failIf( self.baz2.bar is self.bar2 ) - self.failIf( self.baz2.bar is self.baz.bar ) + self.failIf(self.baz2.bar is None) + self.failIf(self.baz2.bar is self.bar2) + self.failIf(self.baz2.bar is self.baz.bar) def test_baz2_bar_foo(self): # Second hand Instance trait is a different object and # is not the same object as the source. - self.failIf( self.baz2.bar.foo is None) - self.failIf( self.baz2.bar.foo is self.foo2 ) - self.failIf( self.baz2.bar.foo is self.baz.bar.foo ) + self.failIf(self.baz2.bar.foo is None) + self.failIf(self.baz2.bar.foo is self.foo2) + self.failIf(self.baz2.bar.foo is self.baz.bar.foo) class CopyTraitsSharedCopyNone: @@ -150,9 +148,9 @@ def test_baz2_shared(self): # First hand Instance trait is a different object and # is not the same object as the source. - self.failIf( self.baz2.shared is None) - self.failIf( self.baz2.shared is self.shared2) - self.failIf( self.baz2.shared is self.shared) + self.failIf(self.baz2.shared is None) + self.failIf(self.baz2.shared is self.shared2) + self.failIf(self.baz2.shared is self.shared) def test_baz2_bar_shared(self): # Second hand Instance that was shared is a different object and @@ -160,10 +158,10 @@ def test_baz2_bar_shared(self): # not the same object as the new first hand instance that was the same. # I.e. There are now (at least) two copies of one original object. - self.failIf( self.baz2.bar.shared is None ) - self.failIf( self.baz2.bar.shared is self.shared2 ) - self.failIf( self.baz2.bar.shared is self.shared ) - self.failIf( self.baz2.bar.shared is self.baz2.shared ) + self.failIf(self.baz2.bar.shared is None) + self.failIf(self.baz2.bar.shared is self.shared2) + self.failIf(self.baz2.bar.shared is self.shared) + self.failIf(self.baz2.bar.shared is self.baz2.shared) def test_baz2_bar_foo_shared(self): # Third hand Instance that was shared is a different object and @@ -171,14 +169,15 @@ def test_baz2_bar_foo_shared(self): # not the same object as the new first hand instance that was the same. # I.e. There are now (at least) two copies of one original object. - self.failIf( self.baz2.bar.foo.shared is None ) - self.failIf( self.baz2.bar.foo.shared is self.shared2 ) - self.failIf( self.baz2.bar.foo.shared is self.shared ) - self.failIf( self.baz2.bar.foo.shared is self.baz2.shared ) + self.failIf(self.baz2.bar.foo.shared is None) + self.failIf(self.baz2.bar.foo.shared is self.shared2) + self.failIf(self.baz2.bar.foo.shared is self.shared) + self.failIf(self.baz2.bar.foo.shared is self.baz2.shared) def test_baz2_bar_and_foo_shared(self): # - # THE BEHAVIOR DEMONSTRATED BY THIS TEST CASE DOES NOT SEEM TO BE CORRECT. + # THE BEHAVIOR DEMONSTRATED BY THIS TEST CASE DOES NOT SEEM TO BE + # CORRECT. # # Second and Third hand Instance object that was shared with first hand # instance are the same as each other but @@ -187,13 +186,14 @@ def test_baz2_bar_and_foo_shared(self): # first hand reference which is a different copy. # I.e. The shared relationship has been fubarred by copy_traits: it's # not maintained, but not completely destroyed. - self.failUnless( self.baz2.bar.shared is self.baz2.bar.foo.shared ) - self.failIf( self.baz2.shared is self.baz2.bar.foo.shared ) + self.failUnless(self.baz2.bar.shared is self.baz2.bar.foo.shared) + self.failIf(self.baz2.shared is self.baz2.bar.foo.shared) -class TestCopyTraitsSharedCopyNone( CopyTraits, - CopyTraitsSharedCopyNone ): +class TestCopyTraitsSharedCopyNone(CopyTraits, + CopyTraitsSharedCopyNone): __test__ = False + def setUp(self): print '\n***TestCopyTraitsSharedCopyNone', #super(TestCopyTraitsSharedCopyNone,self).setUp() @@ -202,119 +202,116 @@ def setUp(self): self.set_shared_copy('deep') return -class TestCopyTraitsCopyNotSpecified( CopyTraitsBase, TestCopyTraitsSharedCopyNone ): +class TestCopyTraitsCopyNotSpecified(CopyTraitsBase, + TestCopyTraitsSharedCopyNone): __test__ = True + def setUp(self): print '\n*TestCopyTraitsCopyNotSpecified', # super(TestCopyTraitsCopyNotSpecified,self).setUp() CopyTraitsBase.setUp(self) TestCopyTraitsSharedCopyNone.setUp(self) - self.baz2.copy_traits( self.baz ) + self.baz2.copy_traits(self.baz) return -class TestCopyTraitsCopyShallow( CopyTraitsBase, TestCopyTraitsSharedCopyNone ): - +class TestCopyTraitsCopyShallow(CopyTraitsBase, TestCopyTraitsSharedCopyNone): __test__ = True + def setUp(self): print '\n*TestCopyTraitsCopyShallow', # super(TestCopyTraitsCopyShallow,self).setUp() CopyTraitsBase.setUp(self) TestCopyTraitsSharedCopyNone.setUp(self) - self.baz2.copy_traits( self.baz, copy='shallow' ) + self.baz2.copy_traits(self.baz, copy='shallow') return -class TestCopyTraitsCopyDeep( CopyTraitsBase, TestCopyTraitsSharedCopyNone ): +class TestCopyTraitsCopyDeep(CopyTraitsBase, TestCopyTraitsSharedCopyNone): __test__ = True + def setUp(self): print '\n*TestCopyTraitsCopyDeep', # super(TestCopyTraitsCopyDeep,self).setUp() CopyTraitsBase.setUp(self) TestCopyTraitsSharedCopyNone.setUp(self) - self.baz2.copy_traits( self.baz, copy='deep' ) + self.baz2.copy_traits(self.baz, copy='deep') return - - - class CopyTraitsSharedCopyRef: def test_baz2_shared(self): # First hand Instance trait is a different object and # is the same object as the source. - self.failIf( self.baz2.shared is None) - self.failIf( self.baz2.shared is self.shared2) - self.failUnless( self.baz2.shared is self.shared) + self.failIf(self.baz2.shared is None) + self.failIf(self.baz2.shared is self.shared2) + self.failUnless(self.baz2.shared is self.shared) def test_baz2_bar_shared(self): - self.failIf( self.baz2.bar.shared is None ) - self.failIf( self.baz2.bar.shared is self.shared2 ) - self.failUnless( self.baz2.bar.shared is self.shared ) - self.failUnless( self.baz2.bar.shared is self.baz2.shared ) + self.failIf(self.baz2.bar.shared is None) + self.failIf(self.baz2.bar.shared is self.shared2) + self.failUnless(self.baz2.bar.shared is self.shared) + self.failUnless(self.baz2.bar.shared is self.baz2.shared) def test_baz2_bar_foo_shared(self): - self.failIf( self.baz2.bar.foo.shared is None ) - self.failIf( self.baz2.bar.foo.shared is self.shared2 ) - self.failUnless( self.baz2.bar.foo.shared is self.shared ) - self.failUnless( self.baz2.bar.foo.shared is self.baz2.shared ) + self.failIf(self.baz2.bar.foo.shared is None) + self.failIf(self.baz2.bar.foo.shared is self.shared2) + self.failUnless(self.baz2.bar.foo.shared is self.shared) + self.failUnless(self.baz2.bar.foo.shared is self.baz2.shared) def test_baz2_bar_and_foo_shared(self): - self.failUnless( self.baz2.bar.shared is self.baz2.bar.foo.shared ) - self.failUnless( self.baz2.shared is self.baz2.bar.foo.shared ) + self.failUnless(self.baz2.bar.shared is self.baz2.bar.foo.shared) + self.failUnless(self.baz2.shared is self.baz2.bar.foo.shared) -class TestCopyTraitsSharedCopyRef( CopyTraits, - CopyTraitsSharedCopyRef ): +class TestCopyTraitsSharedCopyRef(CopyTraits, + CopyTraitsSharedCopyRef): __test__ = False + def setUp(self): print '\n***TestCopyTraitsSharedCopyRef.setUp ', #super(TestCopyTraitsSharedCopyRef,self).setUp() self.set_shared_copy('ref') return + # The next three tests demonstrate that a 'ref' trait is always copied as a # reference regardless of the copy argument to copy_traits. That is, shallow # and deep are indistinguishable. - -class TestCopyTraitsCopyNotSpecifiedSharedRef( CopyTraitsBase, TestCopyTraitsSharedCopyRef): - +class TestCopyTraitsCopyNotSpecifiedSharedRef(CopyTraitsBase, + TestCopyTraitsSharedCopyRef): __test__ = True + def setUp(self): print '\n*TestCopyTraitsCopyNotSpecifiedSharedRef.setUp', -# super(TestCopyTraitsCopyNotSpecifiedSharedRef,self).setUp() CopyTraitsBase.setUp(self) TestCopyTraitsSharedCopyRef.setUp(self) - self.baz2.copy_traits( self.baz ) + self.baz2.copy_traits(self.baz) return -class TestCopyTraitsCopyShallowSharedRef( CopyTraitsBase, TestCopyTraitsSharedCopyRef ): - +class TestCopyTraitsCopyShallowSharedRef(CopyTraitsBase, + TestCopyTraitsSharedCopyRef): __test__ = True + def setUp(self): print '\n*TestCopyTraitsCopyShallowSharedRef.setUp', -# super(TestCopyTraitsCopyShallowSharedRef,self).setUp() CopyTraitsBase.setUp(self) TestCopyTraitsSharedCopyRef.setUp(self) - self.baz2.copy_traits( self.baz, copy='shallow' ) + self.baz2.copy_traits(self.baz, copy='shallow') return -class TestCopyTraitsCopyDeepSharedRef( CopyTraitsBase, TestCopyTraitsSharedCopyRef ): +class TestCopyTraitsCopyDeepSharedRef(CopyTraitsBase, + TestCopyTraitsSharedCopyRef): __test__ = True + def setUp(self): print '\n*TestCopyTraitsCopyDeepSharedRef.setUp', -# super(TestCopyTraitsCopyDeepSharedRef,self).setUp() CopyTraitsBase.setUp(self) TestCopyTraitsSharedCopyRef.setUp(self) - self.baz2.copy_traits( self.baz, copy='deep' ) + self.baz2.copy_traits(self.baz, copy='deep') return - - - ### EOF - - diff --git a/traits/tests/test_copyable_trait_names.py b/traits/tests/test_copyable_trait_names.py index 054996ddb..1d40fa9e3 100644 --- a/traits/tests/test_copyable_trait_names.py +++ b/traits/tests/test_copyable_trait_names.py @@ -1,5 +1,3 @@ -#------------------------------------------------------------------------------- -# # Copyright (c) 2007, Enthought, Inc. # All rights reserved. # @@ -7,16 +5,14 @@ # license included in /LICENSE.txt and may be redistributed only # under the conditions described in the aforementioned license. The license # is also available online at http://www.enthought.com/licenses/BSD.txt -# -# Thanks for using Enthought open source! -# -#------------------------------------------------------------------------------- from __future__ import absolute_import from traits.testing.unittest_tools import unittest -from ..api import HasTraits, Any, Bool, Delegate, Event, Instance, Property, Str +from ..api import (HasTraits, Any, Bool, Delegate, Event, Instance, Property, + Str) + class Foo(HasTraits): @@ -25,7 +21,7 @@ class Foo(HasTraits): s = Str i = Instance(HasTraits) e = Event - d = Delegate( 'i' ) + d = Delegate('i') p = Property @@ -47,6 +43,7 @@ def _get_p_ro(self): def _set_p_wo(self, p_wo): self._p_wo = p_wo + class TestCopyableTraitNames(unittest.TestCase): """ Validate that copyable_trait_names returns the appropriate result. """ @@ -82,6 +79,7 @@ def test_delegate_copyable(self): def test_property_copyable(self): self.assert_('p' in self.names) + class TestCopyableTraitNameQueries(unittest.TestCase): def setUp(self): diff --git a/traits/tests/test_cythonized_traits.py b/traits/tests/test_cythonized_traits.py index cd4a16ed4..e5783aa02 100644 --- a/traits/tests/test_cythonized_traits.py +++ b/traits/tests/test_cythonized_traits.py @@ -19,6 +19,7 @@ from ..testing.unittest_tools import unittest, UnittestTools + def has_no_compiler(): if no_cython: return True @@ -30,6 +31,7 @@ def has_no_compiler(): except: return True + def cython_version(): if no_cython: return None @@ -38,18 +40,20 @@ def cython_version(): SKIP_TEST = has_no_compiler() + # Cython 0.19 implementation of safe_type fails while parsing some of the # code. We provide a very basic implementation that always returns object # (we don't need any particular optimizations) def _always_object_type(arg, context): return 'object' + class CythonizedTraitsTestCase(unittest.TestCase, UnittestTools): @unittest.skipIf(SKIP_TEST, 'Missing Cython and/or compiler') def test_simple_default_methods(self): - code = """ + code = """ from traits.api import HasTraits, Str class Test(HasTraits): @@ -122,7 +126,8 @@ def _update_value(self): return Test() """ - obj = cython.inline(code, get_type=_always_object_type, force=True, locals={}, globals={}) + obj = cython.inline(code, get_type=_always_object_type, force=True, + locals={}, globals={}) with self.assertTraitChanges(obj, 'value', count=1): obj.name = 'changing_name' @@ -146,7 +151,8 @@ def _get_name_len(self): return Test() """ - obj = cython.inline(code, get_type=_always_object_type, force=True, locals={}, globals={}) + obj = cython.inline(code, get_type=_always_object_type, force=True, + locals={}, globals={}) self.assertEquals(obj.name_len, len(obj.name)) @@ -154,7 +160,6 @@ def _get_name_len(self): obj.name = 'Bob' self.assertEquals(obj.name_len, len(obj.name)) - @unittest.skipIf(SKIP_TEST, 'Missing Cython and/or compiler') def test_on_trait_properties_with_standard_getter(self): @@ -172,7 +177,8 @@ def _get_name_length(self): return Test() """ - obj = cython.inline(code, get_type=_always_object_type, force=True, locals={}, globals={}) + obj = cython.inline(code, get_type=_always_object_type, force=True, + locals={}, globals={}) self.assertEquals(obj.name_len, len(obj.name)) @@ -202,7 +208,8 @@ class Test(HasTraits): return Test() """ - obj = cython.inline(code, get_type=_always_object_type, force=True, locals={}, globals={}) + obj = cython.inline(code, get_type=_always_object_type, force=True, + locals={}, globals={}) self.assertEquals(obj.funky_name, obj.name) @@ -238,9 +245,6 @@ class Test(HasTraits): obj.name = 'Bob' self.assertEquals(obj.funky_name, obj.name) - - - @unittest.skipIf(SKIP_TEST, 'Missing Cython and/or compiler') def test_on_trait_lambda_failure(self): @@ -265,7 +269,8 @@ class Test(HasTraits): """ try: - cython.inline(code, get_type=_always_object_type, force=True, locals={}, globals={}) + cython.inline(code, get_type=_always_object_type, force=True, + locals={}, globals={}) except: # We suppose we have an exception. Because of the usage of the # skipIf decorator on the test, we can't use an expectedFailure @@ -276,5 +281,3 @@ class Test(HasTraits): 'Unexpected results. Cython was not managing lambda as regular' ' functions. Behaviour changed ...' ) - - diff --git a/traits/tests/test_delegate.py b/traits/tests/test_delegate.py index 013b6356f..fb3ba3820 100644 --- a/traits/tests/test_delegate.py +++ b/traits/tests/test_delegate.py @@ -1,4 +1,3 @@ -#------------------------------------------------------------------------------ # Copyright (c) 2005, Enthought, Inc. # All rights reserved. # @@ -7,7 +6,6 @@ # under the conditions described in the aforementioned license. The license # is also available online at http://www.enthought.com/licenses/BSD.txt # Thanks for using Enthought open source! -#------------------------------------------------------------------------------ from __future__ import absolute_import @@ -23,90 +21,95 @@ foo_s_handler_self = None foo_t_handler_self = None -class Foo( HasTraits ): - s = Str( 'foo' ) - t = Str( 'foo.t' ) - u = Str( 'foo.u' ) + +class Foo(HasTraits): + s = Str('foo') + t = Str('foo.t') + u = Str('foo.u') def _s_changed(self, name, old, new): - print 'Foo._s_changed( %s, %s, %s, %s)' % (self, name, old, new) + print 'Foo._s_changed(%s, %s, %s, %s)' % (self, name, old, new) global foo_s_handler_self foo_s_handler_self = self return def _t_changed(self, name, old, new): - print 'Foo._t_changed( %s, %s, %s, %s)' % (self, name, old, new) + print 'Foo._t_changed(%s, %s, %s, %s)' % (self, name, old, new) global foo_t_handler_self foo_t_handler_self = self return -class Bar( HasTraits ): - foo = Instance( Foo, () ) - s = Delegate( 'foo' ) -class BazModify( HasTraits ): - foo = Instance( Foo, () ) - sd = Delegate( 'foo', prefix='s', modify=True ) - t = Delegate( 'foo', modify=True ) - u = Delegate( 'foo', listenable=False, modify=True ) +class Bar(HasTraits): + foo = Instance(Foo, ()) + s = Delegate('foo') + + +class BazModify(HasTraits): + foo = Instance(Foo, ()) + sd = Delegate('foo', prefix='s', modify=True) + t = Delegate('foo', modify=True) + u = Delegate('foo', listenable=False, modify=True) def _s_changed(self, name, old, new): # should never be called - print 'BazModify._s_changed( %s, %s, %s, %s)' % (self, name, old, new) + print 'BazModify._s_changed(%s, %s, %s, %s)' % (self, name, old, new) global baz_s_handler_self baz_s_handler_self = self return def _sd_changed(self, name, old, new): - print 'BazModify._sd_changed( %s, %s, %s, %s)' % (self, name, old, new) + print 'BazModify._sd_changed(%s, %s, %s, %s)' % (self, name, old, new) global baz_sd_handler_self baz_sd_handler_self = self return def _t_changed(self, name, old, new): - print 'BazModify._t_changed( %s, %s, %s, %s)' % (self, name, old, new) + print 'BazModify._t_changed(%s, %s, %s, %s)' % (self, name, old, new) global baz_t_handler_self baz_t_handler_self = self return def _u_changed(self, name, old, new): - print 'BazModify._u_changed( %s, %s, %s, %s)' % (self, name, old, new) + print 'BazModify._u_changed(%s, %s, %s, %s)' % (self, name, old, new) global baz_u_handler_self baz_u_handler_self = self return -class BazNoModify( HasTraits ): - foo = Instance( Foo, () ) - sd = Delegate( 'foo', prefix='s' ) - t = Delegate( 'foo' ) - u = Delegate( 'foo', listenable=False ) +class BazNoModify(HasTraits): + foo = Instance(Foo, ()) + sd = Delegate('foo', prefix='s') + t = Delegate('foo') + u = Delegate('foo', listenable=False) def _s_changed(self, name, old, new): - print 'BazNoModify._s_changed( %s, %s, %s, %s)' % (self, name, old, new) + print 'BazNoModify._s_changed(%s, %s, %s, %s)' % (self, name, old, new) global baz_s_handler_self baz_s_handler_self = self return def _sd_changed(self, name, old, new): - print 'BazNoModify._sd_changed( %s, %s, %s, %s)' % (self, name, old, new) + print 'BazNoModify._sd_changed(%s, %s, %s, %s)' % (self, name, old, + new) global baz_sd_handler_self baz_sd_handler_self = self return def _t_changed(self, name, old, new): - print 'BazNoModify._t_changed( %s, %s, %s, %s)' % (self, name, old, new) + print 'BazNoModify._t_changed(%s, %s, %s, %s)' % (self, name, old, new) global baz_t_handler_self baz_t_handler_self = self return def _u_changed(self, name, old, new): - print 'BazNoModify._u_changed( %s, %s, %s, %s)' % (self, name, old, new) + print 'BazNoModify._u_changed(%s, %s, %s, %s)' % (self, name, old, new) global baz_u_handler_self baz_u_handler_self = self return -class DelegateTestCase( unittest.TestCase ): + +class DelegateTestCase(unittest.TestCase): """ Test cases for delegated traits. """ def setUp(self): @@ -132,251 +135,216 @@ def test_reset(self): b = Bar(foo=f) # Check initial delegation. - self.assertEqual( f.s, b.s ) + self.assertEqual(f.s, b.s) # Check that an override works. b.s = 'bar' - self.assertNotEqual( f.s, b.s ) + self.assertNotEqual(f.s, b.s) # Check that we can reset back to delegation. This is what we are # really testing for. del b.s - self.assertEqual( f.s, b.s ) - + self.assertEqual(f.s, b.s) return - # Below are 8 tests to check the calling of change notification handlers. # There are 8 cases for the 2x2x2 matrix with axes: # Delegate with prefix or not # Delegate with modify write through or not # Handler in the delegator and delegatee - # def test_modify_prefix_handler_on_delegator(self): f = Foo() b = BazModify(foo=f) - self.assertEqual( f.s, b.sd ) + self.assertEqual(f.s, b.sd) b.sd = 'changed' - self.assertEqual( f.s, b.sd ) + self.assertEqual(f.s, b.sd) # Don't expect _s_changed to be called because from Baz's perspective # the trait is named 'sd' - self.assertEqual( baz_s_handler_self, None ) + self.assertEqual(baz_s_handler_self, None) # Do expect '_sd_changed' to be called with b as self - self.assertEqual( baz_sd_handler_self, b ) - + self.assertEqual(baz_sd_handler_self, b) return def test_modify_prefix_handler_on_delegatee(self): f = Foo() b = BazModify(foo=f) - self.assertEqual( f.s, b.sd ) + self.assertEqual(f.s, b.sd) b.sd = 'changed' - self.assertEqual( f.s, b.sd ) + self.assertEqual(f.s, b.sd) # Foo expects its '_s_changed' handler to be called with f as self - self.assertEqual( foo_s_handler_self, f ) - + self.assertEqual(foo_s_handler_self, f) return - - def test_no_modify_prefix_handler_on_delegator(self): f = Foo() b = BazNoModify(foo=f) - self.assertEqual( f.s, b.sd ) + self.assertEqual(f.s, b.sd) b.sd = 'changed' - self.assertNotEqual( f.s, b.sd ) + self.assertNotEqual(f.s, b.sd) # Don't expect _s_changed to be called because from Baz's perspective # the trait is named 'sd' - self.assertEqual( baz_s_handler_self, None ) + self.assertEqual(baz_s_handler_self, None) # Do expect '_sd_changed' to be called with b as self - self.assertEqual( baz_sd_handler_self, b ) - + self.assertEqual(baz_sd_handler_self, b) return def test_no_modify_prefix_handler_on_delegatee_not_called(self): f = Foo() b = BazNoModify(foo=f) - self.assertEqual( f.s, b.sd ) + self.assertEqual(f.s, b.sd) b.sd = 'changed' - self.assertNotEqual( f.s, b.sd ) + self.assertNotEqual(f.s, b.sd) # Foo expects its '_s_changed' handler to be called with f as self - self.assertEqual( foo_s_handler_self, None ) - + self.assertEqual(foo_s_handler_self, None) return - - - def test_modify_handler_on_delegator(self): f = Foo() b = BazModify(foo=f) - self.assertEqual( f.t, b.t ) + self.assertEqual(f.t, b.t) b.t = 'changed' - self.assertEqual( f.t, b.t ) + self.assertEqual(f.t, b.t) # Do expect '_t_changed' to be called with b as self - self.assertEqual( baz_t_handler_self, b ) - + self.assertEqual(baz_t_handler_self, b) return def test_modify_handler_on_delegatee(self): f = Foo() b = BazModify(foo=f) - self.assertEqual( f.t, b.t ) + self.assertEqual(f.t, b.t) b.t = 'changed' - self.assertEqual( f.t, b.t ) + self.assertEqual(f.t, b.t) # Foo t did change so '_t_changed' handler should be called - self.assertEqual( foo_t_handler_self, f) - + self.assertEqual(foo_t_handler_self, f) return - def test_no_modify_handler_on_delegator(self): f = Foo() b = BazNoModify(foo=f) - self.assertEqual( f.t, b.t ) + self.assertEqual(f.t, b.t) b.t = 'changed' - self.assertNotEqual( f.t, b.t ) + self.assertNotEqual(f.t, b.t) # Do expect '_t_changed' to be called with b as self - self.assertEqual( baz_t_handler_self, b ) - + self.assertEqual(baz_t_handler_self, b) return def test_no_modify_handler_on_delegatee_not_called(self): f = Foo() b = BazNoModify(foo=f) - self.assertEqual( f.t, b.t ) + self.assertEqual(f.t, b.t) b.t = 'changed' - self.assertNotEqual( f.t, b.t ) + self.assertNotEqual(f.t, b.t) # Foo t did not change so '_t_changed' handler should not be called - self.assertEqual( foo_t_handler_self, None) - + self.assertEqual(foo_t_handler_self, None) return - - # Below are 4 tests for notification when the delegated trait is changed # directly rather than through the delegator. - def test_no_modify_handler_on_delegatee_direct_change(self): f = Foo() b = BazNoModify(foo=f) - self.assertEqual( f.t, b.t ) + self.assertEqual(f.t, b.t) f.t = 'changed' - self.assertEqual( f.t, b.t ) + self.assertEqual(f.t, b.t) # Foo t did change so '_t_changed' handler should be called - self.assertEqual( foo_t_handler_self, f) - + self.assertEqual(foo_t_handler_self, f) return def test_no_modify_handler_on_delegator_direct_change(self): f = Foo() b = BazNoModify(foo=f) - self.assertEqual( f.t, b.t ) + self.assertEqual(f.t, b.t) f.t = 'changed' - self.assertEqual( f.t, b.t ) + self.assertEqual(f.t, b.t) # Do expect '_t_changed' to be called with b as self - self.assertEqual( baz_t_handler_self, b ) - + self.assertEqual(baz_t_handler_self, b) return - - - - - def test_modify_handler_on_delegatee_direct_change(self): f = Foo() b = BazModify(foo=f) - self.assertEqual( f.t, b.t ) + self.assertEqual(f.t, b.t) f.t = 'changed' - self.assertEqual( f.t, b.t ) + self.assertEqual(f.t, b.t) # Foo t did change so '_t_changed' handler should be called - self.assertEqual( foo_t_handler_self, f) - + self.assertEqual(foo_t_handler_self, f) return def test_modify_handler_on_delegator_direct_change(self): f = Foo() b = BazModify(foo=f) - self.assertEqual( f.t, b.t ) + self.assertEqual(f.t, b.t) f.t = 'changed' - self.assertEqual( f.t, b.t ) + self.assertEqual(f.t, b.t) # Do expect '_t_changed' to be called with b as self - self.assertEqual( baz_t_handler_self, b ) - + self.assertEqual(baz_t_handler_self, b) return - # Below are tests which check that we can turn off listenableness. - def test_modify_handler_not_listenable(self): f = Foo() b = BazModify(foo=f) - self.assertEqual( f.u, b.u ) + self.assertEqual(f.u, b.u) f.u = 'changed' - self.assertEqual( f.u, b.u ) + self.assertEqual(f.u, b.u) # Do not expect '_u_changed' to be called. - self.assertEqual( baz_u_handler_self, None ) - + self.assertEqual(baz_u_handler_self, None) return def test_no_modify_handler_not_listenable(self): f = Foo() b = BazNoModify(foo=f) - self.assertEqual( f.u, b.u ) + self.assertEqual(f.u, b.u) f.u = 'changed' - self.assertEqual( f.u, b.u ) + self.assertEqual(f.u, b.u) # Do not expect '_u_changed' to be called. - self.assertEqual( baz_u_handler_self, None ) - + self.assertEqual(baz_u_handler_self, None) return if __name__ == '__main__': unittest.main() - -#### EOF ###################################################################### - +# EOF # diff --git a/traits/tests/test_dict.py b/traits/tests/test_dict.py index 531fba1a7..13c9cdb60 100644 --- a/traits/tests/test_dict.py +++ b/traits/tests/test_dict.py @@ -1,5 +1,3 @@ -#------------------------------------------------------------------------------ -# # Copyright (c) 2007, Enthought, Inc. # All rights reserved. # @@ -7,10 +5,6 @@ # license included in /LICENSE.txt and may be redistributed only # under the conditions described in the aforementioned license. The license # is also available online at http://www.enthought.com/licenses/BSD.txt -# -# Thanks for using Enthought open source! -# -#------------------------------------------------------------------------------ """ Test cases for dictionary (Dict) traits. """ from __future__ import absolute_import @@ -29,18 +23,17 @@ def create_listener(): def listener(obj, trait_name, old, new): - listener.obj = obj + listener.obj = obj listener.trait_name = trait_name - listener.new = new - listener.old = old - listener.called += 1 - + listener.new = new + listener.old = old + listener.called += 1 return - listener.initialize = lambda : initialize_listener(listener) - + listener.initialize = lambda: initialize_listener(listener) return initialize_listener(listener) + def initialize_listener(listener): """ Initialize a listener so it looks like it hasn't been called. @@ -49,13 +42,13 @@ def initialize_listener(listener): """ - listener.obj = None + listener.obj = None listener.trait_name = None - listener.old = None - listener.new = None - listener.called = 0 + listener.old = None + listener.new = None + listener.called = 0 - return listener # For convenience + return listener # For convenience class TestDict(unittest.TestCase): @@ -86,7 +79,7 @@ def _fire_modified_event(self, obj, trait_name, old, new): bar.on_trait_change(listener, 'modified') # Assign a completely new dictionary. - bar.foos = {'dino' : Foo(name='dino')} + bar.foos = {'dino': Foo(name='dino')} self.assertEqual(1, listener.called) self.assertEqual('modified', listener.trait_name) diff --git a/traits/tests/test_dynamic_notifiers.py b/traits/tests/test_dynamic_notifiers.py index b336c95ed..f45834d5d 100644 --- a/traits/tests/test_dynamic_notifiers.py +++ b/traits/tests/test_dynamic_notifiers.py @@ -75,22 +75,36 @@ def failing_method_listener_4(self, obj, name, old, new): # 'ok' function listeners calls_0 = [] + + def function_listener_0(): calls_0.append(True) + calls_1 = [] + + def function_listener_1(new): calls_1.append(new) + calls_2 = [] + + def function_listener_2(name, new): calls_2.append((name, new)) + calls_3 = [] + + def function_listener_3(obj, name, new): calls_3.append((obj, name, new)) + calls_4 = [] + + def function_listener_4(obj, name, old, new): calls_4.append((obj, name, old, new)) @@ -99,22 +113,27 @@ def function_listener_4(obj, name, old, new): exceptions_from = [] + def failing_function_listener_0(): exceptions_from.append(0) raise Exception('error') + def failing_function_listener_1(new): exceptions_from.append(1) raise Exception('error') + def failing_function_listener_2(name, new): exceptions_from.append(2) raise Exception('error') + def failing_function_listener_3(obj, name, new): exceptions_from.append(3) raise Exception('error') + def failing_function_listener_4(obj, name, old, new): exceptions_from.append(4) raise Exception('error') @@ -160,7 +179,7 @@ def test_dynamic_notifiers_methods_failing(self): obj = DynamicNotifiers() obj.fail = 1 - _py2to3.assertCountEqual(self, [0,1,2,3,4], obj.exceptions_from) + _py2to3.assertCountEqual(self, [0, 1, 2, 3, 4], obj.exceptions_from) self.assertEqual([(obj, 'fail', 0, 1)]*5, self.exceptions) def test_dynamic_notifiers_functions(self): @@ -198,10 +217,10 @@ def test_dynamic_notifiers_functions_failing(self): obj.fail = 1 - _py2to3.assertCountEqual(self, [0,1,2,3,4], obj.exceptions_from) + _py2to3.assertCountEqual(self, [0, 1, 2, 3, 4], obj.exceptions_from) # 10 failures: 5 are from the internal dynamic listeners, see # test_dynamic_notifiers_methods_failing - self.assertEqual([(obj, 'fail', 0, 1)]*10, self.exceptions) + self.assertEqual([(obj, 'fail', 0, 1)] * 10, self.exceptions) def test_object_can_be_garbage_collected(self): # Make sure that a trait object can be garbage collected even though @@ -215,6 +234,7 @@ def test_object_can_be_garbage_collected(self): # Create a weak reference to `obj` with a callback that flags when the # object is finalized. obj_collected = [] + def obj_collected_callback(weakref): obj_collected.append(True) diff --git a/traits/tests/test_enum.py b/traits/tests/test_enum.py index e2bbbc2b3..31a1c6d74 100644 --- a/traits/tests/test_enum.py +++ b/traits/tests/test_enum.py @@ -2,6 +2,7 @@ from traits.api import Enum, HasTraits, List, Property, TraitError + class ExampleModel(HasTraits): valid_models = Property(List) root = Enum(values='valid_models') @@ -9,6 +10,7 @@ class ExampleModel(HasTraits): def _get_valid_models(self): return ['model1', 'model2', 'model3'] + class EnumTestCase(unittest.TestCase): def test_valid_enum(self): example_model = ExampleModel(root='model1') @@ -21,5 +23,3 @@ def assign_invalid(): example_model.root = 'not_valid_model' self.assertRaises(TraitError, assign_invalid) - - diff --git a/traits/tests/test_event_order.py b/traits/tests/test_event_order.py index fd32612d2..9cb1b3144 100644 --- a/traits/tests/test_event_order.py +++ b/traits/tests/test_event_order.py @@ -1,5 +1,3 @@ -#------------------------------------------------------------------------------- -# # Copyright (c) 2007, Enthought, Inc. # All rights reserved. # @@ -9,10 +7,6 @@ # under the conditions described in the aforementioned license. The # license # is also available online at http://www.enthought.com/licenses/BSD.txt -# -# Thanks for using Enthought open source! -# -#------------------------------------------------------------------------------- from __future__ import absolute_import @@ -21,16 +15,16 @@ from ..api import HasTraits, Str, Instance, Any -class TestEventOrder( unittest.TestCase ): +class TestEventOrder(unittest.TestCase): """ Tests that demonstrate that trait events are delivered in LIFO order rather than FIFO order. Baz receives the "effect" event before it receives the "cause" event. """ def setUp(self): - foo = Foo( cause='ORIGINAL') - bar = Bar( foo=foo, test=self ) - baz = Baz( bar=bar, test=self ) + foo = Foo(cause='ORIGINAL') + bar = Bar(foo=foo, test=self) + baz = Baz(bar=bar, test=self) self.events_delivered = [] foo.cause = 'CHANGE' @@ -41,7 +35,7 @@ def test_lifo_order(self): 'Baz._effect_changed', 'Baz._caused_changed'] - self.failUnlessEqual( self.events_delivered, lifo) + self.failUnlessEqual(self.events_delivered, lifo) return def test_not_fifo_order(self): @@ -49,7 +43,7 @@ def test_not_fifo_order(self): 'Baz._caused_changed', 'Baz._effect_changed'] - self.failIfEqual( self.events_delivered, fifo) + self.failIfEqual(self.events_delivered, fifo) return @@ -64,41 +58,42 @@ class Bar(HasTraits): def _foo_changed(self, obj, old, new): if old is not None and old is not new: - old.on_trait_change( self._cause_changed, name='cause', remove=True) + old.on_trait_change(self._cause_changed, name='cause', remove=True) if new is not None: - new.on_trait_change( self._cause_changed, name='cause') + new.on_trait_change(self._cause_changed, name='cause') return def _cause_changed(self, obj, name, old, new): - self.test.events_delivered.append( 'Bar._caused_changed' ) + self.test.events_delivered.append('Bar._caused_changed') self.effect = new.lower() return + class Baz(HasTraits): bar = Instance(Bar) test = Any def _bar_changed(self, obj, old, new): if old is not None and old is not new: - old.on_trait_change( self._effect_changed, name='effect', + old.on_trait_change(self._effect_changed, name='effect', remove=True) - old.foo.on_trait_change( self._cause_changed, name='cause', + old.foo.on_trait_change(self._cause_changed, name='cause', remove=True) if new is not None: - new.foo.on_trait_change( self._cause_changed, name='cause') - new.on_trait_change( self._effect_changed, name='effect') + new.foo.on_trait_change(self._cause_changed, name='cause') + new.on_trait_change(self._effect_changed, name='effect') return def _cause_changed(self, obj, name, old, new): - self.test.events_delivered.append( 'Baz._caused_changed' ) + self.test.events_delivered.append('Baz._caused_changed') return def _effect_changed(self, obj, name, old, new): - self.test.events_delivered.append( 'Baz._effect_changed' ) + self.test.events_delivered.append('Baz._effect_changed') return ### EOF ####################################################################### diff --git a/traits/tests/test_events.py b/traits/tests/test_events.py index fc6c00eaf..2795d562c 100644 --- a/traits/tests/test_events.py +++ b/traits/tests/test_events.py @@ -1,4 +1,3 @@ -#------------------------------------------------------------------------------ # Copyright (c) 2005, Enthought, Inc. # All rights reserved. # @@ -10,22 +9,19 @@ # # Author: David C. Morrill Date: 10/22/2003 Description: Unit test case for # Traits event notification handling. -# ------------------------------------------------------------------------------ from __future__ import absolute_import from ..api import HasTraits -#------------------------------------------------------------------------------ - -class TestBase ( HasTraits ): +class TestBase(HasTraits): __traits__ = { 't1': 0, 't2': 0 } - def test ( self ): + def test(self): print '---------- Begin %s test ----------' % self.__class__.__name__ print 'normal changes' self.t1 = 1 @@ -33,102 +29,93 @@ def test ( self ): print '---------- End %s test ----------\n' % self.__class__.__name__ -#------------------------------------------------------------------------------ -class Test1 ( TestBase ): +class Test1(TestBase): - def t1_changed ( self, old, new ): + def t1_changed(self, old, new): print 't1 changed:', old, new - def t2_changed ( self, old, new ): + def t2_changed(self, old, new): print 't2 changed:', old, new -#------------------------------------------------------------------------------ -class Test2 ( Test1 ): +class Test2(Test1): - def anytrait_changed ( self, name, old, new ): + def anytrait_changed(self, name, old, new): print 'anytrait changed:', name, old, new -#------------------------------------------------------------------------------ -class Test3 ( TestBase ): +class Test3(TestBase): - def anytrait_changed ( self, name, old, new ): + def anytrait_changed(self, name, old, new): print 'anytrait changed:', name, old, new -#------------------------------------------------------------------------------ -class Test4 ( TestBase ): +class Test4(TestBase): - def __init__ ( self, **traits ): - TestBase.__init__( self, **traits ) - self.on_trait_change( self.on_anytrait ) + def __init__(self, **traits): + TestBase.__init__(self, **traits) + self.on_trait_change(self.on_anytrait) - def on_anytrait ( self, object, name, old, new ): + def on_anytrait(self, object, name, old, new): print 'on anytrait changed:', name, old, new -#------------------------------------------------------------------------------ -class Test5 ( TestBase ): +class Test5(TestBase): - def __init__ ( self, **traits ): - TestBase.__init__( self, **traits ) - self.on_trait_change( self.t1_trait, 't1' ) - self.on_trait_change( self.t2_trait, 't2' ) + def __init__(self, **traits): + TestBase.__init__(self, **traits) + self.on_trait_change(self.t1_trait, 't1') + self.on_trait_change(self.t2_trait, 't2') - def t1_trait ( self, object, name, old, new ): + def t1_trait(self, object, name, old, new): print 'on t1 changed:', old, new - def t2_trait ( self, object, name, old, new ): + def t2_trait(self, object, name, old, new): print 'on t2 changed:', old, new -#------------------------------------------------------------------------------ -class Test6 ( Test5 ): +class Test6(Test5): - def __init__ ( self, **traits ): - Test5.__init__( self, **traits ) - self.on_trait_change( self.on_anytrait ) + def __init__(self, **traits): + Test5.__init__(self, **traits) + self.on_trait_change(self.on_anytrait) - def on_anytrait ( self, object, name, old, new ): + def on_anytrait(self, object, name, old, new): print 'on anytrait changed:', name, old, new -#------------------------------------------------------------------------------ -class Test7 ( Test1 ): +class Test7(Test1): - def __init__ ( self, **traits ): - Test1.__init__( self, **traits ) - self.on_trait_change( self.t1_trait, 't1' ) - self.on_trait_change( self.t2_trait, 't2' ) + def __init__(self, **traits): + Test1.__init__(self, **traits) + self.on_trait_change(self.t1_trait, 't1') + self.on_trait_change(self.t2_trait, 't2') - def t1_trait ( self, object, name, old, new ): + def t1_trait(self, object, name, old, new): print 'on t1 changed:', old, new - def t2_trait ( self, object, name, old, new ): + def t2_trait(self, object, name, old, new): print 'on t2 changed:', old, new -#------------------------------------------------------------------------------ -class Test8 ( Test2 ): +class Test8(Test2): - def __init__ ( self, **traits ): - Test1.__init__( self, **traits ) - self.on_trait_change( self.t1_trait, 't1' ) - self.on_trait_change( self.t2_trait, 't2' ) - self.on_trait_change( self.on_anytrait ) + def __init__(self, **traits): + Test1.__init__(self, **traits) + self.on_trait_change(self.t1_trait, 't1') + self.on_trait_change(self.t2_trait, 't2') + self.on_trait_change(self.on_anytrait) - def on_anytrait ( self, object, name, old, new ): + def on_anytrait(self, object, name, old, new): print 'on anytrait changed:', name, old, new - def t1_trait ( self, object, name, old, new ): + def t1_trait(self, object, name, old, new): print 'on t1 changed:', old, new - def t2_trait ( self, object, name, old, new ): + def t2_trait(self, object, name, old, new): print 'on t2 changed:', old, new -#------------------------------------------------------------------------------ test1 = Test1() test1.test() diff --git a/traits/tests/test_extended_notifiers.py b/traits/tests/test_extended_notifiers.py index eb39fa329..b7cbd6db0 100644 --- a/traits/tests/test_extended_notifiers.py +++ b/traits/tests/test_extended_notifiers.py @@ -91,24 +91,33 @@ def failing_method_listener_4(self, obj, name, old, new): # 'ok' function listeners - calls_0 = [] + + def function_listener_0(): calls_0.append(True) calls_1 = [] + + def function_listener_1(new): calls_1.append(new) calls_2 = [] + + def function_listener_2(name, new): calls_2.append((name, new)) calls_3 = [] + + def function_listener_3(obj, name, new): calls_3.append((obj, name, new)) calls_4 = [] + + def function_listener_4(obj, name, old, new): calls_4.append((obj, name, old, new)) @@ -117,22 +126,27 @@ def function_listener_4(obj, name, old, new): exceptions_from = [] + def failing_function_listener_0(): exceptions_from.append(0) raise Exception('error') + def failing_function_listener_1(new): exceptions_from.append(1) raise Exception('error') + def failing_function_listener_2(name, new): exceptions_from.append(2) raise Exception('error') + def failing_function_listener_3(obj, name, new): exceptions_from.append(3) raise Exception('error') + def failing_function_listener_4(obj, name, old, new): exceptions_from.append(4) raise Exception('error') @@ -178,7 +192,7 @@ def test_extended_notifiers_methods_failing(self): obj = ExtendedNotifiers() obj.fail = 1 - _py2to3.assertCountEqual(self, [0,1,2,3,4], obj.exceptions_from) + _py2to3.assertCountEqual(self, [0, 1, 2, 3, 4], obj.exceptions_from) self.assertEqual([(obj, 'fail', 0, 1)]*5, self.exceptions) def test_extended_notifiers_functions(self): @@ -221,10 +235,10 @@ def test_extended_notifiers_functions_failing(self): obj.fail = 1 - _py2to3.assertCountEqual(self, [0,1,2,3,4], obj.exceptions_from) + _py2to3.assertCountEqual(self, [0, 1, 2, 3, 4], obj.exceptions_from) # 10 failures: 5 are from the internal extended listeners, see # test_extended_notifiers_methods_failing - self.assertEqual([(obj, 'fail', 0, 1)]*10, self.exceptions) + self.assertEqual([(obj, 'fail', 0, 1)] * 10, self.exceptions) if __name__ == '__main__': diff --git a/traits/tests/test_extended_trait_change.py b/traits/tests/test_extended_trait_change.py index 373b0e64d..e803b40d4 100644 --- a/traits/tests/test_extended_trait_change.py +++ b/traits/tests/test_extended_trait_change.py @@ -1,5 +1,3 @@ -#------------------------------------------------------------------------------- -# # Unit test case for testing HasTraits 'on_trait_change' support. # # Written by: David C. Morrill @@ -12,749 +10,747 @@ # license included in /LICENSE.txt and may be redistributed only # under the conditions described in the aforementioned license. The license # is also available online at http://www.enthought.com/licenses/BSD.txt -# -# Thanks for using Enthought open source! -# -#------------------------------------------------------------------------------- - - -#------------------------------------------------------------------------------- """ Unit test case for testing HasTraits 'on_trait_change' support. """ -#------------------------------------------------------------------------------- -# Imports: -#------------------------------------------------------------------------------- - from __future__ import absolute_import from traits.testing.unittest_tools import unittest -from nose import SkipTest - -from ..api import (Any, Dict, HasTraits, Instance, Int, List, Property, Str, - TraitDictEvent, TraitError, TraitListEvent, Undefined, cached_property, - on_trait_change, pop_exception_handler, push_exception_handler) +from ..api import (Any, Dict, HasTraits, Instance, Int, List, Property, + TraitDictEvent, TraitError, TraitListEvent, Undefined, + cached_property, on_trait_change, pop_exception_handler, + push_exception_handler) from ..trait_handlers import TraitListObject, TraitDictObject -#------------------------------------------------------------------------------- -# Test support classes: -#------------------------------------------------------------------------------- -class ArgCheckBase ( HasTraits ): +class ArgCheckBase(HasTraits): - value = Int( 0 ) - int1 = Int( 0, test = True ) - int2 = Int( 0 ) - int3 = Int( 0, test = True ) - tint1 = Int( 0 ) - tint2 = Int( 0, test = True ) - tint3 = Int( 0 ) + value = Int(0) + int1 = Int(0, test=True) + int2 = Int(0) + int3 = Int(0, test=True) + tint1 = Int(0) + tint2 = Int(0, test=True) + tint3 = Int(0) - calls = Int( 0 ) - tc = Any + calls = Int(0) + tc = Any -class ArgCheckSimple ( ArgCheckBase ): - def arg_check0 ( self ): +class ArgCheckSimple(ArgCheckBase): + + def arg_check0(self): self.calls += 1 - def arg_check1 ( self, new ): + def arg_check1(self, new): self.calls += 1 - self.tc.assertEqual( new, self.value ) + self.tc.assertEqual(new, self.value) - def arg_check2 ( self, name, new ): + def arg_check2(self, name, new): self.calls += 1 - self.tc.assertEqual( name, 'value' ) - self.tc.assertEqual( new, self.value ) + self.tc.assertEqual(name, 'value') + self.tc.assertEqual(new, self.value) - def arg_check3 ( self, object, name, new ): + def arg_check3(self, object, name, new): self.calls += 1 - self.tc.assert_( object is self ) - self.tc.assertEqual( name, 'value' ) - self.tc.assertEqual( new, self.value ) + self.tc.assert_(object is self) + self.tc.assertEqual(name, 'value') + self.tc.assertEqual(new, self.value) - def arg_check4 ( self, object, name, old, new ): + def arg_check4(self, object, name, old, new): self.calls += 1 - self.tc.assert_( object is self ) - self.tc.assertEqual( name, 'value' ) - self.tc.assertEqual( old, (self.value - 1) ) - self.tc.assertEqual( new, self.value ) + self.tc.assert_(object is self) + self.tc.assertEqual(name, 'value') + self.tc.assertEqual(old, (self.value - 1)) + self.tc.assertEqual(new, self.value) + -class ArgCheckDecorator ( ArgCheckBase ): +class ArgCheckDecorator(ArgCheckBase): - @on_trait_change( 'value' ) - def arg_check0 ( self ): + @on_trait_change('value') + def arg_check0(self): self.calls += 1 - @on_trait_change( 'value' ) - def arg_check1 ( self, new ): + @on_trait_change('value') + def arg_check1(self, new): self.calls += 1 - self.tc.assertEqual( new, self.value ) + self.tc.assertEqual(new, self.value) - @on_trait_change( 'value' ) - def arg_check2 ( self, name, new ): + @on_trait_change('value') + def arg_check2(self, name, new): self.calls += 1 - self.tc.assertEqual( name, 'value' ) - self.tc.assertEqual( new, self.value ) + self.tc.assertEqual(name, 'value') + self.tc.assertEqual(new, self.value) - @on_trait_change( 'value' ) - def arg_check3 ( self, object, name, new ): + @on_trait_change('value') + def arg_check3(self, object, name, new): self.calls += 1 - self.tc.assert_( object is self ) - self.tc.assertEqual( name, 'value' ) - self.tc.assertEqual( new, self.value ) + self.tc.assert_(object is self) + self.tc.assertEqual(name, 'value') + self.tc.assertEqual(new, self.value) - @on_trait_change( 'value' ) - def arg_check4 ( self, object, name, old, new ): + @on_trait_change('value') + def arg_check4(self, object, name, old, new): self.calls += 1 - self.tc.assert_( object is self ) - self.tc.assertEqual( name, 'value' ) - self.tc.assertEqual( old, (self.value - 1) ) - self.tc.assertEqual( new, self.value ) + self.tc.assert_(object is self) + self.tc.assertEqual(name, 'value') + self.tc.assertEqual(old, (self.value - 1)) + self.tc.assertEqual(new, self.value) -class Instance1 ( HasTraits ): - ref = Instance( ArgCheckBase, () ) +class Instance1(HasTraits): - calls = Int( 0 ) + ref = Instance(ArgCheckBase, ()) + + calls = Int(0) exp_object = Any - exp_name = Any - dst_name = Any - exp_old = Any - exp_new = Any - dst_new = Any - tc = Any + exp_name = Any + dst_name = Any + exp_old = Any + exp_new = Any + dst_new = Any + tc = Any - @on_trait_change( 'ref.value' ) - def arg_check0 ( self ): + @on_trait_change('ref.value') + def arg_check0(self): self.calls += 1 - @on_trait_change( 'ref.value' ) - def arg_check1 ( self, new ): + @on_trait_change('ref.value') + def arg_check1(self, new): self.calls += 1 - self.tc.assertEqual( new, self.dst_new ) + self.tc.assertEqual(new, self.dst_new) - @on_trait_change( 'ref.value' ) - def arg_check2 ( self, name, new ): + @on_trait_change('ref.value') + def arg_check2(self, name, new): self.calls += 1 - self.tc.assertEqual( name, self.dst_name ) - self.tc.assertEqual( new, self.dst_new ) + self.tc.assertEqual(name, self.dst_name) + self.tc.assertEqual(new, self.dst_new) - @on_trait_change( 'ref.value' ) - def arg_check3 ( self, object, name, new ): + @on_trait_change('ref.value') + def arg_check3(self, object, name, new): self.calls += 1 - self.tc.assert_( object is self.exp_object ) - self.tc.assertEqual( name, self.exp_name ) - self.tc.assertEqual( new, self.exp_new ) + self.tc.assert_(object is self.exp_object) + self.tc.assertEqual(name, self.exp_name) + self.tc.assertEqual(new, self.exp_new) - @on_trait_change( 'ref.value' ) - def arg_check4 ( self, object, name, old, new ): + @on_trait_change('ref.value') + def arg_check4(self, object, name, old, new): self.calls += 1 - self.tc.assert_( object is self.exp_object ) - self.tc.assertEqual( name, self.exp_name ) - self.tc.assertEqual( old, self.exp_old ) - self.tc.assertEqual( new, self.exp_new ) + self.tc.assert_(object is self.exp_object) + self.tc.assertEqual(name, self.exp_name) + self.tc.assertEqual(old, self.exp_old) + self.tc.assertEqual(new, self.exp_new) + -class List1 ( HasTraits ): +class List1(HasTraits): - refs = List( ArgCheckBase ) - calls = Int( 0 ) + refs = List(ArgCheckBase) + calls = Int(0) exp_object = Any - exp_name = Any - type_old = Any - exp_old = Any - type_new = Any - exp_new = Any - tc = Any + exp_name = Any + type_old = Any + exp_old = Any + type_new = Any + exp_new = Any + tc = Any - @on_trait_change( 'refs.value' ) - def arg_check0 ( self ): + @on_trait_change('refs.value') + def arg_check0(self): self.calls += 1 - @on_trait_change( 'refs.value' ) - def arg_check3 ( self, object, name, new ): + @on_trait_change('refs.value') + def arg_check3(self, object, name, new): self.calls += 1 - self.tc.assert_( object is self.exp_object ) - self.tc.assertEqual( name, self.exp_name ) + self.tc.assert_(object is self.exp_object) + self.tc.assertEqual(name, self.exp_name) if self.type_new is None: - self.tc.assertEqual( new, self.exp_new ) + self.tc.assertEqual(new, self.exp_new) else: - self.tc.assert_( isinstance( new, self.type_new ) ) + self.tc.assert_(isinstance(new, self.type_new)) - @on_trait_change( 'refs.value' ) - def arg_check4 ( self, object, name, old, new ): + @on_trait_change('refs.value') + def arg_check4(self, object, name, old, new): self.calls += 1 - self.tc.assert_( object is self.exp_object ) - self.tc.assertEqual( name, self.exp_name ) + self.tc.assert_(object is self.exp_object) + self.tc.assertEqual(name, self.exp_name) if self.type_old is None: - self.tc.assertEqual( old, self.exp_old ) + self.tc.assertEqual(old, self.exp_old) else: - self.tc.assert_( isinstance( old, self.type_old ) ) + self.tc.assert_(isinstance(old, self.type_old)) if self.type_new is None: - self.tc.assertEqual( new, self.exp_new ) + self.tc.assertEqual(new, self.exp_new) else: - self.tc.assert_( isinstance( new, self.type_new ) ) + self.tc.assert_(isinstance(new, self.type_new)) + -class List2 ( HasTraits ): +class List2(HasTraits): - refs = List( ArgCheckBase ) + refs = List(ArgCheckBase) - calls = Int( 0 ) + calls = Int(0) exp_new = Any - tc = Any + tc = Any - @on_trait_change( 'refs.value' ) - def arg_check1 ( self, new ): + @on_trait_change('refs.value') + def arg_check1(self, new): self.calls += 1 - self.tc.assertEqual( new, self.exp_new ) + self.tc.assertEqual(new, self.exp_new) -class List3 ( HasTraits ): - refs = List( ArgCheckBase ) +class List3(HasTraits): - calls = Int( 0 ) + refs = List(ArgCheckBase) + + calls = Int(0) exp_name = Any - exp_new = Any - tc = Any + exp_new = Any + tc = Any - @on_trait_change( 'refs.value' ) - def arg_check2 ( self, name, new ): + @on_trait_change('refs.value') + def arg_check2(self, name, new): self.calls += 1 - self.tc.assertEqual( name, self.exp_name ) - self.tc.assertEqual( new, self.exp_new ) + self.tc.assertEqual(name, self.exp_name) + self.tc.assertEqual(new, self.exp_new) + -class Dict1 ( List1 ): +class Dict1(List1): + refs = Dict(Int, ArgCheckBase) - refs = Dict( Int, ArgCheckBase ) -class Dict2 ( HasTraits ): +class Dict2(HasTraits): - refs = Dict( Int, ArgCheckBase ) + refs = Dict(Int, ArgCheckBase) - calls = Int( 0 ) + calls = Int(0) exp_new = Any - tc = Any + tc = Any - @on_trait_change( 'refs.value' ) - def arg_check1 ( self, new ): + @on_trait_change('refs.value') + def arg_check1(self, new): self.calls += 1 - self.tc.assertEqual( new, self.exp_new ) + self.tc.assertEqual(new, self.exp_new) -class Dict3 ( HasTraits ): - refs = Dict( Int, ArgCheckBase ) +class Dict3(HasTraits): - calls = Int( 0 ) + refs = Dict(Int, ArgCheckBase) + + calls = Int(0) exp_name = Any - exp_new = Any - tc = Any + exp_new = Any + tc = Any - @on_trait_change( 'refs.value' ) - def arg_check2 ( self, name, new ): + @on_trait_change('refs.value') + def arg_check2(self, name, new): self.calls += 1 - self.tc.assertEqual( name, self.exp_name ) - self.tc.assertEqual( new, self.exp_new ) + self.tc.assertEqual(name, self.exp_name) + self.tc.assertEqual(new, self.exp_new) -class Complex ( HasTraits ): - int1 = Int( 0, test = True ) - int2 = Int( 0 ) - int3 = Int( 0, test = True ) - tint1 = Int( 0 ) - tint2 = Int( 0, test = True ) - tint3 = Int( 0 ) - ref = Instance( ArgCheckBase, () ) +class Complex(HasTraits): - calls = Int( 0 ) + int1 = Int(0, test=True) + int2 = Int(0) + int3 = Int(0, test=True) + tint1 = Int(0) + tint2 = Int(0, test=True) + tint3 = Int(0) + ref = Instance(ArgCheckBase, ()) + + calls = Int(0) exp_object = Any - exp_name = Any - dst_name = Any - exp_old = Any - exp_new = Any - dst_new = Any - tc = Any + exp_name = Any + dst_name = Any + exp_old = Any + exp_new = Any + dst_new = Any + tc = Any - def arg_check0 ( self ): + def arg_check0(self): self.calls += 1 - def arg_check1 ( self, new ): + def arg_check1(self, new): self.calls += 1 - self.tc.assertEqual( new, self.exp_new ) + self.tc.assertEqual(new, self.exp_new) - def arg_check2 ( self, name, new ): + def arg_check2(self, name, new): self.calls += 1 - self.tc.assertEqual( name, self.exp_name ) - self.tc.assertEqual( new, self.exp_new ) + self.tc.assertEqual(name, self.exp_name) + self.tc.assertEqual(new, self.exp_new) - def arg_check3 ( self, object, name, new ): + def arg_check3(self, object, name, new): self.calls += 1 - self.tc.assert_( object is self.exp_object ) - self.tc.assertEqual( name, self.exp_name ) - self.tc.assertEqual( new, self.exp_new ) + self.tc.assert_(object is self.exp_object) + self.tc.assertEqual(name, self.exp_name) + self.tc.assertEqual(new, self.exp_new) - def arg_check4 ( self, object, name, old, new ): + def arg_check4(self, object, name, old, new): self.calls += 1 - self.tc.assert_( object is self.exp_object ) - self.tc.assertEqual( name, self.exp_name ) - self.tc.assertEqual( old, self.exp_old ) - self.tc.assertEqual( new, self.exp_new ) + self.tc.assert_(object is self.exp_object) + self.tc.assertEqual(name, self.exp_name) + self.tc.assertEqual(old, self.exp_old) + self.tc.assertEqual(new, self.exp_new) -class Link ( HasTraits ): - next = Any - prev = Any - value = Int( 0 ) +class Link(HasTraits): -class LinkTest ( HasTraits ): + next = Any + prev = Any + value = Int(0) - head = Instance( Link ) - calls = Int( 0 ) +class LinkTest(HasTraits): + + head = Instance(Link) + + calls = Int(0) exp_object = Any - exp_name = Any - dst_name = Any - exp_old = Any - exp_new = Any - dst_new = Any - tc = Any + exp_name = Any + dst_name = Any + exp_old = Any + exp_new = Any + dst_new = Any + tc = Any - def arg_check0 ( self ): + def arg_check0(self): self.calls += 1 - def arg_check1 ( self, new ): + def arg_check1(self, new): self.calls += 1 - self.tc.assertEqual( new, self.exp_new ) + self.tc.assertEqual(new, self.exp_new) - def arg_check2 ( self, name, new ): + def arg_check2(self, name, new): self.calls += 1 - self.tc.assertEqual( name, self.exp_name ) - self.tc.assertEqual( new, self.exp_new ) + self.tc.assertEqual(name, self.exp_name) + self.tc.assertEqual(new, self.exp_new) - def arg_check3 ( self, object, name, new ): + def arg_check3(self, object, name, new): self.calls += 1 - self.tc.assert_( object is self.exp_object ) - self.tc.assertEqual( name, self.exp_name ) - self.tc.assertEqual( new, self.exp_new ) + self.tc.assert_(object is self.exp_object) + self.tc.assertEqual(name, self.exp_name) + self.tc.assertEqual(new, self.exp_new) - def arg_check4 ( self, object, name, old, new ): + def arg_check4(self, object, name, old, new): self.calls += 1 - self.tc.assert_( object is self.exp_object ) - self.tc.assertEqual( name, self.exp_name ) - self.tc.assertEqual( old, self.exp_old ) - self.tc.assertEqual( new, self.exp_new ) + self.tc.assert_(object is self.exp_object) + self.tc.assertEqual(name, self.exp_name) + self.tc.assertEqual(old, self.exp_old) + self.tc.assertEqual(new, self.exp_new) + -class PropertyDependsOn ( HasTraits ): +class PropertyDependsOn(HasTraits): - sum = Property( depends_on = 'ref.[int1,int2,int3]' ) - ref = Instance( ArgCheckBase, () ) + sum = Property(depends_on='ref.[int1,int2,int3]') + ref = Instance(ArgCheckBase, ()) - pcalls = Int( 0 ) - calls = Int( 0 ) + pcalls = Int(0) + calls = Int(0) exp_old = Any exp_new = Any - tc = Any + tc = Any @cached_property - def _get_sum ( self ): + def _get_sum(self): self.pcalls += 1 r = self.ref return (r.int1 + r.int2 + r.int3) - def _sum_changed ( self, old, new ): + def _sum_changed(self, old, new): self.calls += 1 - self.tc.assertEqual( old, self.exp_old ) - self.tc.assertEqual( new, self.exp_new ) + self.tc.assertEqual(old, self.exp_old) + self.tc.assertEqual(new, self.exp_new) -#------------------------------------------------------------------------------- -# 'OnTraitChangeTest' unit test class: -#------------------------------------------------------------------------------- -class OnTraitChangeTest ( unittest.TestCase ): +class OnTraitChangeTest(unittest.TestCase): def setUp(self): - def ignore ( *args ): + def ignore(*args): pass push_exception_handler(handler=ignore, reraise_exceptions=True) def tearDown(self): pop_exception_handler() - #-- Unit Test Methods ------------------------------------------------------ - - def test_arg_check_simple ( self ): - ac = ArgCheckSimple( tc = self ) - ac.on_trait_change( ac.arg_check0, 'value' ) - ac.on_trait_change( ac.arg_check1, 'value' ) - ac.on_trait_change( ac.arg_check2, 'value' ) - ac.on_trait_change( ac.arg_check3, 'value' ) - ac.on_trait_change( ac.arg_check4, 'value' ) - for i in range( 3 ): + def test_arg_check_simple(self): + ac = ArgCheckSimple(tc=self) + ac.on_trait_change(ac.arg_check0, 'value') + ac.on_trait_change(ac.arg_check1, 'value') + ac.on_trait_change(ac.arg_check2, 'value') + ac.on_trait_change(ac.arg_check3, 'value') + ac.on_trait_change(ac.arg_check4, 'value') + for i in range(3): ac.value += 1 - self.assert_( ac.calls == (3 * 5) ) - ac.on_trait_change( ac.arg_check0, 'value', remove = True ) - ac.on_trait_change( ac.arg_check1, 'value', remove = True ) - ac.on_trait_change( ac.arg_check2, 'value', remove = True ) - ac.on_trait_change( ac.arg_check3, 'value', remove = True ) - ac.on_trait_change( ac.arg_check4, 'value', remove = True ) - for i in range( 3 ): + self.assert_(ac.calls == (3 * 5)) + ac.on_trait_change(ac.arg_check0, 'value', remove=True) + ac.on_trait_change(ac.arg_check1, 'value', remove=True) + ac.on_trait_change(ac.arg_check2, 'value', remove=True) + ac.on_trait_change(ac.arg_check3, 'value', remove=True) + ac.on_trait_change(ac.arg_check4, 'value', remove=True) + for i in range(3): ac.value += 1 - self.assertEqual( ac.calls, (3 * 5) ) - self.assertEqual( ac.value, (2 * 3) ) + self.assertEqual(ac.calls, (3 * 5)) + self.assertEqual(ac.value, (2 * 3)) - def test_arg_check_decorator ( self ): - ac = ArgCheckDecorator( tc = self ) - for i in range( 3 ): + def test_arg_check_decorator(self): + ac = ArgCheckDecorator(tc=self) + for i in range(3): ac.value += 1 - self.assertEqual( ac.calls, (3 * 5) ) - self.assertEqual( ac.value, 3 ) - - def test_instance1 ( self ): - i1 = Instance1( tc = self ) - for i in range( 3 ): - i1.set( exp_object = i1.ref, exp_name = 'value', dst_name = 'value', - exp_old = i, exp_new = (i + 1), dst_new = (i + 1) ) + self.assertEqual(ac.calls, (3 * 5)) + self.assertEqual(ac.value, 3) + + def test_instance1(self): + i1 = Instance1(tc=self) + for i in range(3): + i1.set(exp_object=i1.ref, exp_name='value', dst_name='value', + exp_old=i, exp_new=(i + 1), dst_new=(i + 1)) i1.ref.value = (i + 1) - self.assertEqual( i1.calls, (3 * 5) ) - self.assertEqual( i1.ref.value, 3 ) + self.assertEqual(i1.calls, (3 * 5)) + self.assertEqual(i1.ref.value, 3) ref = ArgCheckBase() - i1.set( exp_object = i1, exp_name = 'ref', dst_name = 'value', - exp_old = i1.ref, exp_new = ref, dst_new = 0 ) + i1.set(exp_object=i1, exp_name='ref', dst_name='value', + exp_old=i1.ref, exp_new=ref, dst_new=0) i1.ref = ref - self.assertEqual( i1.calls, (4 * 5) ) - self.assertEqual( i1.ref.value, 0 ) - for i in range( 3 ): - i1.set( exp_object = i1.ref, exp_name = 'value', dst_name = 'value', - exp_old = i, exp_new = (i + 1), dst_new = (i + 1) ) + self.assertEqual(i1.calls, (4 * 5)) + self.assertEqual(i1.ref.value, 0) + for i in range(3): + i1.set(exp_object=i1.ref, exp_name='value', dst_name='value', + exp_old=i, exp_new=(i + 1), dst_new=(i + 1)) i1.ref.value = (i + 1) - self.assertEqual( i1.calls, (7 * 5) ) - self.assertEqual( i1.ref.value, 3 ) + self.assertEqual(i1.calls, (7 * 5)) + self.assertEqual(i1.ref.value, 3) - def test_list1 ( self ): - l1 = List1( tc = self ) - for i in range( 3 ): + def test_list1(self): + l1 = List1(tc=self) + for i in range(3): ac = ArgCheckBase() - l1.set( exp_object = l1, exp_name = 'refs_items', type_old = None, - exp_old = Undefined, type_new = TraitListEvent ) - l1.refs.append( ac ) - #self.assertEqual( l1.calls, (3 * 3) ) # FIXME - for i in range( 3 ): - self.assertEqual( l1.refs[i].value, 0 ) - refs = [ ArgCheckBase(), ArgCheckBase(), ArgCheckBase() ] - l1.set( exp_object = l1, exp_name = 'refs', type_old = None, - exp_old = l1.refs, type_new = TraitListObject ) + l1.set(exp_object=l1, exp_name='refs_items', type_old=None, + exp_old=Undefined, type_new=TraitListEvent) + l1.refs.append(ac) + #self.assertEqual(l1.calls, (3 * 3)) # FIXME + for i in range(3): + self.assertEqual(l1.refs[i].value, 0) + refs = [ArgCheckBase(), ArgCheckBase(), ArgCheckBase()] + l1.set(exp_object=l1, exp_name='refs', type_old=None, + exp_old=l1.refs, type_new=TraitListObject) l1.refs = refs - #self.assertEqual( l1.calls, (4 * 3) ) - for i in range( 3 ): - self.assertEqual( l1.refs[i].value, 0 ) - for i in range( 3 ): - for j in range( 3 ): - l1.set( exp_object = l1.refs[j], exp_name = 'value', - type_old = None, exp_old = i, - type_new = None, exp_new = (i + 1) ) + #self.assertEqual(l1.calls, (4 * 3)) + for i in range(3): + self.assertEqual(l1.refs[i].value, 0) + for i in range(3): + for j in range(3): + l1.set(exp_object=l1.refs[j], exp_name='value', + type_old=None, exp_old=i, + type_new=None, exp_new=(i + 1)) l1.refs[j].value = (i + 1) - #self.assertEqual( l1.calls, (13 * 3) ) - for i in range( 3 ): - self.assertEqual( l1.refs[i].value, 3 ) + #self.assertEqual(l1.calls, (13 * 3)) + for i in range(3): + self.assertEqual(l1.refs[i].value, 3) - def test_list2 ( self ): - self.check_list( List2( tc = self ) ) + def test_list2(self): + self.check_list(List2(tc=self)) - def test_list3 ( self ): - self.check_list( List3( tc = self ) ) + def test_list3(self): + self.check_list(List3(tc=self)) - def test_dict1 ( self ): - d1 = Dict1( tc = self ) - for i in range( 3 ): + def test_dict1(self): + d1 = Dict1(tc=self) + for i in range(3): ac = ArgCheckBase() - d1.set( exp_object = d1, exp_name = 'refs_items', type_old = None, - exp_old = Undefined, type_new = TraitDictEvent ) + d1.set(exp_object=d1, exp_name='refs_items', type_old=None, + exp_old=Undefined, type_new=TraitDictEvent) d1.refs[i] = ac - #self.assertEqual( d1.calls, (3 * 3) ) # FIXME - for i in range( 3 ): - self.assertEqual( d1.refs[i].value, 0 ) - refs = { 0: ArgCheckBase(), 1: ArgCheckBase(), 2: ArgCheckBase() } - d1.set( exp_object = d1, exp_name = 'refs', type_old = None, - exp_old = d1.refs, type_new = TraitDictObject ) + #self.assertEqual(d1.calls, (3 * 3)) # FIXME + for i in range(3): + self.assertEqual(d1.refs[i].value, 0) + refs = {0: ArgCheckBase(), 1: ArgCheckBase(), 2: ArgCheckBase()} + d1.set(exp_object=d1, exp_name='refs', type_old=None, + exp_old=d1.refs, type_new=TraitDictObject) d1.refs = refs - #self.assertEqual( d1.calls, (4 * 3) ) - for i in range( 3 ): - self.assertEqual( d1.refs[i].value, 0 ) - for i in range( 3 ): - for j in range( 3 ): - d1.set( exp_object = d1.refs[j], exp_name = 'value', - type_old = None, exp_old = i, - type_new = None, exp_new = (i + 1) ) + #self.assertEqual(d1.calls, (4 * 3)) + for i in range(3): + self.assertEqual(d1.refs[i].value, 0) + for i in range(3): + for j in range(3): + d1.set(exp_object=d1.refs[j], exp_name='value', + type_old=None, exp_old=i, + type_new=None, exp_new=(i + 1)) d1.refs[j].value = (i + 1) - #self.assertEqual( d1.calls, (13 * 3) ) - for i in range( 3 ): - self.assertEqual( d1.refs[i].value, 3 ) - - def test_dict2 ( self ): - self.check_dict( Dict2( tc = self ) ) - - def test_dict3 ( self ): - self.check_dict( Dict3( tc = self ) ) - - def test_pattern_list1 ( self ): - c = Complex( tc = self ) - self.check_complex( c, c, 'int1, int2, int3', - [ 'int1', 'int2', 'int3' ], [ 'tint1', 'tint2', 'tint3' ] ) - - def test_pattern_list2 ( self ): - c = Complex( tc = self ) - self.check_complex( c, c, [ 'int1', 'int2', 'int3' ], - [ 'int1', 'int2', 'int3' ], [ 'tint1', 'tint2', 'tint3' ] ) - - def test_pattern_list3 ( self ): - c = Complex( tc = self ) - self.check_complex( c, c.ref, 'ref.[int1, int2, int3]', - [ 'int1', 'int2', 'int3' ], [ 'tint1', 'tint2', 'tint3' ] ) - - def test_pattern_list4 ( self ): - c = Complex( tc = self ) - handlers = [ c.arg_check0, c.arg_check3, c.arg_check4 ] - n = len( handlers ) - pattern = 'ref.[int1,int2,int3]' - self.multi_register( c, handlers, pattern ) + #self.assertEqual(d1.calls, (13 * 3)) + for i in range(3): + self.assertEqual(d1.refs[i].value, 3) + + def test_dict2(self): + self.check_dict(Dict2(tc=self)) + + def test_dict3(self): + self.check_dict(Dict3(tc=self)) + + def test_pattern_list1(self): + c = Complex(tc=self) + self.check_complex(c, c, 'int1, int2, int3', + ['int1', 'int2', 'int3'], + ['tint1', 'tint2', 'tint3']) + + def test_pattern_list2(self): + c = Complex(tc=self) + self.check_complex(c, c, ['int1', 'int2', 'int3'], + ['int1', 'int2', 'int3'], + ['tint1', 'tint2', 'tint3']) + + def test_pattern_list3(self): + c = Complex(tc=self) + self.check_complex(c, c.ref, 'ref.[int1, int2, int3]', + ['int1', 'int2', 'int3'], + ['tint1', 'tint2', 'tint3']) + + def test_pattern_list4(self): + c = Complex(tc=self) + handlers = [c.arg_check0, c.arg_check3, c.arg_check4] + n = len(handlers) + pattern = 'ref.[int1,int2,int3]' + self.multi_register(c, handlers, pattern) r0 = c.ref r1 = ArgCheckBase() - c.set( exp_object = c, exp_name = 'ref', exp_old = r0, exp_new = r1 ) + c.set(exp_object=c, exp_name='ref', exp_old=r0, exp_new=r1) c.ref = r1 - c.set( exp_old = r1, exp_new = r0 ) + c.set(exp_old=r1, exp_new=r0) c.ref = r0 - self.assertEqual( c.calls, 2 * n ) - self.multi_register( c, handlers, pattern, remove = True ) + self.assertEqual(c.calls, 2 * n) + self.multi_register(c, handlers, pattern, remove=True) c.ref = r1 c.ref = r0 - self.assertEqual( c.calls, 2 * n ) - - def test_pattern_list5 ( self ): - c = Complex( tc = self ) - c.on_trait_change( c.arg_check1, 'ref.[int1,int2,int3]' ) - self.assertRaises( TraitError, c.set, ref = ArgCheckBase() ) - - def test_pattern_list6 ( self ): - c = Complex( tc = self ) - c.on_trait_change( c.arg_check2, 'ref.[int1,int2,int3]' ) - self.assertRaises( TraitError, c.set, ref = ArgCheckBase() ) - - def test_pattern_list7 ( self ): - c = Complex( tc = self ) - self.check_complex( c, c, '+test', [ 'int1', 'int3', 'tint2' ], - [ 'int2', 'tint1', 'tint3' ] ) - - def test_pattern_list8 ( self ): - c = Complex( tc = self ) - self.check_complex( c, c, 'int+test', - [ 'int1', 'int3' ], [ 'int2', 'tint1', 'tint2', 'tint3' ] ) - - def test_pattern_list9 ( self ): - c = Complex( tc = self ) - self.check_complex( c, c, 'int-test', [ 'int2' ], - [ 'int1', 'int3', 'tint4', 'tint5', 'tint6' ] ) - - def test_pattern_list10 ( self ): - c = Complex( tc = self ) - self.check_complex( c, c, 'int+', - [ 'int1', 'int2', 'int3' ], [ 'tint1', 'tint2', 'tint3' ] ) - - def test_pattern_list11 ( self ): - c = Complex( tc = self ) - self.check_complex( c, c, 'int-', - [ 'int1', 'int2', 'int3' ], [ 'tint1', 'tint2', 'tint3' ] ) - - def test_pattern_list12 ( self ): - c = Complex( tc = self ) - self.check_complex( c, c, 'int+test,tint-test', - [ 'int1', 'int3', 'tint1', 'tint3' ], [ 'int2', 'tint2' ] ) - - def test_pattern_list13 ( self ): - c = Complex( tc = self ) - self.check_complex( c, c.ref, 'ref.[int+test,tint-test]', - [ 'int1', 'int3', 'tint1', 'tint3' ], [ 'int2', 'tint2' ] ) - - def test_cycle1 ( self ): - lt = LinkTest( tc = self, head = self.build_list() ) - handlers = [ lt.arg_check0, lt.arg_check1, lt.arg_check2, lt.arg_check3, - lt.arg_check4 ] - nh = len( handlers ) - self.multi_register( lt, handlers, 'head.next*.value' ) + self.assertEqual(c.calls, 2 * n) + + def test_pattern_list5(self): + c = Complex(tc=self) + c.on_trait_change(c.arg_check1, 'ref.[int1,int2,int3]') + self.assertRaises(TraitError, c.set, ref=ArgCheckBase()) + + def test_pattern_list6(self): + c = Complex(tc=self) + c.on_trait_change(c.arg_check2, 'ref.[int1,int2,int3]') + self.assertRaises(TraitError, c.set, ref=ArgCheckBase()) + + def test_pattern_list7(self): + c = Complex(tc=self) + self.check_complex(c, c, '+test', ['int1', 'int3', 'tint2'], + ['int2', 'tint1', 'tint3']) + + def test_pattern_list8(self): + c = Complex(tc=self) + self.check_complex(c, c, 'int+test', + ['int1', 'int3'], + ['int2', 'tint1', 'tint2', 'tint3']) + + def test_pattern_list9(self): + c = Complex(tc=self) + self.check_complex(c, c, 'int-test', ['int2'], + ['int1', 'int3', 'tint4', 'tint5', 'tint6']) + + def test_pattern_list10(self): + c = Complex(tc=self) + self.check_complex(c, c, 'int+', + ['int1', 'int2', 'int3'], + ['tint1', 'tint2', 'tint3']) + + def test_pattern_list11(self): + c = Complex(tc=self) + self.check_complex(c, c, 'int-', + ['int1', 'int2', 'int3'], + ['tint1', 'tint2', 'tint3']) + + def test_pattern_list12(self): + c = Complex(tc=self) + self.check_complex(c, c, 'int+test,tint-test', + ['int1', 'int3', 'tint1', 'tint3'], + ['int2', 'tint2']) + + def test_pattern_list13(self): + c = Complex(tc=self) + self.check_complex(c, c.ref, 'ref.[int+test,tint-test]', + ['int1', 'int3', 'tint1', 'tint3'], + ['int2', 'tint2']) + + def test_cycle1(self): + lt = LinkTest(tc=self, head=self.build_list()) + handlers = [lt.arg_check0, lt.arg_check1, lt.arg_check2, lt.arg_check3, + lt.arg_check4] + nh = len(handlers) + self.multi_register(lt, handlers, 'head.next*.value') cur = lt.head - for i in range( 4 ): - lt.set( exp_object = cur, exp_name = 'value', exp_old = 10 * i, - exp_new = (10 * i) + 1 ) + for i in range(4): + lt.set(exp_object=cur, exp_name='value', exp_old=10 * i, + exp_new=(10 * i) + 1) cur.value = (10 * i) + 1 cur = cur.next - self.assertEqual( lt.calls, 4 * nh ) - self.multi_register( lt, handlers, 'head.next*.value', remove = True ) + self.assertEqual(lt.calls, 4 * nh) + self.multi_register(lt, handlers, 'head.next*.value', remove=True) cur = lt.head - for i in range( 4 ): + for i in range(4): cur.value = (10 * i) + 2 cur = cur.next - self.assertEqual( lt.calls, 4 * nh ) - - def test_cycle2 ( self ): - lt = LinkTest( tc = self, head = self.build_list() ) - handlers = [ lt.arg_check0, lt.arg_check1, lt.arg_check2, lt.arg_check3, - lt.arg_check4 ] - nh = len( handlers ) - self.multi_register( lt, handlers, 'head.[next,prev]*.value' ) + self.assertEqual(lt.calls, 4 * nh) + + def test_cycle2(self): + lt = LinkTest(tc=self, head=self.build_list()) + handlers = [lt.arg_check0, lt.arg_check1, lt.arg_check2, lt.arg_check3, + lt.arg_check4] + nh = len(handlers) + self.multi_register(lt, handlers, 'head.[next,prev]*.value') cur = lt.head - for i in range( 4 ): - lt.set( exp_object = cur, exp_name = 'value', exp_old = 10 * i, - exp_new = (10 * i) + 1 ) + for i in range(4): + lt.set(exp_object=cur, exp_name='value', exp_old=10 * i, + exp_new=(10 * i) + 1) cur.value = (10 * i) + 1 cur = cur.next - self.assertEqual( lt.calls, 4 * nh ) - self.multi_register( lt, handlers, 'head.[next,prev]*.value', remove = True ) + self.assertEqual(lt.calls, 4 * nh) + self.multi_register(lt, handlers, 'head.[next,prev]*.value', + remove=True) cur = lt.head - for i in range( 4 ): + for i in range(4): cur.value = (10 * i) + 2 cur = cur.next - self.assertEqual( lt.calls, 4 * nh ) - - def test_cycle3 ( self ): - lt = LinkTest( tc = self, head = self.build_list() ) - handlers = [ lt.arg_check0, lt.arg_check3, lt.arg_check4 ] - nh = len( handlers ) - self.multi_register( lt, handlers, 'head.next*.value' ) - link = self.new_link( lt, lt.head, 1 ) - self.assertEqual( lt.calls, nh ) - link = self.new_link( lt, link, 2 ) - self.assertEqual( lt.calls, 2 * nh ) - self.multi_register( lt, handlers, 'head.next*.value', remove = True ) - link = self.new_link( lt, link, 3 ) - self.assertEqual( lt.calls, 2 * nh ) - - def test_property ( self ): - pdo = PropertyDependsOn( tc = self ) + self.assertEqual(lt.calls, 4 * nh) + + def test_cycle3(self): + lt = LinkTest(tc=self, head=self.build_list()) + handlers = [lt.arg_check0, lt.arg_check3, lt.arg_check4] + nh = len(handlers) + self.multi_register(lt, handlers, 'head.next*.value') + link = self.new_link(lt, lt.head, 1) + self.assertEqual(lt.calls, nh) + link = self.new_link(lt, link, 2) + self.assertEqual(lt.calls, 2 * nh) + self.multi_register(lt, handlers, 'head.next*.value', remove=True) + link = self.new_link(lt, link, 3) + self.assertEqual(lt.calls, 2 * nh) + + def test_property(self): + pdo = PropertyDependsOn(tc=self) sum = pdo.sum - self.assertEqual( sum, 0 ) - for n in [ 'int1', 'int2', 'int3' ]: - for i in range( 3 ): - pdo.set( exp_old = sum, exp_new = sum + 1 ) - setattr( pdo.ref, n, i + 1 ) + self.assertEqual(sum, 0) + for n in ['int1', 'int2', 'int3']: + for i in range(3): + pdo.set(exp_old=sum, exp_new=sum + 1) + setattr(pdo.ref, n, i + 1) sum += 1 - self.assertEqual( pdo.pcalls, (3 * 3) + 1 ) - self.assertEqual( pdo.calls, 3 * 3 ) - for i in range( 10 ): + self.assertEqual(pdo.pcalls, (3 * 3) + 1) + self.assertEqual(pdo.calls, 3 * 3) + for i in range(10): x = pdo.sum - self.assertEqual( pdo.pcalls, (3 * 3) + 1 ) - pdo.set( exp_old = sum, exp_new = 60 ) + self.assertEqual(pdo.pcalls, (3 * 3) + 1) + pdo.set(exp_old=sum, exp_new=60) old_ref = pdo.ref - pdo.ref = ArgCheckBase( int1 = 10, int2 = 20, int3 = 30 ) - self.assertEqual( pdo.pcalls, (3 * 3) + 2 ) - self.assertEqual( pdo.calls, (3 * 3) + 1 ) + pdo.ref = ArgCheckBase(int1=10, int2=20, int3=30) + self.assertEqual(pdo.pcalls, (3 * 3) + 2) + self.assertEqual(pdo.calls, (3 * 3) + 1) sum = 60 - for n in [ 'int1', 'int2', 'int3' ]: - for i in range( 3 ): - pdo.set( exp_old = sum, exp_new = sum + 1 ) - setattr( pdo.ref, n, getattr( pdo.ref, n ) + 1 ) + for n in ['int1', 'int2', 'int3']: + for i in range(3): + pdo.set(exp_old=sum, exp_new=sum + 1) + setattr(pdo.ref, n, getattr(pdo.ref, n) + 1) sum += 1 - self.assertEqual( pdo.pcalls, (2 * 3 * 3) + 2 ) - self.assertEqual( pdo.calls, (2 * 3 * 3) + 1 ) - for n in [ 'int1', 'int2', 'int3' ]: - for i in range( 3 ): - setattr( old_ref, n, getattr( old_ref, n ) + 1 ) - self.assertEqual( pdo.pcalls, (2 * 3 * 3) + 2 ) - self.assertEqual( pdo.calls, (2 * 3 * 3) + 1 ) - self.assertEqual( pdo.sum, sum ) - self.assertEqual( pdo.pcalls, (2 * 3 * 3) + 2 ) - - #-- Helper methods --------------------------------------------------------- - - def check_list ( self, l ): - for i in range( 3 ): + self.assertEqual(pdo.pcalls, (2 * 3 * 3) + 2) + self.assertEqual(pdo.calls, (2 * 3 * 3) + 1) + for n in ['int1', 'int2', 'int3']: + for i in range(3): + setattr(old_ref, n, getattr(old_ref, n) + 1) + self.assertEqual(pdo.pcalls, (2 * 3 * 3) + 2) + self.assertEqual(pdo.calls, (2 * 3 * 3) + 1) + self.assertEqual(pdo.sum, sum) + self.assertEqual(pdo.pcalls, (2 * 3 * 3) + 2) + + def check_list(self, l): + for i in range(3): ac = ArgCheckBase() - self.assertRaises( TraitError, l.refs.append, ac) - self.assertEqual( l.calls, 0 ) - for i in range( 3 ): - self.assertEqual( l.refs[i].value, 0 ) - refs = [ ArgCheckBase(), ArgCheckBase(), ArgCheckBase() ] - self.assertRaises( TraitError, l.set, refs = refs ) - self.assertEqual( l.calls, 0 ) - for i in range( 3 ): - self.assertEqual( l.refs[i].value, 0 ) - for i in range( 3 ): - for j in range( 3 ): + self.assertRaises(TraitError, l.refs.append, ac) + self.assertEqual(l.calls, 0) + for i in range(3): + self.assertEqual(l.refs[i].value, 0) + refs = [ArgCheckBase(), ArgCheckBase(), ArgCheckBase()] + self.assertRaises(TraitError, l.set, refs=refs) + self.assertEqual(l.calls, 0) + for i in range(3): + self.assertEqual(l.refs[i].value, 0) + for i in range(3): + for j in range(3): l.exp_new = (i + 1) l.refs[j].value = (i + 1) - self.assertEqual( l.calls, 0 ) - for i in range( 3 ): - self.assertEqual( l.refs[i].value, 3 ) + self.assertEqual(l.calls, 0) + for i in range(3): + self.assertEqual(l.refs[i].value, 3) - def check_dict ( self, d ): - for i in range( 3 ): + def check_dict(self, d): + for i in range(3): ac = ArgCheckBase() - self.assertRaises( TraitError, d.refs.setdefault, i, ac ) - self.assertEqual( d.calls, 0 ) - for i in range( 3 ): - self.assertEqual( d.refs[i].value, 0 ) - refs = { 0: ArgCheckBase(), 1: ArgCheckBase(), 2: ArgCheckBase() } - self.assertRaises( TraitError, d.set, refs = refs ) - self.assertEqual( d.calls, 0 ) - for i in range( 3 ): - self.assertEqual( d.refs[i].value, 0 ) - for i in range( 3 ): - for j in range( 3 ): + self.assertRaises(TraitError, d.refs.setdefault, i, ac) + self.assertEqual(d.calls, 0) + for i in range(3): + self.assertEqual(d.refs[i].value, 0) + refs = {0: ArgCheckBase(), 1: ArgCheckBase(), 2: ArgCheckBase()} + self.assertRaises(TraitError, d.set, refs=refs) + self.assertEqual(d.calls, 0) + for i in range(3): + self.assertEqual(d.refs[i].value, 0) + for i in range(3): + for j in range(3): d.exp_new = (i + 1) d.refs[j].value = (i + 1) - self.assertEqual( d.calls, 0 ) - for i in range( 3 ): - self.assertEqual( d.refs[i].value, 3 ) - - def check_complex ( self, c, r, pattern, names, other = [] ): - handlers = [ c.arg_check0, c.arg_check1, c.arg_check2, c.arg_check3, - c.arg_check4 ] - nh = len( handlers ) - nn = len( names ) - self.multi_register( c, handlers, pattern ) - for i in range( 3 ): + self.assertEqual(d.calls, 0) + for i in range(3): + self.assertEqual(d.refs[i].value, 3) + + def check_complex(self, c, r, pattern, names, other=[]): + handlers = [c.arg_check0, c.arg_check1, c.arg_check2, c.arg_check3, + c.arg_check4] + nh = len(handlers) + nn = len(names) + self.multi_register(c, handlers, pattern) + for i in range(3): for n in names: - c.set( exp_object = r, exp_name = n, exp_old = i, - exp_new = (i + 1) ) - setattr( r, n, i + 1 ) + c.set(exp_object=r, exp_name=n, exp_old=i, + exp_new=(i + 1)) + setattr(r, n, i + 1) for n in other: - c.set( exp_object = r, exp_name = n, exp_old = i, - exp_new = (i + 1) ) - setattr( r, n, i + 1 ) - self.assertEqual( c.calls, 3 * nn * nh ) - self.multi_register( c, handlers, pattern, remove = True ) - for i in range( 3 ): + c.set(exp_object=r, exp_name=n, exp_old=i, + exp_new=(i + 1)) + setattr(r, n, i + 1) + self.assertEqual(c.calls, 3 * nn * nh) + self.multi_register(c, handlers, pattern, remove=True) + for i in range(3): for n in names: - setattr( r, n, i + 1 ) + setattr(r, n, i + 1) for n in other: - setattr( r, n, i + 1 ) - self.assertEqual( c.calls, 3 * nn * nh ) + setattr(r, n, i + 1) + self.assertEqual(c.calls, 3 * nn * nh) - def multi_register ( self, object, handlers, pattern, remove = False ): + def multi_register(self, object, handlers, pattern, remove=False): for handler in handlers: - object.on_trait_change( handler, pattern, remove = remove ) - - def build_list ( self ): - l1 = Link( value = 00 ) - l2 = Link( value = 10 ) - l3 = Link( value = 20 ) - l4 = Link( value = 30 ) - l1.set( next = l2, prev = l4 ) - l2.set( next = l3, prev = l1 ) - l3.set( next = l4, prev = l2 ) - l4.set( next = l1, prev = l3 ) + object.on_trait_change(handler, pattern, remove=remove) + + def build_list(self): + l1 = Link(value=00) + l2 = Link(value=10) + l3 = Link(value=20) + l4 = Link(value=30) + l1.set(next=l2, prev=l4) + l2.set(next=l3, prev=l1) + l3.set(next=l4, prev=l2) + l4.set(next=l1, prev=l3) return l1 - def new_link ( self, lt, cur, value ): - link = Link( value = value, next = cur.next, prev = cur ) + def new_link(self, lt, cur, value): + link = Link(value=value, next=cur.next, prev=cur) cur.next.prev = link - lt.set( exp_object = cur, exp_name = 'next', exp_old = cur.next, - exp_new = link ) + lt.set(exp_object=cur, exp_name='next', exp_old=cur.next, + exp_new=link) cur.next = link return link # Run the unit tests (if invoked from the command line): if __name__ == '__main__': unittest.main() - diff --git a/traits/tests/test_getstate_setstate.py b/traits/tests/test_getstate_setstate.py deleted file mode 100644 index 2bc7e7686..000000000 --- a/traits/tests/test_getstate_setstate.py +++ /dev/null @@ -1,64 +0,0 @@ -#------------------------------------------------------------------------------- -# -# Unit test case for testing HasTraits __getstate__/__setstate__ support. -# -# Written by: David C. Morrill -# -# Date: 4/10/2007 -# -# Copyright (c) 2007, Enthought, Inc. -# All rights reserved. -# -# This software is provided without warranty under the terms of the BSD -# license included in /LICENSE.txt and may be redistributed only -# under the conditions described in the aforementioned license. The license -# is also available online at http://www.enthought.com/licenses/BSD.txt -# -# Thanks for using Enthought open source! -# -#------------------------------------------------------------------------------- - -""" Unit test case for testing HasTraits __getstate__/__setstate__ support. -""" - -#------------------------------------------------------------------------------- -# Imports: -#------------------------------------------------------------------------------- - -from traits.testing.unittest_tools import unittest - -#------------------------------------------------------------------------------- -# 'GetstateSetstateTest' unit test class: -#------------------------------------------------------------------------------- - -class GetstateSetstateTest ( unittest.TestCase ): - - #--------------------------------------------------------------------------- - # Test fixture set-up: - #--------------------------------------------------------------------------- - - def setUp ( self ): - """ Test fixture set-up. - """ - pass - - #--------------------------------------------------------------------------- - # Test fixture tear-down: - #--------------------------------------------------------------------------- - - def tearDown ( self ): - """ Test fixture tear-down. - """ - pass - - #--------------------------------------------------------------------------- - # Individual unit test methods: - #--------------------------------------------------------------------------- - - def test_ ( self ): - pass - -# Run the unit tests (if invoked from the command line): -if __name__ == '__main__': - unittest.main() - diff --git a/traits/tests/test_int_range_long.py b/traits/tests/test_int_range_long.py index b2d401cc8..142bec0ce 100644 --- a/traits/tests/test_int_range_long.py +++ b/traits/tests/test_int_range_long.py @@ -1,5 +1,3 @@ -#------------------------------------------------------------------------------- -# # Copyright (c) 2007, Enthought, Inc. # All rights reserved. # @@ -7,19 +5,14 @@ # license included in /LICENSE.txt and may be redistributed only # under the conditions described in the aforementioned license. The license # is also available online at http://www.enthought.com/licenses/BSD.txt -# -# Thanks for using Enthought open source! -# -#------------------------------------------------------------------------------- from __future__ import absolute_import -import sys - from traits.testing.unittest_tools import unittest from ..api import HasTraits, Int, Range, Long, TraitError + class A(HasTraits): i = Int l = Long diff --git a/traits/tests/test_integer.py b/traits/tests/test_integer.py index 9ac3dfad7..d9dac776c 100644 --- a/traits/tests/test_integer.py +++ b/traits/tests/test_integer.py @@ -1,4 +1,4 @@ -#------------------------------------------------------------------------------- +#------------------------------------------------------------------------------ # # Copyright (c) 2013, Enthought, Inc. # All rights reserved. @@ -10,7 +10,7 @@ # # Thanks for using Enthought open source! # -#------------------------------------------------------------------------------- +#------------------------------------------------------------------------------ """ Tests for the Int trait type. diff --git a/traits/tests/test_interface_checker.py b/traits/tests/test_interface_checker.py index f5ab00c49..aa78a6435 100644 --- a/traits/tests/test_interface_checker.py +++ b/traits/tests/test_interface_checker.py @@ -1,5 +1,3 @@ -#------------------------------------------------------------------------------- -# # Copyright (c) 2007, Enthought, Inc. # All rights reserved. # @@ -7,10 +5,6 @@ # license included in /LICENSE.txt and may be redistributed only # under the conditions described in the aforementioned license. The license # is also available online at http://www.enthought.com/licenses/BSD.txt -# -# Thanks for using Enthought open source! -# -#------------------------------------------------------------------------------- """ Tests to help find out if we can do type-safe casting. """ @@ -120,9 +114,7 @@ class IFoo(Interface): class Foo(HasTraits): pass - self.failUnlessRaises(InterfaceError, check_implements, Foo, IFoo, 2) - return def test_single_interface_with_missing_method(self): @@ -137,7 +129,6 @@ def method(self): class Foo(HasTraits): pass - self.failUnlessRaises(InterfaceError, check_implements, Foo, IFoo, 2) return @@ -424,11 +415,9 @@ class FooToIFooAdapter(Adapter): self.assertNotEqual(None, i_foo) self.assertEqual(FooToIFooAdapter, type(i_foo)) - return # Entry point for stand-alone testing. if __name__ == '__main__': unittest.main() - diff --git a/traits/tests/test_interfaces.py b/traits/tests/test_interfaces.py index a10e42e81..0106e8350 100644 --- a/traits/tests/test_interfaces.py +++ b/traits/tests/test_interfaces.py @@ -1,5 +1,3 @@ -#------------------------------------------------------------------------------- -# # Unit test case for testing interfaces and adaptation. # # Written by: David C. Morrill @@ -13,153 +11,137 @@ # license included in /LICENSE.txt and may be redistributed only # under the conditions described in the aforementioned license. The license # is also available online at http://www.enthought.com/licenses/BSD.txt -# -# Thanks for using Enthought open source! -# -#------------------------------------------------------------------------------- - """ Unit test case for testing interfaces and adaptation. """ -#------------------------------------------------------------------------------- -# Imports: -#------------------------------------------------------------------------------- - from __future__ import absolute_import from traits.testing.unittest_tools import unittest -from traits.api import HasTraits, Adapter, AdaptsTo, Instance, Int, Interface, \ - List, provides, register_factory, Supports, TraitError - +from traits.api import (HasTraits, Adapter, AdaptsTo, Instance, Int, Interface, + List, provides, register_factory, Supports, TraitError) -#------------------------------------------------------------------------------- -# Test 'Interface' definitions: -#------------------------------------------------------------------------------- class IFoo(Interface): def get_foo(self): """ Returns the current foo. """ + class IFooPlus(IFoo): def get_foo_plus(self): """ Returns even more foo. """ + class IAverage(Interface): def get_average(self): """ Returns the average value for the object. """ + class IList(Interface): def get_list(self): """ Returns the list value for the object. """ -#------------------------------------------------------------------------------- -# Test 'model' classes: -#------------------------------------------------------------------------------- -class Sample ( HasTraits ): +class Sample(HasTraits): + + s1 = Int(1, sample=True) + s2 = Int(2, sample=True) + s3 = Int(3, sample=True) + i1 = Int(4) + i2 = Int(5) + i3 = Int(6) - s1 = Int( 1, sample = True ) - s2 = Int( 2, sample = True ) - s3 = Int( 3, sample = True ) - i1 = Int( 4 ) - i2 = Int( 5 ) - i3 = Int( 6 ) @provides(IList) -class SampleList ( HasTraits ): +class SampleList(HasTraits): """SampleList docstring.""" - data = List( Int, [ 10, 20, 30 ] ) + data = List(Int, [10, 20, 30]) - def get_list ( self ): + def get_list(self): return self.data + @provides(IList, IAverage) -class SampleAverage ( HasTraits ): +class SampleAverage(HasTraits): - data = List( Int, [ 100, 200, 300 ] ) + data = List(Int, [100, 200, 300]) - def get_list ( self ): + def get_list(self): return self.data - def get_average ( self ): + def get_average(self): value = self.get_list() - if len( value ) == 0: + if len(value) == 0: return 0.0 average = 0.0 for item in value: average += item - return (average / len( value )) + return (average / len(value)) -class SampleBad ( HasTraits ): +class SampleBad(HasTraits): pass -#------------------------------------------------------------------------------- -# Test interfaces class: -#------------------------------------------------------------------------------- - -class TraitsHolder ( HasTraits ): - a_no = Instance( IAverage, adapt = 'no' ) - a_yes = Instance( IAverage, adapt = 'yes' ) - a_default = Instance( IAverage, adapt = 'default' ) - list_adapted_to = Supports( IList ) - foo_adapted_to = Supports( IFoo ) - foo_plus_adapted_to = Supports( IFooPlus ) - list_adapts_to = AdaptsTo( IList ) - foo_adapts_to = AdaptsTo( IFoo ) - foo_plus_adapts_to = AdaptsTo( IFooPlus ) +class TraitsHolder(HasTraits): -#------------------------------------------------------------------------------- -# Test 'adapter' definitions: -#------------------------------------------------------------------------------- + a_no = Instance(IAverage, adapt='no') + a_yes = Instance(IAverage, adapt='yes') + a_default = Instance(IAverage, adapt='default') + list_adapted_to = Supports(IList) + foo_adapted_to = Supports(IFoo) + foo_plus_adapted_to = Supports(IFooPlus) + list_adapts_to = AdaptsTo(IList) + foo_adapts_to = AdaptsTo(IFoo) + foo_plus_adapts_to = AdaptsTo(IFooPlus) -class SampleListAdapter ( Adapter ): - def get_list ( self ): +class SampleListAdapter(Adapter): + def get_list(self): obj = self.adaptee - return [ getattr( obj, name ) - for name in obj.trait_names( sample = True ) ] + return [getattr(obj, name) + for name in obj.trait_names(sample=True)] -class ListAverageAdapter ( Adapter ): - def get_average ( self ): +class ListAverageAdapter(Adapter): + def get_average(self): value = self.adaptee.get_list() - if len( value ) == 0: + if len(value) == 0: return 0.0 average = 0.0 for item in value: average += item - return (average / len( value )) + return (average / len(value)) + -class SampleFooAdapter ( HasTraits ): +class SampleFooAdapter(HasTraits): - object = Instance( Sample ) + object = Instance(Sample) - def __init__ ( self, object ): + def __init__(self, object): self.object = object - def get_foo ( self ): + def get_foo(self): object = self.object return (object.s1 + object.s2 + object.s3) -class FooPlusAdapter ( object ): - def __init__ ( self, obj ): +class FooPlusAdapter(object): + + def __init__(self, obj): self.obj = obj - def get_foo ( self ): + def get_foo(self): return self.obj.get_foo() - def get_foo_plus ( self ): + def get_foo_plus(self): return (self.obj.get_foo() + 1) register_factory(SampleListAdapter, Sample, IList) @@ -167,32 +149,25 @@ def get_foo_plus ( self ): register_factory(SampleFooAdapter, Sample, IFoo) register_factory(FooPlusAdapter, IFoo, IFooPlus) -#------------------------------------------------------------------------------- -# 'InterfacesTest' unit test class: -#------------------------------------------------------------------------------- - -class InterfacesTest ( unittest.TestCase ): - #--------------------------------------------------------------------------- - # Individual unit test methods: - #--------------------------------------------------------------------------- +class InterfacesTest(unittest.TestCase): - def test_provides_none ( self ): + def test_provides_none(self): @provides() class Test(HasTraits): pass - def test_provides_one ( self ): + def test_provides_one(self): @provides(IFoo) class Test(HasTraits): pass - def test_provides_multi ( self ): + def test_provides_multi(self): @provides(IFoo, IAverage, IList) class Test (HasTraits): pass - def test_provides_extended ( self ): + def test_provides_extended(self): """ Ensure that subclasses of Interfaces imply the superinterface. """ @provides(IFooPlus) @@ -202,114 +177,114 @@ class Test(HasTraits): ta = TraitsHolder() ta.foo_adapted_to = Test() - def test_provides_bad ( self ): + def test_provides_bad(self): with self.assertRaises(Exception): @provides(Sample) class Test(HasTraits): pass - def test_instance_adapt_no ( self ): + def test_instance_adapt_no(self): ta = TraitsHolder() - # Verify that SampleAverage() does not raise an error (it is an instance - # of the IAverage interface). + # Verify that SampleAverage() does not raise an error (it is an + # instance of the IAverage interface). try: ta.a_no = SampleAverage() except TraitError: - self.fail("Setting instance of interface should not require " \ + self.fail("Setting instance of interface should not require " "adaptation") # These are not instances of the IAverage interface, and therefore # cannot be set to the trait. - self.assertRaises( TraitError, ta.set, a_no = SampleList() ) - self.assertRaises( TraitError, ta.set, a_no = Sample() ) - self.assertRaises( TraitError, ta.set, a_no = SampleBad() ) + self.assertRaises(TraitError, ta.set, a_no=SampleList()) + self.assertRaises(TraitError, ta.set, a_no=Sample()) + self.assertRaises(TraitError, ta.set, a_no=SampleBad()) - def test_instance_adapt_yes ( self ): + def test_instance_adapt_yes(self): ta = TraitsHolder() ta.a_yes = object = SampleAverage() - self.assertEqual( ta.a_yes.get_average(), 200.0 ) - self.assert_( isinstance( ta.a_yes, SampleAverage ) ) - self.assertFalse( hasattr(ta, 'a_yes_') ) + self.assertEqual(ta.a_yes.get_average(), 200.0) + self.assert_(isinstance(ta.a_yes, SampleAverage)) + self.assertFalse(hasattr(ta, 'a_yes_')) ta.a_yes = object = SampleList() - self.assertEqual( ta.a_yes.get_average(), 20.0 ) - self.assert_( isinstance( ta.a_yes, ListAverageAdapter ) ) - self.assertFalse( hasattr(ta, 'a_yes_') ) + self.assertEqual(ta.a_yes.get_average(), 20.0) + self.assert_(isinstance(ta.a_yes, ListAverageAdapter)) + self.assertFalse(hasattr(ta, 'a_yes_')) ta.a_yes = object = Sample() - self.assertEqual( ta.a_yes.get_average(), 2.0 ) - self.assert_( isinstance( ta.a_yes, ListAverageAdapter ) ) - self.assertFalse( hasattr(ta, 'a_yes_') ) + self.assertEqual(ta.a_yes.get_average(), 2.0) + self.assert_(isinstance(ta.a_yes, ListAverageAdapter)) + self.assertFalse(hasattr(ta, 'a_yes_')) - self.assertRaises( TraitError, ta.set, a_yes = SampleBad() ) + self.assertRaises(TraitError, ta.set, a_yes=SampleBad()) - def test_instance_adapt_default ( self ): + def test_instance_adapt_default(self): ta = TraitsHolder() ta.a_default = object = SampleAverage() - self.assertEqual( ta.a_default.get_average(), 200.0 ) - self.assert_( isinstance( ta.a_default, SampleAverage ) ) - self.assertFalse( hasattr(ta, 'a_default_') ) + self.assertEqual(ta.a_default.get_average(), 200.0) + self.assert_(isinstance(ta.a_default, SampleAverage)) + self.assertFalse(hasattr(ta, 'a_default_')) ta.a_default = object = SampleList() - self.assertEqual( ta.a_default.get_average(), 20.0 ) - self.assert_( isinstance( ta.a_default, ListAverageAdapter ) ) - self.assertFalse( hasattr(ta, 'a_default_') ) + self.assertEqual(ta.a_default.get_average(), 20.0) + self.assert_(isinstance(ta.a_default, ListAverageAdapter)) + self.assertFalse(hasattr(ta, 'a_default_')) ta.a_default = object = Sample() - self.assertEqual( ta.a_default.get_average(), 2.0 ) - self.assert_( isinstance( ta.a_default, ListAverageAdapter ) ) - self.assertFalse( hasattr(ta, 'a_default_') ) + self.assertEqual(ta.a_default.get_average(), 2.0) + self.assert_(isinstance(ta.a_default, ListAverageAdapter)) + self.assertFalse(hasattr(ta, 'a_default_')) ta.a_default = object = SampleBad() - self.assertEqual( ta.a_default, None ) - self.assertFalse( hasattr(ta, 'a_default_') ) + self.assertEqual(ta.a_default, None) + self.assertFalse(hasattr(ta, 'a_default_')) def test_adapted_to(self): ta = TraitsHolder() ta.list_adapted_to = object = Sample() result = ta.list_adapted_to.get_list() - self.assertEqual( len( result ), 3 ) - for n in [ 1, 2, 3 ]: - self.assert_( n in result ) - self.assert_( isinstance( ta.list_adapted_to, SampleListAdapter ) ) - self.assertEqual( ta.list_adapted_to_, object ) + self.assertEqual(len(result), 3) + for n in [1, 2, 3]: + self.assert_(n in result) + self.assert_(isinstance(ta.list_adapted_to, SampleListAdapter)) + self.assertEqual(ta.list_adapted_to_, object) ta.foo_adapted_to = object = Sample() - self.assertEqual( ta.foo_adapted_to.get_foo(), 6 ) - self.assert_( isinstance( ta.foo_adapted_to, SampleFooAdapter ) ) - self.assertEqual( ta.foo_adapted_to_, object ) + self.assertEqual(ta.foo_adapted_to.get_foo(), 6) + self.assert_(isinstance(ta.foo_adapted_to, SampleFooAdapter)) + self.assertEqual(ta.foo_adapted_to_, object) - ta.foo_plus_adapted_to = object = Sample( s1 = 5, s2 = 10, s3 = 15 ) - self.assertEqual( ta.foo_plus_adapted_to.get_foo(), 30 ) - self.assertEqual( ta.foo_plus_adapted_to.get_foo_plus(), 31 ) - self.assert_( isinstance( ta.foo_plus_adapted_to, FooPlusAdapter ) ) - self.assertEqual( ta.foo_plus_adapted_to_, object ) + ta.foo_plus_adapted_to = object = Sample(s1=5, s2=10, s3=15) + self.assertEqual(ta.foo_plus_adapted_to.get_foo(), 30) + self.assertEqual(ta.foo_plus_adapted_to.get_foo_plus(), 31) + self.assert_(isinstance(ta.foo_plus_adapted_to, FooPlusAdapter)) + self.assertEqual(ta.foo_plus_adapted_to_, object) def test_adapts_to(self): ta = TraitsHolder() ta.list_adapts_to = object = Sample() - self.assertEqual(ta.list_adapts_to, object ) + self.assertEqual(ta.list_adapts_to, object) result = ta.list_adapts_to_.get_list() - self.assertEqual( len( result ), 3 ) - for n in [ 1, 2, 3 ]: - self.assert_( n in result ) - self.assert_( isinstance( ta.list_adapts_to_, SampleListAdapter ) ) + self.assertEqual(len(result), 3) + for n in [1, 2, 3]: + self.assert_(n in result) + self.assert_(isinstance(ta.list_adapts_to_, SampleListAdapter)) ta.foo_adapts_to = object = Sample() - self.assertEqual( ta.foo_adapts_to, object ) - self.assertEqual( ta.foo_adapts_to_.get_foo(), 6 ) - self.assert_( isinstance( ta.foo_adapts_to_, SampleFooAdapter ) ) - - ta.foo_plus_adapts_to = object = Sample( s1 = 5, s2 = 10, s3 = 15 ) - self.assertEqual( ta.foo_plus_adapts_to, object ) - self.assertEqual( ta.foo_plus_adapts_to_.get_foo(), 30 ) - self.assertEqual( ta.foo_plus_adapts_to_.get_foo_plus(), 31 ) - self.assert_( isinstance( ta.foo_plus_adapts_to_, FooPlusAdapter ) ) + self.assertEqual(ta.foo_adapts_to, object) + self.assertEqual(ta.foo_adapts_to_.get_foo(), 6) + self.assert_(isinstance(ta.foo_adapts_to_, SampleFooAdapter)) + + ta.foo_plus_adapts_to = object = Sample(s1=5, s2=10, s3=15) + self.assertEqual(ta.foo_plus_adapts_to, object) + self.assertEqual(ta.foo_plus_adapts_to_.get_foo(), 30) + self.assertEqual(ta.foo_plus_adapts_to_.get_foo_plus(), 31) + self.assert_(isinstance(ta.foo_plus_adapts_to_, FooPlusAdapter)) def test_decorated_class_name_and_docstring(self): self.assertEqual(SampleList.__name__, 'SampleList') diff --git a/traits/tests/test_interfaces_with_implements.py b/traits/tests/test_interfaces_with_implements.py index ee2ea63da..79bc6646f 100644 --- a/traits/tests/test_interfaces_with_implements.py +++ b/traits/tests/test_interfaces_with_implements.py @@ -1,5 +1,3 @@ -#------------------------------------------------------------------------------- -# # Unit test case for testing interfaces and adaptation. # # Written by: David C. Morrill @@ -13,11 +11,6 @@ # license included in /LICENSE.txt and may be redistributed only # under the conditions described in the aforementioned license. The license # is also available online at http://www.enthought.com/licenses/BSD.txt -# -# Thanks for using Enthought open source! -# -#------------------------------------------------------------------------------- - """ Unit test case for testing interfaces and adaptation. This file is equivalent to test_interfaces.py, only using the deprecated @@ -25,10 +18,6 @@ """ -#------------------------------------------------------------------------------- -# Imports: -#------------------------------------------------------------------------------- - from __future__ import absolute_import import sys @@ -46,286 +35,277 @@ Therefore, this test will fail due to the use of "adapts". """) -#------------------------------------------------------------------------------- + +#------------------------------------------------------------------------------ # Test 'Interface' definitions: -#------------------------------------------------------------------------------- +#------------------------------------------------------------------------------ class IFoo(Interface): def get_foo(self): """ Returns the current foo. """ + class IFooPlus(IFoo): def get_foo_plus(self): """ Returns even more foo. """ + class IAverage(Interface): def get_average(self): """ Returns the average value for the object. """ + class IList(Interface): def get_list(self): """ Returns the list value for the object. """ -#------------------------------------------------------------------------------- -# Test 'model' classes: -#------------------------------------------------------------------------------- -class Sample ( HasTraits ): +class Sample(HasTraits): + s1 = Int(1, sample=True) + s2 = Int(2, sample=True) + s3 = Int(3, sample=True) + i1 = Int(4) + i2 = Int(5) + i3 = Int(6) - s1 = Int( 1, sample = True ) - s2 = Int( 2, sample = True ) - s3 = Int( 3, sample = True ) - i1 = Int( 4 ) - i2 = Int( 5 ) - i3 = Int( 6 ) -class SampleList ( HasTraits ): +class SampleList(HasTraits): - implements( IList ) + implements(IList) - data = List( Int, [ 10, 20, 30 ] ) + data = List(Int, [10, 20, 30]) - def get_list ( self ): + def get_list(self): return self.data -class SampleAverage ( HasTraits ): - implements( IList, IAverage ) +class SampleAverage(HasTraits): + + implements(IList, IAverage) - data = List( Int, [ 100, 200, 300 ] ) + data = List(Int, [100, 200, 300]) - def get_list ( self ): + def get_list(self): return self.data - def get_average ( self ): + def get_average(self): value = self.get_list() - if len( value ) == 0: + if len(value) == 0: return 0.0 average = 0.0 for item in value: average += item - return (average / len( value )) + return (average / len(value)) -class SampleBad ( HasTraits ): +class SampleBad(HasTraits): pass -#------------------------------------------------------------------------------- -# Test interfaces class: -#------------------------------------------------------------------------------- - -class TraitsHolder ( HasTraits ): - a_no = Instance( IAverage, adapt = 'no' ) - a_yes = Instance( IAverage, adapt = 'yes' ) - a_default = Instance( IAverage, adapt = 'default' ) - list_adapted_to = Supports( IList ) - foo_adapted_to = Supports( IFoo ) - foo_plus_adapted_to = Supports( IFooPlus ) - list_adapts_to = AdaptsTo( IList ) - foo_adapts_to = AdaptsTo( IFoo ) - foo_plus_adapts_to = AdaptsTo( IFooPlus ) +class TraitsHolder(HasTraits): -#------------------------------------------------------------------------------- -# Test 'adapter' definitions: -#------------------------------------------------------------------------------- + a_no = Instance(IAverage, adapt='no') + a_yes = Instance(IAverage, adapt='yes') + a_default = Instance(IAverage, adapt='default') + list_adapted_to = Supports(IList) + foo_adapted_to = Supports(IFoo) + foo_plus_adapted_to = Supports(IFooPlus) + list_adapts_to = AdaptsTo(IList) + foo_adapts_to = AdaptsTo(IFoo) + foo_plus_adapts_to = AdaptsTo(IFooPlus) -class SampleListAdapter ( Adapter ): - adapts( Sample, IList ) +class SampleListAdapter(Adapter): + adapts(Sample, IList) - def get_list ( self ): + def get_list(self): obj = self.adaptee - return [ getattr( obj, name ) - for name in obj.trait_names( sample = True ) ] + return [getattr(obj, name) + for name in obj.trait_names(sample=True)] -class ListAverageAdapter ( Adapter ): - adapts( IList, IAverage ) +class ListAverageAdapter(Adapter): - def get_average ( self ): + adapts(IList, IAverage) + + def get_average(self): value = self.adaptee.get_list() - if len( value ) == 0: + if len(value) == 0: return 0.0 average = 0.0 for item in value: average += item - return (average / len( value )) + return (average / len(value)) + -class SampleFooAdapter ( HasTraits ): +class SampleFooAdapter(HasTraits): - adapts( Sample, IFoo ) + adapts(Sample, IFoo) - object = Instance( Sample ) + object = Instance(Sample) - def __init__ ( self, object ): + def __init__(self, object): self.object = object - def get_foo ( self ): + def get_foo(self): object = self.object return (object.s1 + object.s2 + object.s3) -class FooPlusAdapter ( object ): - def __init__ ( self, obj ): +class FooPlusAdapter(object): + + def __init__(self, obj): self.obj = obj - def get_foo ( self ): + def get_foo(self): return self.obj.get_foo() - def get_foo_plus ( self ): + def get_foo_plus(self): return (self.obj.get_foo() + 1) -adapts( FooPlusAdapter, IFoo, IFooPlus ) - -#------------------------------------------------------------------------------- -# 'InterfacesTest' unit test class: -#------------------------------------------------------------------------------- +adapts(FooPlusAdapter, IFoo, IFooPlus) -class InterfacesTest ( unittest.TestCase ): - #--------------------------------------------------------------------------- - # Individual unit test methods: - #--------------------------------------------------------------------------- +class InterfacesTest(unittest.TestCase): - def test_implements_none ( self ): - class Test ( HasTraits ): + def test_implements_none(self): + class Test(HasTraits): implements() - def test_implements_one ( self ): - class Test ( HasTraits ): - implements( IFoo ) + def test_implements_one(self): + class Test(HasTraits): + implements(IFoo) - def test_implements_multi ( self ): - class Test ( HasTraits ): - implements( IFoo, IAverage, IList ) + def test_implements_multi(self): + class Test(HasTraits): + implements(IFoo, IAverage, IList) - def test_implements_extended ( self ): + def test_implements_extended(self): """ Ensure that subclasses of Interfaces imply the superinterface. """ - class Test ( HasTraits ): - implements( IFooPlus ) + class Test(HasTraits): + implements(IFooPlus) ta = TraitsHolder() ta.foo_adapted_to = Test() - def test_implements_bad ( self ): - self.assertRaises( TraitError, self.implements_bad ) + def test_implements_bad(self): + self.assertRaises(TraitError, self.implements_bad) - def test_instance_adapt_no ( self ): + def test_instance_adapt_no(self): ta = TraitsHolder() - # Verify that SampleAverage() does not raise an error (it is an instance - # of the IAverage interface). + # Verify that SampleAverage() does not raise an error (it is an + # instance of the IAverage interface). try: ta.a_no = SampleAverage() except TraitError: - self.fail("Setting instance of interface should not require " \ + self.fail("Setting instance of interface should not require " "adaptation") # These are not instances of the IAverage interface, and therefore # cannot be set to the trait. - self.assertRaises( TraitError, ta.set, a_no = SampleList() ) - self.assertRaises( TraitError, ta.set, a_no = Sample() ) - self.assertRaises( TraitError, ta.set, a_no = SampleBad() ) + self.assertRaises(TraitError, ta.set, a_no=SampleList()) + self.assertRaises(TraitError, ta.set, a_no=Sample()) + self.assertRaises(TraitError, ta.set, a_no=SampleBad()) - def test_instance_adapt_yes ( self ): + def test_instance_adapt_yes(self): ta = TraitsHolder() ta.a_yes = object = SampleAverage() - self.assertEqual( ta.a_yes.get_average(), 200.0 ) - self.assert_( isinstance( ta.a_yes, SampleAverage ) ) - self.assertFalse( hasattr(ta, 'a_yes_') ) + self.assertEqual(ta.a_yes.get_average(), 200.0) + self.assert_(isinstance(ta.a_yes, SampleAverage)) + self.assertFalse(hasattr(ta, 'a_yes_')) ta.a_yes = object = SampleList() - self.assertEqual( ta.a_yes.get_average(), 20.0 ) - self.assert_( isinstance( ta.a_yes, ListAverageAdapter ) ) - self.assertFalse( hasattr(ta, 'a_yes_') ) + self.assertEqual(ta.a_yes.get_average(), 20.0) + self.assert_(isinstance(ta.a_yes, ListAverageAdapter)) + self.assertFalse(hasattr(ta, 'a_yes_')) ta.a_yes = object = Sample() - self.assertEqual( ta.a_yes.get_average(), 2.0 ) - self.assert_( isinstance( ta.a_yes, ListAverageAdapter ) ) - self.assertFalse( hasattr(ta, 'a_yes_') ) + self.assertEqual(ta.a_yes.get_average(), 2.0) + self.assert_(isinstance(ta.a_yes, ListAverageAdapter)) + self.assertFalse(hasattr(ta, 'a_yes_')) - self.assertRaises( TraitError, ta.set, a_yes = SampleBad() ) + self.assertRaises(TraitError, ta.set, a_yes=SampleBad()) - def test_instance_adapt_default ( self ): + def test_instance_adapt_default(self): ta = TraitsHolder() ta.a_default = object = SampleAverage() - self.assertEqual( ta.a_default.get_average(), 200.0 ) - self.assert_( isinstance( ta.a_default, SampleAverage ) ) - self.assertFalse( hasattr(ta, 'a_default_') ) + self.assertEqual(ta.a_default.get_average(), 200.0) + self.assert_(isinstance(ta.a_default, SampleAverage)) + self.assertFalse(hasattr(ta, 'a_default_')) ta.a_default = object = SampleList() - self.assertEqual( ta.a_default.get_average(), 20.0 ) - self.assert_( isinstance( ta.a_default, ListAverageAdapter ) ) - self.assertFalse( hasattr(ta, 'a_default_') ) + self.assertEqual(ta.a_default.get_average(), 20.0) + self.assert_(isinstance(ta.a_default, ListAverageAdapter)) + self.assertFalse(hasattr(ta, 'a_default_')) ta.a_default = object = Sample() - self.assertEqual( ta.a_default.get_average(), 2.0 ) - self.assert_( isinstance( ta.a_default, ListAverageAdapter ) ) - self.assertFalse( hasattr(ta, 'a_default_') ) + self.assertEqual(ta.a_default.get_average(), 2.0) + self.assert_(isinstance(ta.a_default, ListAverageAdapter)) + self.assertFalse(hasattr(ta, 'a_default_')) ta.a_default = object = SampleBad() - self.assertEqual( ta.a_default, None ) - self.assertFalse( hasattr(ta, 'a_default_') ) + self.assertEqual(ta.a_default, None) + self.assertFalse(hasattr(ta, 'a_default_')) def test_adapted_to(self): ta = TraitsHolder() ta.list_adapted_to = object = Sample() result = ta.list_adapted_to.get_list() - self.assertEqual( len( result ), 3 ) - for n in [ 1, 2, 3 ]: - self.assert_( n in result ) - self.assert_( isinstance( ta.list_adapted_to, SampleListAdapter ) ) - self.assertEqual( ta.list_adapted_to_, object ) + self.assertEqual(len(result), 3) + for n in [1, 2, 3]: + self.assert_(n in result) + self.assert_(isinstance(ta.list_adapted_to, SampleListAdapter)) + self.assertEqual(ta.list_adapted_to_, object) ta.foo_adapted_to = object = Sample() - self.assertEqual( ta.foo_adapted_to.get_foo(), 6 ) - self.assert_( isinstance( ta.foo_adapted_to, SampleFooAdapter ) ) - self.assertEqual( ta.foo_adapted_to_, object ) + self.assertEqual(ta.foo_adapted_to.get_foo(), 6) + self.assert_(isinstance(ta.foo_adapted_to, SampleFooAdapter)) + self.assertEqual(ta.foo_adapted_to_, object) - ta.foo_plus_adapted_to = object = Sample( s1 = 5, s2 = 10, s3 = 15 ) - self.assertEqual( ta.foo_plus_adapted_to.get_foo(), 30 ) - self.assertEqual( ta.foo_plus_adapted_to.get_foo_plus(), 31 ) - self.assert_( isinstance( ta.foo_plus_adapted_to, FooPlusAdapter ) ) - self.assertEqual( ta.foo_plus_adapted_to_, object ) + ta.foo_plus_adapted_to = object = Sample(s1=5, s2=10, s3=15) + self.assertEqual(ta.foo_plus_adapted_to.get_foo(), 30) + self.assertEqual(ta.foo_plus_adapted_to.get_foo_plus(), 31) + self.assert_(isinstance(ta.foo_plus_adapted_to, FooPlusAdapter)) + self.assertEqual(ta.foo_plus_adapted_to_, object) def test_adapts_to(self): ta = TraitsHolder() ta.list_adapts_to = object = Sample() - self.assertEqual(ta.list_adapts_to, object ) + self.assertEqual(ta.list_adapts_to, object) result = ta.list_adapts_to_.get_list() - self.assertEqual( len( result ), 3 ) - for n in [ 1, 2, 3 ]: - self.assert_( n in result ) - self.assert_( isinstance( ta.list_adapts_to_, SampleListAdapter ) ) + self.assertEqual(len(result), 3) + for n in [1, 2, 3]: + self.assert_(n in result) + self.assert_(isinstance(ta.list_adapts_to_, SampleListAdapter)) ta.foo_adapts_to = object = Sample() - self.assertEqual( ta.foo_adapts_to, object ) - self.assertEqual( ta.foo_adapts_to_.get_foo(), 6 ) - self.assert_( isinstance( ta.foo_adapts_to_, SampleFooAdapter ) ) + self.assertEqual(ta.foo_adapts_to, object) + self.assertEqual(ta.foo_adapts_to_.get_foo(), 6) + self.assert_(isinstance(ta.foo_adapts_to_, SampleFooAdapter)) - ta.foo_plus_adapts_to = object = Sample( s1 = 5, s2 = 10, s3 = 15 ) - self.assertEqual( ta.foo_plus_adapts_to, object ) - self.assertEqual( ta.foo_plus_adapts_to_.get_foo(), 30 ) - self.assertEqual( ta.foo_plus_adapts_to_.get_foo_plus(), 31 ) - self.assert_( isinstance( ta.foo_plus_adapts_to_, FooPlusAdapter ) ) + ta.foo_plus_adapts_to = object = Sample(s1=5, s2=10, s3=15) + self.assertEqual(ta.foo_plus_adapts_to, object) + self.assertEqual(ta.foo_plus_adapts_to_.get_foo(), 30) + self.assertEqual(ta.foo_plus_adapts_to_.get_foo_plus(), 31) + self.assert_(isinstance(ta.foo_plus_adapts_to_, FooPlusAdapter)) #-- Helper Methods -------------------------------------------------------- - def implements_bad ( self ): - class Test ( HasTraits ): - implements( Sample ) + def implements_bad(self): + class Test(HasTraits): + implements(Sample) # Run the unit tests (if invoked from the command line): if __name__ == '__main__': diff --git a/traits/tests/test_keyword_args.py b/traits/tests/test_keyword_args.py index 5b7d900d3..a94ff3909 100644 --- a/traits/tests/test_keyword_args.py +++ b/traits/tests/test_keyword_args.py @@ -1,5 +1,3 @@ -#------------------------------------------------------------------------------- -# # Copyright (c) 2007, Enthought, Inc. # All rights reserved. # @@ -7,10 +5,6 @@ # license included in /LICENSE.txt and may be redistributed only # under the conditions described in the aforementioned license. The license # is also available online at http://www.enthought.com/licenses/BSD.txt -# -# Thanks for using Enthought open source! -# -#------------------------------------------------------------------------------- from __future__ import absolute_import @@ -18,18 +12,21 @@ from traits.testing.unittest_tools import unittest + class Bar(HasTraits): b = Int(3) + class Foo(HasTraits): - bar = Instance(Bar) + bar = Instance(Bar) + class KeyWordArgsTest(unittest.TestCase): - def test_using_kw(self): - bar = Bar(b=5) - foo = Foo(bar=bar) - self.assertEqual(foo.bar.b, 5) - - def test_not_using_kw(self): - foo = Foo() - self.assertEqual(foo.bar, None) + def test_using_kw(self): + bar = Bar(b=5) + foo = Foo(bar=bar) + self.assertEqual(foo.bar.b, 5) + + def test_not_using_kw(self): + foo = Foo() + self.assertEqual(foo.bar, None) diff --git a/traits/tests/test_list.py b/traits/tests/test_list.py index 2d6baedf6..6a42cf87b 100644 --- a/traits/tests/test_list.py +++ b/traits/tests/test_list.py @@ -1,5 +1,3 @@ -#------------------------------------------------------------------------------- -# # Copyright (c) 2007, Enthought, Inc. # All rights reserved. # @@ -7,10 +5,6 @@ # license included in /LICENSE.txt and may be redistributed only # under the conditions described in the aforementioned license. The license # is also available online at http://www.enthought.com/licenses/BSD.txt -# -# Thanks for using Enthought open source! -# -#------------------------------------------------------------------------------- from __future__ import absolute_import @@ -20,9 +14,11 @@ from ..api import CList, HasTraits, Instance, Int, List, Str, TraitError + class Foo(HasTraits): l = List(Str) + class Bar(HasTraits): name = Str @@ -30,6 +26,7 @@ class Bar(HasTraits): class Baz(HasTraits): bars = List(Bar) + class BazRef(HasTraits): bars = List(Bar, copy='ref') @@ -37,32 +34,35 @@ class BazRef(HasTraits): class DeepBaz(HasTraits): baz = Instance(Baz) + class DeepBazBazRef(HasTraits): baz = Instance(BazRef) + class CFoo(HasTraits): ints = CList(Int) strs = CList(Str) + class ListTestCase(unittest.TestCase): def test_initialized(self): f = Foo() - self.failIfEqual( f.l, None ) - self.failUnlessEqual( len(f.l), 0 ) + self.failIfEqual(f.l, None) + self.failUnlessEqual(len(f.l), 0) return def test_initializer(self): - f = Foo( l=['a', 'list']) - self.failIfEqual( f.l, None ) - self.failUnlessEqual( f.l, ['a', 'list'] ) + f = Foo(l=['a', 'list']) + self.failIfEqual(f.l, None) + self.failUnlessEqual(f.l, ['a', 'list']) return def test_type_check(self): f = Foo() f.l.append('string') - self.failUnlessRaises( TraitError, f.l.append, 123.456 ) + self.failUnlessRaises(TraitError, f.l.append, 123.456) return def test_append(self): @@ -79,53 +79,53 @@ def test_remove(self): return def test_slice(self): - f = Foo( l=['zero', 'one', 'two', 'three'] ) - self.failUnlessEqual( f.l[0], 'zero') - self.failUnlessEqual( f.l[:0], []) - self.failUnlessEqual( f.l[:1], ['zero']) - self.failUnlessEqual( f.l[0:1], ['zero']) - self.failUnlessEqual( f.l[1:], ['one','two','three']) - self.failUnlessEqual( f.l[-1], 'three') - self.failUnlessEqual( f.l[-2], 'two') - self.failUnlessEqual( f.l[:-1], ['zero', 'one', 'two']) + f = Foo(l=['zero', 'one', 'two', 'three']) + self.failUnlessEqual(f.l[0], 'zero') + self.failUnlessEqual(f.l[:0], []) + self.failUnlessEqual(f.l[:1], ['zero']) + self.failUnlessEqual(f.l[0:1], ['zero']) + self.failUnlessEqual(f.l[1:], ['one', 'two', 'three']) + self.failUnlessEqual(f.l[-1], 'three') + self.failUnlessEqual(f.l[-2], 'two') + self.failUnlessEqual(f.l[:-1], ['zero', 'one', 'two']) return def test_retrieve_reference(self): - f = Foo( l=['initial', 'value'] ) + f = Foo(l=['initial', 'value']) l = f.l - self.failUnless( l is f.l ) + self.failUnless(l is f.l) # no copy on change behavior, l is always a reference l.append('change') - self.failUnlessEqual( f.l, ['initial', 'value', 'change']) + self.failUnlessEqual(f.l, ['initial', 'value', 'change']) f.l.append('more change') - self.failUnlessEqual( l, ['initial', 'value', 'change', 'more change']) + self.failUnlessEqual(l, ['initial', 'value', 'change', 'more change']) return def test_assignment_makes_copy(self): - f = Foo( l=['initial', 'value'] ) + f = Foo(l=['initial', 'value']) l = ['new'] f.l = l # same content - self.failUnlessEqual( l, f.l) + self.failUnlessEqual(l, f.l) # different objects - self.failIf( l is f.l ) + self.failIf(l is f.l) # which means behaviorally... l.append('l change') - self.failIf( 'l change' in f.l ) + self.failIf('l change' in f.l) f.l.append('f.l change') - self.failIf( 'f.l change' in l ) + self.failIf('f.l change' in l) return def test_should_not_allow_none(self): - f = Foo( l=['initial', 'value'] ) + f = Foo(l=['initial', 'value']) try: f.l = None self.fail('None assigned to List trait.') @@ -135,114 +135,110 @@ def test_should_not_allow_none(self): def test_clone(self): baz = Baz() for name in ['a', 'b', 'c', 'd']: - baz.bars.append( Bar(name=name) ) + baz.bars.append(Bar(name=name)) # Clone will clone baz, the bars list, and the objects in the list baz_copy = baz.clone_traits() - self.failIf( baz_copy is baz) - self.failIf( baz_copy.bars is baz.bars) + self.failIf(baz_copy is baz) + self.failIf(baz_copy.bars is baz.bars) - self.failUnlessEqual( len(baz_copy.bars), len(baz.bars) ) + self.failUnlessEqual(len(baz_copy.bars), len(baz.bars)) for bar in baz.bars: - self.failIf( bar in baz_copy.bars ) + self.failIf(bar in baz_copy.bars) - baz_bar_names = [ bar.name for bar in baz.bars ] - baz_copy_bar_names = [ bar.name for bar in baz_copy.bars ] + baz_bar_names = [bar.name for bar in baz.bars] + baz_copy_bar_names = [bar.name for bar in baz_copy.bars] baz_bar_names.sort() baz_copy_bar_names.sort() - self.failUnlessEqual( baz_copy_bar_names, baz_bar_names ) + self.failUnlessEqual(baz_copy_bar_names, baz_bar_names) return def test_clone_ref(self): baz = BazRef() for name in ['a', 'b', 'c', 'd']: - baz.bars.append( Bar(name=name) ) + baz.bars.append(Bar(name=name)) # Clone will clone baz, the bars list, but the objects in the list # will not be cloned because the copy metatrait of the List is 'ref' baz_copy = baz.clone_traits() - self.failIf( baz_copy is baz) - self.failIf( baz_copy.bars is baz.bars) + self.failIf(baz_copy is baz) + self.failIf(baz_copy.bars is baz.bars) - self.failUnlessEqual( len(baz_copy.bars), len(baz.bars) ) + self.failUnlessEqual(len(baz_copy.bars), len(baz.bars)) for bar in baz.bars: - self.failUnless( bar in baz_copy.bars ) + self.failUnless(bar in baz_copy.bars) return - def test_clone_deep_baz(self): baz = Baz() for name in ['a', 'b', 'c', 'd']: - baz.bars.append( Bar(name=name) ) + baz.bars.append(Bar(name=name)) - deep_baz = DeepBaz( baz=baz ) + deep_baz = DeepBaz(baz=baz) # Clone will clone deep_baz, deep_baz.baz, the bars list, # and the objects in the list deep_baz_copy = deep_baz.clone_traits() - self.failIf( deep_baz_copy is deep_baz) - self.failIf( deep_baz_copy.baz is deep_baz.baz) + self.failIf(deep_baz_copy is deep_baz) + self.failIf(deep_baz_copy.baz is deep_baz.baz) baz_copy = deep_baz_copy.baz - self.failIf( baz_copy is baz) - self.failIf( baz_copy.bars is baz.bars) + self.failIf(baz_copy is baz) + self.failIf(baz_copy.bars is baz.bars) - self.failUnlessEqual( len(baz_copy.bars), len(baz.bars) ) + self.failUnlessEqual(len(baz_copy.bars), len(baz.bars)) for bar in baz.bars: - self.failIf( bar in baz_copy.bars ) + self.failIf(bar in baz_copy.bars) - baz_bar_names = [ bar.name for bar in baz.bars ] - baz_copy_bar_names = [ bar.name for bar in baz_copy.bars ] + baz_bar_names = [bar.name for bar in baz.bars] + baz_copy_bar_names = [bar.name for bar in baz_copy.bars] baz_bar_names.sort() baz_copy_bar_names.sort() - self.failUnlessEqual( baz_copy_bar_names, baz_bar_names ) - + self.failUnlessEqual(baz_copy_bar_names, baz_bar_names) return - def test_clone_deep_baz_ref(self): baz = BazRef() for name in ['a', 'b', 'c', 'd']: - baz.bars.append( Bar(name=name) ) + baz.bars.append(Bar(name=name)) - deep_baz = DeepBazBazRef( baz=baz ) + deep_baz = DeepBazBazRef(baz=baz) deep_baz_copy = deep_baz.clone_traits() - self.failIf( deep_baz_copy is deep_baz) - self.failIf( deep_baz_copy.baz is deep_baz.baz) + self.failIf(deep_baz_copy is deep_baz) + self.failIf(deep_baz_copy.baz is deep_baz.baz) baz_copy = deep_baz_copy.baz - self.failIf( baz_copy is baz) - self.failIf( baz_copy.bars is baz.bars) + self.failIf(baz_copy is baz) + self.failIf(baz_copy.bars is baz.bars) - self.failUnlessEqual( len(baz_copy.bars), len(baz.bars) ) + self.failUnlessEqual(len(baz_copy.bars), len(baz.bars)) for bar in baz.bars: - self.failUnless( bar in baz_copy.bars ) - + self.failUnless(bar in baz_copy.bars) return def test_coercion(self): f = CFoo() # Test coercion from basic built-in types - f.ints = [1,2,3] - desired = [1,2,3] - self.failUnlessEqual( f.ints, desired ) - f.ints = (1,2,3) - self.failUnlessEqual( f.ints, desired ) + f.ints = [1, 2, 3] + desired = [1, 2, 3] + self.failUnlessEqual(f.ints, desired) + f.ints = (1, 2, 3) + self.failUnlessEqual(f.ints, desired) f.strs = ("abc", "def", "ghi") - self.failUnlessEqual( f.strs, ["abc", "def", "ghi"] ) + self.failUnlessEqual(f.strs, ["abc", "def", "ghi"]) f.strs = "abcdef" - self.failUnlessEqual( f.strs, list("abcdef") ) + self.failUnlessEqual(f.strs, list("abcdef")) try: from numpy import array @@ -250,17 +246,12 @@ def test_coercion(self): pass else: if sys.version_info[0] < 3: - f.ints = array([1,2,3]) - self.failUnlessEqual( f.ints, [1,2,3] ) + f.ints = array([1, 2, 3]) + self.failUnlessEqual(f.ints, [1, 2, 3]) else: # These would fail due to np.int_ being an invalid vallue - # for the Int-trait. + # for the Int-trait. pass - - f.strs = array( ("abc", "def", "ghi") ) - self.failUnlessEqual( f.strs, ["abc", "def", "ghi"] ) - - - -### EOF + f.strs = array(("abc", "def", "ghi")) + self.failUnlessEqual(f.strs, ["abc", "def", "ghi"]) diff --git a/traits/tests/test_listeners.py b/traits/tests/test_listeners.py index 465c996ae..44d1e6487 100644 --- a/traits/tests/test_listeners.py +++ b/traits/tests/test_listeners.py @@ -1,5 +1,3 @@ -#------------------------------------------------------------------------------- -# # Test the 'add_trait_listener', 'remove_trait_listener' interface to # the HasTraits class. # @@ -18,12 +16,6 @@ # available online at http://www.enthought.com/licenses/BSD.txt # # Thanks for using Enthought open source! -# -#------------------------------------------------------------------------------- - -#------------------------------------------------------------------------------- -# Imports: -#------------------------------------------------------------------------------- from __future__ import absolute_import @@ -38,9 +30,6 @@ from ..api import HasTraits, Str, Int, Float, Any, Event from ..api import push_exception_handler, pop_exception_handler -#------------------------------------------------------------------------------- -# captured_stderr helper context manager -#------------------------------------------------------------------------------- @contextlib.contextmanager def captured_stderr(): @@ -57,53 +46,36 @@ def captured_stderr(): sys.stderr = original_stderr -#------------------------------------------------------------------------------- -# 'GenerateEvents' class: -#------------------------------------------------------------------------------- - -class GenerateEvents ( HasTraits ): - - #--------------------------------------------------------------------------- - # Trait definitions: - #--------------------------------------------------------------------------- - - name = Str - age = Int +class GenerateEvents(HasTraits): + name = Str + age = Int weight = Float -#------------------------------------------------------------------------------- -# 'ListenEvents' class: -#------------------------------------------------------------------------------- +events = {} # dict of events -events = {} # dict of events -class ListenEvents ( HasTraits ): +class ListenEvents(HasTraits): - #--------------------------------------------------------------------------- # 'GenerateEvents' event interface: # the events are stored in the dict 'events' - #--------------------------------------------------------------------------- - def _name_changed ( self, object, name, old, new ): + def _name_changed(self, object, name, old, new): events["_name_changed"] = (name, old, new) - def _age_changed ( self, object, name, old, new ): + def _age_changed(self, object, name, old, new): events["_age_changed"] = (name, old, new) - def _weight_changed ( self, object, name, old, new ): + def _weight_changed(self, object, name, old, new): events["_weight_changed"] = (name, old, new) - def alt_name_changed ( self, object, name, old, new ): + def alt_name_changed(self, object, name, old, new): events["alt_name_changed"] = (name, old, new) - def alt_weight_changed ( self, object, name, old, new ): + def alt_weight_changed(self, object, name, old, new): events["alt_weight_changed"] = (name, old, new) -#------------------------------------------------------------------------------- -# unit test class: -#------------------------------------------------------------------------------- -class Test_Listeners ( unittest.TestCase ): +class Test_Listeners(unittest.TestCase): def test(self): global events @@ -113,12 +85,12 @@ def test(self): le = ListenEvents() # Starting test: No Listeners - ge.set( name = 'Joe', age = 22, weight = 152.0 ) + ge.set(name='Joe', age=22, weight=152.0) # Adding default listener - ge.add_trait_listener( le ) + ge.add_trait_listener(le) events = {} - ge.set( name = 'Mike', age = 34, weight = 178.0 ) + ge.set(name='Mike', age=34, weight=178.0) self.assertEqual(events, { '_age_changed': ('age', 22, 34), '_weight_changed': ('weight', 152.0, 178.0), @@ -126,9 +98,9 @@ def test(self): }) # Adding alternate listener - ge.add_trait_listener( le, 'alt' ) + ge.add_trait_listener(le, 'alt') events = {} - ge.set( name = 'Gertrude', age = 39, weight = 108.0 ) + ge.set(name='Gertrude', age=39, weight=108.0) self.assertEqual(events, { '_age_changed': ('age', 34, 39), '_name_changed': ('name', 'Mike', 'Gertrude'), @@ -138,18 +110,18 @@ def test(self): }) # Removing default listener - ge.remove_trait_listener( le ) + ge.remove_trait_listener(le) events = {} - ge.set( name = 'Sally', age = 46, weight = 118.0 ) + ge.set(name='Sally', age=46, weight=118.0) self.assertEqual(events, { 'alt_name_changed': ('name', 'Gertrude', 'Sally'), 'alt_weight_changed': ('weight', 108.0, 118.0), }) # Removing alternate listener - ge.remove_trait_listener( le, 'alt' ) + ge.remove_trait_listener(le, 'alt') events = {} - ge.set( name = 'Ralph', age = 29, weight = 198.0 ) + ge.set(name='Ralph', age=29, weight=198.0) self.assertEqual(events, {}) @@ -176,7 +148,7 @@ def setUp(self): handler=lambda *args: None, reraise_exceptions=True, main=True, - ) + ) def tearDown(self): pop_exception_handler() @@ -233,7 +205,7 @@ def main_thread(event_source, start_event): t = threading.Thread( target=worker_thread, args=(event_source, start_event), - ) + ) t.start() main_thread(event_source, start_event) t.join() diff --git a/traits/tests/test_new_notifiers.py b/traits/tests/test_new_notifiers.py index 3064765d6..01287b92b 100644 --- a/traits/tests/test_new_notifiers.py +++ b/traits/tests/test_new_notifiers.py @@ -23,8 +23,8 @@ class TestNewNotifiers(unittest.TestCase): """ Tests for dynamic notifiers with `dispatch='new'`. """ def test_notification_on_separate_thread(self): - notifications = [] + def on_foo_notifications(obj, name, old, new): thread_id = thread.get_ident() event = (thread_id, obj, name, old, new) diff --git a/traits/tests/test_pickle_validated_dict.py b/traits/tests/test_pickle_validated_dict.py index 3eaf4d55e..6e4dacff4 100644 --- a/traits/tests/test_pickle_validated_dict.py +++ b/traits/tests/test_pickle_validated_dict.py @@ -1,5 +1,3 @@ -#------------------------------------------------------------------------------- -# # Copyright (c) 2007, Enthought, Inc. # All rights reserved. # @@ -7,10 +5,6 @@ # license included in /LICENSE.txt and may be redistributed only # under the conditions described in the aforementioned license. The license # is also available online at http://www.enthought.com/licenses/BSD.txt -# -# Thanks for using Enthought open source! -# -#------------------------------------------------------------------------------- from __future__ import absolute_import @@ -19,15 +13,16 @@ from ..api import Dict, HasTraits, Int, List -class C(HasTraits): +class C(HasTraits): # A dict trait containing a list trait a = Dict(Int, List(Int)) # And we must initialize it to something non-trivial def __init__(self): super(C, self).__init__() - self.a = {1 : [2,3]} + self.a = {1: [2, 3]} + class PickleValidatedDictTestCase(unittest.TestCase): def test(self): @@ -38,4 +33,3 @@ def test(self): loads(x) except AttributeError, e: self.fail('Unpickling raised an AttributeError: %s' % e) - diff --git a/traits/tests/test_property_notifications.py b/traits/tests/test_property_notifications.py index 3499ce314..81a8f8f0e 100644 --- a/traits/tests/test_property_notifications.py +++ b/traits/tests/test_property_notifications.py @@ -16,65 +16,68 @@ from ..api import HasTraits, Property -class Test ( HasTraits ): - __traits__ = { } +class Test(HasTraits): - def __value_get ( self ): - return self.__dict__.get( '_value', 0 ) + __traits__ = {} - def __value_set ( self, value ): - old_value = self.__dict__.get( '_value', 0 ) + def __value_get(self): + return self.__dict__.get('_value', 0) + + def __value_set(self, value): + old_value = self.__dict__.get('_value', 0) if value != old_value: self._value = value - self.trait_property_changed( 'value', old_value, value ) + self.trait_property_changed('value', old_value, value) - __traits__[ 'value' ] = Property( __value_get, __value_set ) + __traits__['value'] = Property(__value_get, __value_set) -class Test_1 ( Test ): +class Test_1 (Test): - def value_changed ( self, value ): + def value_changed(self, value): print 'value_changed:', value -class Test_2 ( Test ): +class Test_2 (Test): - def anytrait_changed ( self, name, value ): - print 'anytrait_changed for %s: %s' % ( name, value ) + def anytrait_changed(self, name, value): + print 'anytrait_changed for %s: %s' % (name, value) -class Test_3 ( Test_2 ): +class Test_3 (Test_2): - def value_changed ( self, value ): + def value_changed(self, value): print 'value_changed:', value -def on_value_changed ( value ): +def on_value_changed(value): print 'on_value_changed:', value -def on_anyvalue_changed ( value ): + +def on_anyvalue_changed(value): print 'on_anyvalue_changed:', value + def test_property_notifications(): Test_1().value = 'test 1' Test_2().value = 'test 2' Test_3().value = 'test 3' test_4 = Test() - test_4.on_trait_change( on_value_changed, 'value' ) + test_4.on_trait_change(on_value_changed, 'value') test_4.value = 'test 4' test_5 = Test() - test_5.on_trait_change( on_anyvalue_changed ) + test_5.on_trait_change(on_anyvalue_changed) test_5.value = 'test 5' test_6 = Test() - test_6.on_trait_change( on_value_changed, 'value' ) - test_6.on_trait_change( on_anyvalue_changed ) + test_6.on_trait_change(on_value_changed, 'value') + test_6.on_trait_change(on_anyvalue_changed) test_6.value = 'test 6' test_7 = Test_3() - test_7.on_trait_change( on_value_changed, 'value' ) - test_7.on_trait_change( on_anyvalue_changed ) + test_7.on_trait_change(on_value_changed, 'value') + test_7.on_trait_change(on_anyvalue_changed) test_7.value = 'test 7' diff --git a/traits/tests/test_protocols_usage.py b/traits/tests/test_protocols_usage.py index 07e7785d4..afbfa1dc2 100644 --- a/traits/tests/test_protocols_usage.py +++ b/traits/tests/test_protocols_usage.py @@ -1,4 +1,4 @@ -#------------------------------------------------------------------------------- +#------------------------------------------------------------------------------ # # Copyright (c) 2007, Enthought, Inc. # All rights reserved. @@ -10,7 +10,7 @@ # # Thanks for using Enthought open source! # -#------------------------------------------------------------------------------- +#------------------------------------------------------------------------------ """ Tests for protocols usage. """ @@ -18,11 +18,14 @@ # Standard library imports. -import pickle, unittest, os, sys +import os +import pickle +import sys +import unittest # Enthought library imports. from ..api import (Bool, HasTraits, Int, Interface, Str, Adapter, adapts, - Property) + Property) # NOTE: There is a File class in apptools.io module, but since we want to # eliminate dependencies of Traits on other modules, we create another @@ -64,7 +67,8 @@ class Person(HasTraits): """ A person! """ name = Str - age = Int + age = Int + class ProtocolsUsageTestCase(unittest.TestCase): """ Tests for protocols usage. """ @@ -205,7 +209,6 @@ class ISaveable(Interface): def save(self, output_stream): """ Save the object to an output stream. """ - class HasTraitsToISaveableAdapter(Adapter): """ An adapter from 'HasTraits' to 'ISaveable'. """ @@ -247,7 +250,7 @@ def _set_dirty(self): return # Create some people! - fred = Person(name='fred', age=42) + fred = Person(name='fred', age=42) wilma = Person(name='wilma', age=35) fred_saveable = ISaveable(fred) @@ -272,8 +275,8 @@ def _set_dirty(self): # Clean up. for path in ['fred.pickle', 'wilma.pickle']: - if os.access(path, os.W_OK): - os.remove(path) + if os.access(path, os.W_OK): + os.remove(path) return diff --git a/traits/tests/test_range.py b/traits/tests/test_range.py index 68e746c06..94ebd115f 100644 --- a/traits/tests/test_range.py +++ b/traits/tests/test_range.py @@ -1,5 +1,3 @@ -#------------------------------------------------------------------------------- -# # Copyright (c) 2007, Enthought, Inc. # All rights reserved. # @@ -7,10 +5,6 @@ # license included in /LICENSE.txt and may be redistributed only # under the conditions described in the aforementioned license. The license # is also available online at http://www.enthought.com/licenses/BSD.txt -# -# Thanks for using Enthought open source! -# -#------------------------------------------------------------------------------- from __future__ import absolute_import @@ -30,7 +24,7 @@ def _r_changed(self, old, new): self.r_copied_on_change = str(self.r) if (self.r % 10) > 0: - self.r += 10-(self.r % 10) + self.r += 10 - (self.r % 10) class WithLargeIntRange(HasTraits): @@ -104,5 +98,3 @@ def test_dynamic_events(self): with self.assertRaises(TraitError): obj.r = obj.high self.assertEqual(obj.r, 5) - -### EOF diff --git a/traits/tests/test_regression.py b/traits/tests/test_regression.py index eb841037f..11eb9e49c 100644 --- a/traits/tests/test_regression.py +++ b/traits/tests/test_regression.py @@ -44,12 +44,13 @@ def _init_trait_listeners(self): """ for name in ['y', '_on_dummy1_x']: data = self.__class__.__listener_traits__[name] - getattr( self, '_init_trait_%s_listener' % data[0] )( name, *data ) + getattr(self, '_init_trait_%s_listener' % data[0])(name, *data) class Presenter(HasTraits): obj = Instance(Dummy) y = Property(Int(), depends_on='obj.x') + def _get_y(self): return self.obj.x diff --git a/traits/tests/test_rich_compare.py b/traits/tests/test_rich_compare.py index 934e97c66..fa332eca3 100644 --- a/traits/tests/test_rich_compare.py +++ b/traits/tests/test_rich_compare.py @@ -1,4 +1,4 @@ -#------------------------------------------------------------------------------- +#------------------------------------------------------------------------------ # # Copyright (c) 2007, Enthought, Inc. # All rights reserved. @@ -10,7 +10,7 @@ # # Thanks for using Enthought open source! # -#------------------------------------------------------------------------------- +#------------------------------------------------------------------------------ from __future__ import absolute_import @@ -18,12 +18,15 @@ from ..api import HasTraits, Any, Str + class IdentityCompare(HasTraits): bar = Any(rich_compare=False) + class RichCompare(HasTraits): bar = Any(rich_compare=True) + class RichCompareTests: def bar_changed(self, object, trait, old, new): @@ -41,122 +44,119 @@ def reset_change_tracker(self): self.changed_count = 0 def check_tracker(self, object, trait, old, new, count): - self.failUnlessEqual( count, self.changed_count ) - self.failUnless( object is self.changed_object ) - self.failUnlessEqual( trait, self.changed_trait ) - self.failUnless( old is self.changed_old ) - self.failUnless( new is self.changed_new ) + self.failUnlessEqual(count, self.changed_count) + self.failUnless(object is self.changed_object) + self.failUnlessEqual(trait, self.changed_trait) + self.failUnless(old is self.changed_old) + self.failUnless(new is self.changed_new) return def test_id_first_assignment(self): ic = IdentityCompare() - ic.on_trait_change( self.bar_changed, 'bar' ) + ic.on_trait_change(self.bar_changed, 'bar') self.reset_change_tracker() default_value = ic.bar ic.bar = self.a - self.check_tracker( ic, 'bar', default_value, self.a, 1 ) + self.check_tracker(ic, 'bar', default_value, self.a, 1) return def test_rich_first_assignment(self): rich = RichCompare() - rich.on_trait_change( self.bar_changed, 'bar' ) + rich.on_trait_change(self.bar_changed, 'bar') self.reset_change_tracker() default_value = rich.bar rich.bar = self.a - self.check_tracker( rich, 'bar', default_value, self.a, 1 ) + self.check_tracker(rich, 'bar', default_value, self.a, 1) return def test_id_same_object(self): ic = IdentityCompare() - ic.on_trait_change( self.bar_changed, 'bar' ) + ic.on_trait_change(self.bar_changed, 'bar') self.reset_change_tracker() default_value = ic.bar ic.bar = self.a - self.check_tracker( ic, 'bar', default_value, self.a, 1 ) + self.check_tracker(ic, 'bar', default_value, self.a, 1) ic.bar = self.a - self.check_tracker( ic, 'bar', default_value, self.a, 1 ) - + self.check_tracker(ic, 'bar', default_value, self.a, 1) return def test_rich_same_object(self): rich = RichCompare() - rich.on_trait_change( self.bar_changed, 'bar' ) + rich.on_trait_change(self.bar_changed, 'bar') self.reset_change_tracker() default_value = rich.bar rich.bar = self.a - self.check_tracker( rich, 'bar', default_value, self.a, 1 ) + self.check_tracker(rich, 'bar', default_value, self.a, 1) rich.bar = self.a - self.check_tracker( rich, 'bar', default_value, self.a, 1 ) + self.check_tracker(rich, 'bar', default_value, self.a, 1) return def test_id_different_object(self): ic = IdentityCompare() - ic.on_trait_change( self.bar_changed, 'bar' ) + ic.on_trait_change(self.bar_changed, 'bar') self.reset_change_tracker() default_value = ic.bar ic.bar = self.a - self.check_tracker( ic, 'bar', default_value, self.a, 1 ) + self.check_tracker(ic, 'bar', default_value, self.a, 1) ic.bar = self.different_from_a - self.check_tracker( ic, 'bar', self.a, self.different_from_a, 2 ) - + self.check_tracker(ic, 'bar', self.a, self.different_from_a, 2) return def test_rich_different_object(self): rich = RichCompare() - rich.on_trait_change( self.bar_changed, 'bar' ) + rich.on_trait_change(self.bar_changed, 'bar') self.reset_change_tracker() default_value = rich.bar rich.bar = self.a - self.check_tracker( rich, 'bar', default_value, self.a, 1 ) + self.check_tracker(rich, 'bar', default_value, self.a, 1) rich.bar = self.different_from_a - self.check_tracker( rich, 'bar', self.a, self.different_from_a, 2 ) + self.check_tracker(rich, 'bar', self.a, self.different_from_a, 2) return def test_id_different_object_same_as(self): ic = IdentityCompare() - ic.on_trait_change( self.bar_changed, 'bar' ) + ic.on_trait_change(self.bar_changed, 'bar') self.reset_change_tracker() default_value = ic.bar ic.bar = self.a - self.check_tracker( ic, 'bar', default_value, self.a, 1 ) + self.check_tracker(ic, 'bar', default_value, self.a, 1) ic.bar = self.same_as_a - self.check_tracker( ic, 'bar', self.a, self.same_as_a, 2 ) - + self.check_tracker(ic, 'bar', self.a, self.same_as_a, 2) return def test_rich_different_object_same_as(self): rich = RichCompare() - rich.on_trait_change( self.bar_changed, 'bar' ) + rich.on_trait_change(self.bar_changed, 'bar') self.reset_change_tracker() default_value = rich.bar rich.bar = self.a - self.check_tracker( rich, 'bar', default_value, self.a, 1 ) + self.check_tracker(rich, 'bar', default_value, self.a, 1) # Values of a and same_as_a are the same and should therefore not # be considered a change. rich.bar = self.same_as_a - self.check_tracker( rich, 'bar', default_value, self.a, 1 ) + self.check_tracker(rich, 'bar', default_value, self.a, 1) return @@ -172,30 +172,20 @@ def __eq__(self, other): # Not required, but a good idea to make __eq__ and __ne__ compatible return self.name == other.name + class RichCompareHasTraitsTestCase(unittest.TestCase, RichCompareTests): def setUp(self): self.a = Foo(name='a') self.same_as_a = Foo(name='a') self.different_from_a = Foo(name='not a') - -# print '\na' -# self.a.print_traits() -# print '\nsame_as_a' -# self.same_as_a.print_traits() -# print '\ndifferent_from_a' -# self.different_from_a.print_traits() - return def test_assumptions(self): - self.failIf( self.a is self.same_as_a ) - self.failIf( self.a is self.different_from_a ) + self.failIf(self.a is self.same_as_a) + self.failIf(self.a is self.different_from_a) - self.failUnless( self.a.name == self.same_as_a.name ) - self.failIf( self.a.name == self.different_from_a.name ) + self.failUnless(self.a.name == self.same_as_a.name) + self.failIf(self.a.name == self.different_from_a.name) return - - ### EOF - diff --git a/traits/tests/test_special_event_handlers.py b/traits/tests/test_special_event_handlers.py index dfba240fc..ce1a437d5 100644 --- a/traits/tests/test_special_event_handlers.py +++ b/traits/tests/test_special_event_handlers.py @@ -3,33 +3,33 @@ from traits.api import Any, HasStrictTraits, Str -class TestSpecialEvent( unittest.TestCase ): +class TestSpecialEvent(unittest.TestCase): """ Test demonstrating special change events using the 'event' metadata. """ def setUp(self): self.change_events = [] - self.foo = Foo( test=self ) + self.foo = Foo(test=self) def test_events(self): self.foo.val = 'CHANGE' values = ['CHANGE'] - self.failUnlessEqual( self.change_events, values) + self.failUnlessEqual(self.change_events, values) def test_instance_events(self): foo = self.foo - foo.add_trait('val2',Str(event='the_trait')) + foo.add_trait('val2', Str(event='the_trait')) foo.val2 = 'CHANGE2' values = ['CHANGE2'] - self.failUnlessEqual( self.change_events, values) + self.failUnlessEqual(self.change_events, values) class Foo(HasStrictTraits): val = Str(event='the_trait') test = Any(None) - - def _the_trait_changed(self,new): + + def _the_trait_changed(self, new): if self.test is not None: self.test.change_events.append(new) diff --git a/traits/tests/test_static_notifiers.py b/traits/tests/test_static_notifiers.py index 0edfd6dec..f1bb60c0f 100644 --- a/traits/tests/test_static_notifiers.py +++ b/traits/tests/test_static_notifiers.py @@ -1,65 +1,80 @@ +############################################################################## +# Copyright 2014 Enthought, Inc. +############################################################################## + """ Tests for the static notifiers. """ from traits.api import Float, HasTraits from traits.testing.unittest_tools import unittest from traits import trait_notifiers - calls_0 = [] + + class StaticNotifiers0(HasTraits): ok = Float + def _ok_changed(): calls_0.append(True) fail = Float + def _fail_changed(): raise Exception('error') class StaticNotifiers1(HasTraits): ok = Float + def _ok_changed(self): if not hasattr(self, 'calls'): self.calls = [] self.calls.append(True) fail = Float + def _fail_changed(self): raise Exception('error') class StaticNotifiers2(HasTraits): ok = Float + def _ok_changed(self, new): if not hasattr(self, 'calls'): self.calls = [] self.calls.append(new) fail = Float + def _fail_changed(self, new): raise Exception('error') class StaticNotifiers3(HasTraits): ok = Float + def _ok_changed(self, old, new): if not hasattr(self, 'calls'): self.calls = [] self.calls.append((old, new)) fail = Float + def _fail_changed(self, old, new): raise Exception('error') class StaticNotifiers4(HasTraits): ok = Float + def _ok_changed(self, name, old, new): if not hasattr(self, 'calls'): self.calls = [] self.calls.append((name, old, new)) fail = Float + def _fail_changed(self, name, old, new): raise Exception('error') @@ -68,8 +83,6 @@ class TestNotifiers(unittest.TestCase): """ Tests for the static notifiers, and the "anytrait" static notifiers. """ - #### 'TestCase' protocol ################################################## - def setUp(self): self.exceptions = [] trait_notifiers.push_exception_handler(self._handle_exception) @@ -77,13 +90,9 @@ def setUp(self): def tearDown(self): trait_notifiers.pop_exception_handler() - #### Private protocol ##################################################### - def _handle_exception(self, obj, name, old, new): self.exceptions.append((obj, name, old, new)) - #### Tests ################################################################ - def test_static_notifiers_0(self): obj = StaticNotifiers0(ok=2) obj.ok = 3 diff --git a/traits/tests/test_str_handler.py b/traits/tests/test_str_handler.py index bc72d5a2c..a46c01661 100644 --- a/traits/tests/test_str_handler.py +++ b/traits/tests/test_str_handler.py @@ -1,4 +1,4 @@ -#------------------------------------------------------------------------------- +#------------------------------------------------------------------------------ # # Copyright (c) 2007, Enthought, Inc. # All rights reserved. @@ -10,7 +10,7 @@ # # Thanks for using Enthought open source! # -#------------------------------------------------------------------------------- +#------------------------------------------------------------------------------ from __future__ import absolute_import @@ -19,6 +19,7 @@ from ..api import HasTraits, Trait, TraitError, TraitHandler from ..trait_base import strx + # Validation via function def validator(object, name, value): if isinstance(value, basestring): @@ -30,17 +31,18 @@ def validator(object, name, value): else: raise TraitError + # Validation via Handler class MyHandler(TraitHandler): - def validate ( self, object, name, value ): + def validate(self, object, name, value): #print 'myvalidate "%s" %s' % (value, type(value)) try: - value = strx( value ) + value = strx(value) if value.find('fail') < 0: return value except: pass - self.error( object, name, value ) + self.error(object, name, value) return @@ -48,23 +50,26 @@ def info(self): msg = "a string not containing the character sequence 'fail'" return msg + class Foo(HasTraits): s = Trait('', validator) + class Bar(HasTraits): - s = Trait('', MyHandler() ) + s = Trait('', MyHandler()) + class StrHandlerCase(unittest.TestCase): def test_validator_function(self): f = Foo() - self.failUnlessEqual( f.s, '' ) + self.failUnlessEqual(f.s, '') f.s = 'ok' - self.failUnlessEqual( f.s, 'ok' ) + self.failUnlessEqual(f.s, 'ok') - self.failUnlessRaises( TraitError, setattr, f, 's', 'should fail.') - self.failUnlessEqual( f.s, 'ok' ) + self.failUnlessRaises(TraitError, setattr, f, 's', 'should fail.') + self.failUnlessEqual(f.s, 'ok') return @@ -75,10 +80,9 @@ def test_validator_handler(self): b.s = 'ok' self.failUnlessEqual(b.s, 'ok') - self.failUnlessRaises( TraitError, setattr, b, 's', 'should fail.') - self.failUnlessEqual( b.s, 'ok') + self.failUnlessRaises(TraitError, setattr, b, 's', 'should fail.') + self.failUnlessEqual(b.s, 'ok') return ### EOF - diff --git a/traits/tests/test_target.py b/traits/tests/test_target.py index cf40b2e68..e773e46e2 100644 --- a/traits/tests/test_target.py +++ b/traits/tests/test_target.py @@ -1,4 +1,4 @@ -#------------------------------------------------------------------------------- +#------------------------------------------------------------------------------ # # Copyright (c) 2010, Enthought, Inc. # All rights reserved. @@ -10,10 +10,7 @@ # # Thanks for using Enthought open source! # -#------------------------------------------------------------------------------- - - - +#------------------------------------------------------------------------------ """ Test whether HasTraits objects with cycles can be garbage collected. """ @@ -23,6 +20,7 @@ # Enthought library imports from traits.api import HasTraits, Instance, Int + class TestCase(unittest.TestCase): """ Tests the 'target' argument for on_traits_change. """ @@ -37,6 +35,7 @@ class Test(HasTraits): # Set up to count changes in i self.count = 0 + def count_notifies(): self.count += 1 obj.on_trait_change(count_notifies, "i", target=target) @@ -64,6 +63,7 @@ class Parent(HasTraits): # Set up to count changes in i self.count = 0 + def count_notifies(): self.count += 1 parent.on_trait_change(count_notifies, "child:i", target=target) @@ -78,11 +78,3 @@ def count_notifies(): if __name__ == '__main__': unittest.main() - - - - - - - - diff --git a/traits/tests/test_trait_change_event_tracer.py b/traits/tests/test_trait_change_event_tracer.py index 388ff54c2..89a58451e 100644 --- a/traits/tests/test_trait_change_event_tracer.py +++ b/traits/tests/test_trait_change_event_tracer.py @@ -98,7 +98,7 @@ def _on_foo_baz_changed(obj, name, old, new): ] self.assertEqual(self.post_change_events, expected_post_events) - self.assertEqual(self.exceptions, [None]*4) + self.assertEqual(self.exceptions, [None] * 4) # Deactivate the tracer; it should not be called anymore. trait_notifiers.clear_change_event_tracers() diff --git a/traits/tests/test_trait_cycle.py b/traits/tests/test_trait_cycle.py index 8d5de1809..61f121050 100644 --- a/traits/tests/test_trait_cycle.py +++ b/traits/tests/test_trait_cycle.py @@ -1,4 +1,4 @@ -#------------------------------------------------------------------------------- +#------------------------------------------------------------------------------ # # Copyright (c) 2007, Enthought, Inc. # All rights reserved. @@ -10,10 +10,7 @@ # # Thanks for using Enthought open source! # -#------------------------------------------------------------------------------- - - - +#------------------------------------------------------------------------------ """ Test whether HasTraits objects with cycles can be garbage collected. """ @@ -26,6 +23,7 @@ # Enthought library imports from ..api import HasTraits, Any, DelegatesTo, Instance, Int + class TestCase(unittest.TestCase): def _simple_cycle_helper(self, foo_class): """ Can the garbage collector clean up a cycle with traits objects? @@ -34,10 +32,10 @@ def _simple_cycle_helper(self, foo_class): # Create two Foo objects that refer to each other. first = foo_class() second = foo_class(child=first) - first.child=second + first.child = second # get their ids - foo_ids = [id(first), id(second)] + foo_ids = [id(first), id(second)] # delete the items so that they can be garbage collected del first, second @@ -56,7 +54,7 @@ def test_simple_cycle_oldstyle_class(self): """ Can the garbage collector clean up a cycle with old style class? """ class Foo: - def __init__(self,child=None): + def __init__(self, child=None): self.child = child self._simple_cycle_helper(Foo) @@ -65,7 +63,7 @@ def test_simple_cycle_newstyle_class(self): """ Can the garbage collector clean up a cycle with new style class? """ class Foo(object): - def __init__(self,child=None): + def __init__(self, child=None): self.child = child self._simple_cycle_helper(Foo) @@ -91,13 +89,14 @@ class Foo(HasTraits): foo = Foo() - # It seems like foo sometimes has not finished construction yet, so the - # frame found by referrers is not _exactly_ the same as Foo(). For more - # information, see the gc doc: http://docs.python.org/lib/module-gc.html + # It seems like foo sometimes has not finished construction yet, so + # the frame found by referrers is not _exactly_ the same as Foo(). For + # more information, see the gc doc: http://docs.python.org/lib/module- + # gc.html # - # The documentation says that this (get_referrers) should be used for no - # purpose other than debugging, so this is really not a good way to test - # the code. + # The documentation says that this (get_referrers) should be used for + # no purpose other than debugging, so this is really not a good way to + # test the code. time.sleep(0.1) referrers = gc.get_referrers(foo.__dict__) @@ -113,7 +112,6 @@ class Base(HasTraits): i = Int - class Delegates(HasTraits): """ Object that delegates. """ @@ -131,7 +129,7 @@ class Delegates(HasTraits): gc.collect(2) # See if we still have a Delegates - ds = [ obj for obj in gc.get_objects() if isinstance(obj, Delegates) ] + ds = [obj for obj in gc.get_objects() if isinstance(obj, Delegates)] self.assert_(ds == []) if __name__ == '__main__': diff --git a/traits/tests/test_trait_default_initializer.py b/traits/tests/test_trait_default_initializer.py index fea9cf539..c57d1a7ab 100644 --- a/traits/tests/test_trait_default_initializer.py +++ b/traits/tests/test_trait_default_initializer.py @@ -1,4 +1,4 @@ -#------------------------------------------------------------------------------- +#------------------------------------------------------------------------------ # # Copyright (c) 2013, Enthought, Inc. # All rights reserved. @@ -10,7 +10,7 @@ # # Thanks for using Enthought open source! # -#------------------------------------------------------------------------------- +#------------------------------------------------------------------------------ from __future__ import absolute_import @@ -27,6 +27,7 @@ class Foo(HasTraits): def _bar_default(self): return 4 + class TestTraitDefaultInitializer(unittest.TestCase): """ Test basic usage of the default method. diff --git a/traits/tests/test_trait_list_dict.py b/traits/tests/test_trait_list_dict.py index dbf7added..1bf617d38 100644 --- a/traits/tests/test_trait_list_dict.py +++ b/traits/tests/test_trait_list_dict.py @@ -1,4 +1,9 @@ -""" Test the persistence behavior of TraitListObjects, TraitDictObjects and TraitSetObjects. +############################################################################## +# Copyright 2014 Enthought, Inc. +############################################################################## + +""" Test the persistence behavior of TraitListObjects, TraitDictObjects and +TraitSetObjects. """ from __future__ import absolute_import @@ -21,6 +26,7 @@ class A(HasTraits): def _receive_events(self, object, name, old, new): self.events.append((name, new)) + class B(HasTraits): dict = Dict(Str, Instance(A)) @@ -36,6 +42,7 @@ def test_trait_list_object_persists(): list2 = loads(dumps(list)) assert list2.object() is None + def test_trait_dict_object_persists(): a = A() dict = loads(dumps(a.adict)) @@ -47,6 +54,7 @@ def test_trait_dict_object_persists(): dict2 = loads(dumps(dict)) assert dict2.object() is None + def test_trait_set_object_persists(): a = A() set = loads(dumps(a.aset)) @@ -58,6 +66,7 @@ def test_trait_set_object_persists(): set2 = loads(dumps(set)) assert set2.object() is None + def test_trait_list_object_copies(): a = A() list = copy.deepcopy(a.alist) @@ -70,6 +79,7 @@ def test_trait_list_object_copies(): list2.append(30) assert list2.object() is None + def test_trait_dict_object_copies(): a = A() dict = copy.deepcopy(a.adict) @@ -82,6 +92,7 @@ def test_trait_dict_object_copies(): dict2['key2'] = 20 assert dict2.object() is None + def test_trait_set_object_copies(): a = A() set1 = copy.deepcopy(a.aset) @@ -98,6 +109,7 @@ def test_trait_set_object_copies(): # Should not raise an AttributeError: set3.remove(20) + def test_pickle_whole(): a = A() loads(dumps(a)) diff --git a/traits/tests/test_trait_types.py b/traits/tests/test_trait_types.py index 758bd4eed..a4af256f8 100644 --- a/traits/tests/test_trait_types.py +++ b/traits/tests/test_trait_types.py @@ -1,5 +1,3 @@ -#------------------------------------------------------------------------------- -# # Unit test case for testing trait types created by subclassing TraitType. # # Written by: David C. Morrill @@ -16,7 +14,6 @@ # # Thanks for using Enthought open source! # -#------------------------------------------------------------------------------- """ Unit test case for testing trait types created by subclassing TraitType. """ @@ -25,7 +22,8 @@ from traits.api import Float, TraitType -class TraitTypesTest ( unittest.TestCase ): + +class TraitTypesTest(unittest.TestCase): def test_traits_shared_transient(self): # Regression test for a bug in traits where the same _metadata @@ -63,4 +61,3 @@ def test_numpy_validators_loaded_if_numpy_present(self): # Run the unit tests (if invoked from the command line): if __name__ == '__main__': unittest.main() - diff --git a/traits/tests/test_traits.py b/traits/tests/test_traits.py index 6b31c4556..5a8d124c6 100644 --- a/traits/tests/test_traits.py +++ b/traits/tests/test_traits.py @@ -10,12 +10,9 @@ # # Author: David C. Morrill Date: 03/20/2003 Description: Unit Test Case for the # Traits Package -# ------------------------------------------------------------------------------ - -#------------------------------------------------------------------------------- -# Imports: -#------------------------------------------------------------------------------- +#------------------------------------------------------------------------------ +# Imports from __future__ import absolute_import import sys @@ -23,13 +20,12 @@ from traits.testing.unittest_tools import unittest from ..api import (Any, CFloat, CInt, CLong, Delegate, Float, HasTraits, - Instance, Int, List, Long, Str, Trait, TraitError, TraitList, - TraitPrefixList, TraitPrefixMap, TraitRange, Tuple, pop_exception_handler, - push_exception_handler) + Instance, Int, List, Long, Str, Trait, TraitError, + TraitList, TraitPrefixList, TraitPrefixMap, TraitRange, + Tuple, pop_exception_handler, push_exception_handler) -#------------------------------------------------------------------------------- # Base unit test classes: -#------------------------------------------------------------------------------- + class BaseTest(object): @@ -59,13 +55,14 @@ def test_assignment(self): for value in self._bad_values: self.assertRaises(TraitError, self.assign, value) + class test_base2(unittest.TestCase): def indexed_assign(self, list, index, value): - list[ index ] = value + list[index] = value def indexed_range_assign(self, list, index1, index2, value): - list[ index1: index2 ] = value + list[index1: index2] = value def extended_slice_assign(self, list, index1, index2, step, value): list[index1:index2:step] = value @@ -74,11 +71,11 @@ def extended_slice_assign(self, list, index1, index2, step, value): # called by the tester directly, as nose looks for all tests, regardless of # the handler at the bottom of this file. def check_values(self, name, default_value, good_values, bad_values, - actual_values = None, mapped_values = None): + actual_values=None, mapped_values=None): obj = self.obj try: # Make sure the default value is correct: - msg = 'default value' + msg = 'default value' value = default_value self.assertEqual(getattr(obj, name), value) @@ -86,13 +83,13 @@ def check_values(self, name, default_value, good_values, bad_values, if actual_values is None: actual_values = good_values msg = 'legal values' - i = 0 + i = 0 for value in good_values: setattr(obj, name, value) self.assertEqual(getattr(obj, name), actual_values[i]) if mapped_values is not None: self.assertEqual(getattr(obj, name + '_'), - mapped_values[i]) + mapped_values[i]) i += 1 # Iterate over all illegal values being tested: @@ -104,48 +101,39 @@ def check_values(self, name, default_value, good_values, bad_values, msg, value, value.__class__.__name__, self.__class__.__name__) raise -#------------------------------------------------------------------------------- -# Trait that can have any value: -#------------------------------------------------------------------------------- class AnyTrait(HasTraits): - - # Trait definitions: value = Any + class AnyTraitTest(BaseTest, unittest.TestCase): obj = AnyTrait() _default_value = None - _good_values = [10.0, 'ten', u'ten', [10], {'ten': 10},(10,), None, 1j] + _good_values = [10.0, 'ten', u'ten', [10], {'ten': 10}, (10,), None, 1j] _mapped_values = [] - _bad_values = [] + _bad_values = [] -#------------------------------------------------------------------------------- -# Trait that can only have 'int' values: -#------------------------------------------------------------------------------- class CoercibleIntTrait(HasTraits): - - # Trait definitions: value = CInt(99) -class IntTrait(HasTraits): - # Trait definitions: +class IntTrait(HasTraits): value = Int(99) + class CoercibleIntTest(AnyTraitTest): obj = CoercibleIntTrait() _default_value = 99 - _good_values = [10, -10, 10L, -10L, 10.1, -10.1, '10', '-10', u'10', - u'-10'] - _bad_values = ['10L', '-10L', '10.1', '-10.1', u'10L', u'-10L', u'10.1', - u'-10.1', 'ten', u'ten', [10], {'ten': 10},(10,), None, - 1j] + _good_values = [10, -10, 10L, -10L, 10.1, -10.1, '10', '-10', u'10', + u'-10'] + _bad_values = ['10L', '-10L', '10.1', '-10.1', u'10L', u'-10L', u'10.1', + u'-10.1', 'ten', u'ten', [10], {'ten': 10}, (10, ), None, + 1j] def coerce(self, value): try: @@ -156,33 +144,28 @@ def coerce(self, value): except: return int(long(value)) + class IntTest(AnyTraitTest): obj = IntTrait() _default_value = 99 - _good_values = [10, -10, 10L, -10L] - _bad_values = ['ten', u'ten', [10], {'ten': 10},(10,), None, 1j, - 10.1, -10.1, '10L', '-10L', '10.1', '-10.1', u'10L', - u'-10L', u'10.1', u'-10.1', '10', '-10', u'10', u'-10'] + _good_values = [10, -10, 10L, -10L] + _bad_values = ['ten', u'ten', [10], {'ten': 10}, (10,), None, 1j, + 10.1, -10.1, '10L', '-10L', '10.1', '-10.1', u'10L', + u'-10L', u'10.1', u'-10.1', '10', '-10', u'10', u'-10'] try: import numpy as np except ImportError: pass else: - if sys.version_info[0] < 3: - _good_values.extend([ - np.int64(10),np.int64(-10), - np.int32(10),np.int32(-10), - np.int_(10),np.int_(-10) - ]) - _bad_values.extend([ - ]) - else: - #TODO: status of numpy-ints is unclear in python 3! - pass - + _good_values.extend([ + np.int64(10), np.int64(-10), + np.int32(10), np.int32(-10), + np.int_(10), np.int_(-10) + ]) + def coerce(self, value): try: return int(value) @@ -192,30 +175,26 @@ def coerce(self, value): except: return int(long(value)) -#------------------------------------------------------------------------------- -# Trait that can only have 'long' values: -#------------------------------------------------------------------------------- class CoercibleLongTrait(HasTraits): - - # Trait definitions: value = CLong(99L) -class LongTrait(HasTraits): - # Trait definitions: +class LongTrait(HasTraits): value = Long(99L) + class CoercibleLongTest(AnyTraitTest): obj = CoercibleLongTrait() _default_value = 99L - _good_values = [10, -10, 10L, -10L, 10.1, -10.1, '10', '-10', u'10', u'-10'] + _good_values = [ + 10, -10, 10L, -10L, 10.1, -10.1, '10', '-10', u'10', u'-10'] if sys.version_info[0] < 3: - _good_values.extend(['10L','-10L',u'10L',u'-10L']) - _bad_values = ['10.1', '-10.1', u'10.1', u'-10.1', 'ten', u'ten', [10], - [10l], {'ten': 10},(10,),(10L,), None, 1j] + _good_values.extend(['10L', '-10L', u'10L', u'-10L']) + _bad_values = ['10.1', '-10.1', u'10.1', u'-10.1', 'ten', u'ten', [10], + [10l], {'ten': 10}, (10,), (10L,), None, 1j] def coerce(self, value): try: @@ -223,16 +202,17 @@ def coerce(self, value): except: return long(float(value)) + class LongTest(AnyTraitTest): obj = LongTrait() _default_value = 99L - _good_values = [10, -10, 10L, -10L] - _bad_values = ['ten', u'ten', [10], [10l], {'ten': 10},(10,),(10L,), - None, 1j, 10.1, -10.1, '10', '-10', '10L', '-10L', '10.1', - '-10.1', u'10', u'-10', u'10L', u'-10L', u'10.1', - u'-10.1'] + _good_values = [10, -10, 10L, -10L] + _bad_values = ['ten', u'ten', [10], [10l], {'ten': 10}, (10, ), (10L,), + None, 1j, 10.1, -10.1, '10', '-10', '10L', '-10L', '10.1', + '-10.1', u'10', u'-10', u'10L', u'-10L', u'10.1', + u'-10.1'] def coerce(self, value): try: @@ -241,29 +221,22 @@ def coerce(self, value): return long(float(value)) -#------------------------------------------------------------------------------- -# Trait that can only have 'float' values: -#------------------------------------------------------------------------------- - class CoercibleFloatTrait(HasTraits): - - # Trait definitions: value = CFloat(99.0) -class FloatTrait(HasTraits): - # Trait definitions: +class FloatTrait(HasTraits): value = Float(99.0) -class CoercibleFloatTest(AnyTraitTest): +class CoercibleFloatTest(AnyTraitTest): obj = CoercibleFloatTrait() _default_value = 99.0 - _good_values = [10, -10, 10L, -10L, 10.1, -10.1, '10', '-10', '10.1', - '-10.1', u'10', u'-10', u'10.1', u'-10.1'] - _bad_values = ['10L', '-10L', u'10L', u'-10L', 'ten', u'ten', [10], - {'ten': 10},(10,), None, 1j] + _good_values = [10, -10, 10L, -10L, 10.1, -10.1, '10', '-10', '10.1', + '-10.1', u'10', u'-10', u'10.1', u'-10.1'] + _bad_values = ['10L', '-10L', u'10L', u'-10L', 'ten', u'ten', [10], + {'ten': 10}, (10, ), None, 1j] def coerce(self, value): try: @@ -271,20 +244,20 @@ def coerce(self, value): except: return float(long(value)) -class FloatTest(AnyTraitTest): +class FloatTest(AnyTraitTest): obj = FloatTrait() _default_value = 99.0 - _good_values = [10, -10, 10.1, -10.1] - _bad_values = ['ten', u'ten', [10], {'ten': 10},(10,), None, - 1j, '10', '-10', '10L', '-10L', '10.1', '-10.1', u'10', - u'-10', u'10L', u'-10L', u'10.1', u'-10.1'] + _good_values = [10, -10, 10.1, -10.1] + _bad_values = ['ten', u'ten', [10], {'ten': 10}, (10,), None, + 1j, '10', '-10', '10L', '-10L', '10.1', '-10.1', u'10', + u'-10', u'10L', u'-10L', u'10.1', u'-10.1'] if sys.version_info[0] < 3: - # 2to3 will remove the L suffix and therfore make them actually good ones! - _bad_values.extend([-10L,10L]) - + # 2to3 will remove the L suffix and therfore make them actually good + # ones! + _bad_values.extend([-10L, 10L]) def coerce(self, value): try: @@ -292,24 +265,22 @@ def coerce(self, value): except: return float(long(value)) -#------------------------------------------------------------------------------- # Trait that can only have 'complex'(i.e. imaginary) values: -#------------------------------------------------------------------------------- + class ImaginaryValueTrait(HasTraits): + value = Trait(99.0 - 99.0j) - # Trait definitions: - value = Trait(99.0-99.0j) class ImaginaryValueTest(AnyTraitTest): obj = ImaginaryValueTrait() - _default_value = 99.0-99.0j - _good_values = [10, -10, 10L, -10L, 10.1, -10.1, '10', '-10', '10.1', - '-10.1', 10j, 10+10j, 10-10j, 10.1j, 10.1+10.1j, - 10.1-10.1j, '10j', '10+10j', '10-10j'] - _bad_values = [u'10L', u'-10L', 'ten', [10], {'ten': 10},(10,), None] + _default_value = 99.0 - 99.0j + _good_values = [10, -10, 10L, -10L, 10.1, -10.1, '10', '-10', '10.1', + '-10.1', 10j, 10 + 10j, 10 - 10j, 10.1j, 10.1 + 10.1j, + 10.1 - 10.1j, '10j', '10+10j', '10-10j'] + _bad_values = [u'10L', u'-10L', 'ten', [10], {'ten': 10}, (10,), None] def coerce(self, value): try: @@ -317,144 +288,113 @@ def coerce(self, value): except: return complex(long(value)) -#------------------------------------------------------------------------------- -# Trait that can only have 'string' values: -#------------------------------------------------------------------------------- class StringTrait(HasTraits): - - # Trait definitions: value = Trait('string') + class StringTest(AnyTraitTest): obj = StringTrait() _default_value = 'string' - _good_values = [10, -10, 10L, -10L, 10.1, -10.1, '10', '-10', '10L', - '-10L', '10.1', '-10.1', 'string', u'string', 1j, [10], - ['ten'],{'ten': 10},(10,), None] - _bad_values = [] + _good_values = [10, -10, 10L, -10L, 10.1, -10.1, '10', '-10', '10L', + '-10L', '10.1', '-10.1', 'string', u'string', 1j, [10], + ['ten'], {'ten': 10}, (10,), None] + _bad_values = [] def coerce(self, value): return str(value) -#------------------------------------------------------------------------------- -# Trait that can only have 'unicode' values: -#------------------------------------------------------------------------------- class UnicodeTrait(HasTraits): - - # Trait definitions: value = Trait(u'unicode') + class UnicodeTest(StringTest): obj = UnicodeTrait() _default_value = u'unicode' - _good_values = [10, -10, 10L, -10L, 10.1, -10.1, '10', '-10', '10L', - '-10L', '10.1', '-10.1', '', u'', 'string', u'string', 1j, - [10], ['ten'], [u'ten'], {'ten': 10},(10,), None] - _bad_values = [] + _good_values = [10, -10, 10L, -10L, 10.1, -10.1, '10', '-10', '10L', + '-10L', '10.1', '-10.1', '', u'', 'string', u'string', 1j, + [10], ['ten'], [u'ten'], {'ten': 10}, (10,), None] + _bad_values = [] def coerce(self, value): return str(value) -#------------------------------------------------------------------------------- -# Trait that can only have an 'enumerated list' values: -#------------------------------------------------------------------------------- class EnumTrait(HasTraits): - - # Trait definitions: value = Trait([1, 'one', 2, 'two', 3, 'three', 4.4, u'four.four']) + class EnumTest(AnyTraitTest): obj = EnumTrait() _default_value = 1 - _good_values = [1, 'one', 2, 'two', 3, 'three', 4.4, u'four.four'] - _bad_values = [0, 'zero', 4, None] + _good_values = [1, 'one', 2, 'two', 3, 'three', 4.4, u'four.four'] + _bad_values = [0, 'zero', 4, None] -#------------------------------------------------------------------------------- -# Trait that can only have a 'mapped' values: -#------------------------------------------------------------------------------- class MappedTrait(HasTraits): - - # Trait definitions: value = Trait('one', {'one': 1, 'two': 2, 'three': 3}) -class MappedTest(AnyTraitTest): +class MappedTest(AnyTraitTest): obj = MappedTrait() _default_value = 'one' - _good_values = ['one', 'two', 'three'] + _good_values = ['one', 'two', 'three'] _mapped_values = [1, 2, 3] - _bad_values = ['four', 1, 2, 3, [1],(1,), {1: 1}, None] + _bad_values = ['four', 1, 2, 3, [1], (1,), {1: 1}, None] -#------------------------------------------------------------------------------- -# Trait that must be a unique prefix of an enumerated list of values: -#------------------------------------------------------------------------------- class PrefixListTrait(HasTraits): - - # Trait definitions: value = Trait('one', TraitPrefixList('one', 'two', 'three')) -class PrefixListTest(AnyTraitTest): +class PrefixListTest(AnyTraitTest): obj = PrefixListTrait() _default_value = 'one' - _good_values = ['o', 'on', 'one', 'tw', 'two', 'th', 'thr', 'thre', - 'three'] - _bad_values = ['t', 'one ', ' two', 1, None] + _good_values = ['o', 'on', 'one', 'tw', 'two', 'th', 'thr', 'thre', + 'three'] + _bad_values = ['t', 'one ', ' two', 1, None] def coerce(self, value): return {'o': 'one', 'on': 'one', 'tw': 'two', 'th': 'three'}[value[:2]] -#------------------------------------------------------------------------------- -# Trait that must be a unique prefix of a mapped set of values: -#------------------------------------------------------------------------------- class PrefixMapTrait(HasTraits): - - # Trait definitions: value = Trait('one', TraitPrefixMap({'one': 1, 'two': 2, 'three': 3})) -class PrefixMapTest(AnyTraitTest): +class PrefixMapTest(AnyTraitTest): obj = PrefixMapTrait() _default_value = 'one' - _good_values = ['o', 'on', 'one', 'tw', 'two', 'th', 'thr', 'thre', - 'three'] + _good_values = ['o', 'on', 'one', 'tw', 'two', 'th', 'thr', 'thre', + 'three'] _mapped_values = [1, 1, 1, 2, 2, 3, 3, 3] - _bad_values = ['t', 'one ', ' two', 1, None] + _bad_values = ['t', 'one ', ' two', 1, None] def coerce(self, value): return {'o': 'one', 'on': 'one', 'tw': 'two', 'th': 'three'}[value[:2]] -#------------------------------------------------------------------------------- -# Trait that must be within a specified integer range: -#------------------------------------------------------------------------------- class IntRangeTrait(HasTraits): - - # Trait definitions: value = Trait(3, TraitRange(2, 5)) + class IntRangeTest(AnyTraitTest): obj = IntRangeTrait() _default_value = 3 - _good_values = [2, 3, 4, 5] - _bad_values = [0, 1, 6, 0.999, 6.01, 'two', '0.999', '6.01', None] + _good_values = [2, 3, 4, 5] + _bad_values = [0, 1, 6, 0.999, 6.01, 'two', '0.999', '6.01', None] def coerce(self, value): try: @@ -465,23 +405,19 @@ def coerce(self, value): except: return int(long(value)) -#------------------------------------------------------------------------------- -# Trait that must be within a specified float range: -#------------------------------------------------------------------------------- class FloatRangeTrait(HasTraits): - - # Trait definitions: value = Trait(3.0, TraitRange(2.0, 5.0)) + class FloatRangeTest(AnyTraitTest): obj = FloatRangeTrait() _default_value = 3.0 - _good_values = [2.0, 3.0, 4.0, 5.0, 2.001, 4.999] - _bad_values = [0, 1, 6, 0L, 1L, 6L, 1.999, 6.01, 'two', '0.999', '6.01', - None] + _good_values = [2.0, 3.0, 4.0, 5.0, 2.001, 4.999] + _bad_values = [0, 1, 6, 0L, 1L, 6L, 1.999, 6.01, 'two', '0.999', '6.01', + None] def coerce(self, value): try: @@ -489,75 +425,98 @@ def coerce(self, value): except: return float(long(value)) -#------------------------------------------------------------------------------- -# Trait that must be an instance of a particular class(or subclass): -#------------------------------------------------------------------------------- # Old style class version: -class OTraitTest1: pass -class OTraitTest2(OTraitTest1): pass -class OTraitTest3(OTraitTest2): pass -class OBadTraitTest: pass + + +class OTraitTest1: + pass + + +class OTraitTest2(OTraitTest1): + pass + + +class OTraitTest3(OTraitTest2): + pass + + +class OBadTraitTest: + pass otrait_test1 = OTraitTest1() -class OldInstanceTrait(HasTraits): - # Trait definitions: +class OldInstanceTrait(HasTraits): value = Trait(otrait_test1) -class OldInstanceTest(AnyTraitTest): - # Trait definitions: +class OldInstanceTest(AnyTraitTest): obj = OldInstanceTrait() _default_value = otrait_test1 - _good_values = [otrait_test1, OTraitTest1(), OTraitTest2(), - OTraitTest3(), None] - _bad_values = [0, 0L, 0.0, 0j, OTraitTest1, OTraitTest2, OBadTraitTest(), - 'string', u'string', [otrait_test1],(otrait_test1,), - {'data': otrait_test1}] + _good_values = [otrait_test1, OTraitTest1(), OTraitTest2(), + OTraitTest3(), None] + _bad_values = [0, 0L, 0.0, 0j, OTraitTest1, OTraitTest2, OBadTraitTest(), + 'string', u'string', [otrait_test1], (otrait_test1,), + {'data': otrait_test1}] + # New style class version: -class NTraitTest1(object): pass -class NTraitTest2(NTraitTest1): pass -class NTraitTest3(NTraitTest2): pass -class NBadTraitTest: pass +class NTraitTest1(object): + pass + + +class NTraitTest2(NTraitTest1): + pass + + +class NTraitTest3(NTraitTest2): + pass + + +class NBadTraitTest: + pass + ntrait_test1 = NTraitTest1() -class NewInstanceTrait(HasTraits): - # Trait definitions: +class NewInstanceTrait(HasTraits): value = Trait(ntrait_test1) -class NewInstanceTest(AnyTraitTest): +class NewInstanceTest(AnyTraitTest): obj = NewInstanceTrait() _default_value = ntrait_test1 - _good_values = [ntrait_test1, NTraitTest1(), NTraitTest2(), NTraitTest3(), - None] - _bad_values = [0, 0L, 0.0, 0j, NTraitTest1, NTraitTest2, NBadTraitTest(), - 'string', u'string', [ntrait_test1],(ntrait_test1,), - {'data': ntrait_test1}] + _good_values = [ntrait_test1, NTraitTest1(), NTraitTest2(), NTraitTest3(), + None] + _bad_values = [0, 0L, 0.0, 0j, NTraitTest1, NTraitTest2, NBadTraitTest(), + 'string', u'string', [ntrait_test1], (ntrait_test1,), + {'data': ntrait_test1}] class FactoryClass(HasTraits): pass + class ConsumerClass(HasTraits): x = Instance(FactoryClass, ()) + class ConsumerSubclass(ConsumerClass): x = FactoryClass() -embedded_instance_trait = Trait('', Str, Instance('traits.has_traits.HasTraits')) +embedded_instance_trait = Trait('', Str, + Instance('traits.has_traits.HasTraits')) + class Dummy(HasTraits): x = embedded_instance_trait xl = List(embedded_instance_trait) + class RegressionTest(unittest.TestCase): """ Check that fixed bugs stay fixed. """ @@ -575,51 +534,45 @@ def test_trait_compound_instance(self): and then a list will not replace the validate method for the outermost trait. """ - # Pass through an instance in order to make the instance trait resolve the class. + # Pass through an instance in order to make the instance trait resolve + # the class. d = Dummy() d.xl = [HasTraits()] d.x = 'OK' -#------------------------------------------------------------------------------- # Trait(using a function) that must be an odd integer: -#------------------------------------------------------------------------------- + def odd_integer(object, name, value): try: - float(value) - if(value % 2) == 1: - return int(value) + float(value) + if(value % 2) == 1: + return int(value) except: pass raise TraitError -class OddIntegerTrait(HasTraits): - # Trait definitions: +class OddIntegerTrait(HasTraits): value = Trait(99, odd_integer) -class OddIntegerTest(AnyTraitTest): +class OddIntegerTest(AnyTraitTest): obj = OddIntegerTrait() _default_value = 99 - _good_values = [ 1, 3, 5, 7, 9, 999999999, - 1L, 3L, 5L, 7L, 9L, 999999999L, - 1.0, 3.0, 5.0, 7.0, 9.0, 999999999.0, - -1, -3, -5, -7, -9, -999999999, - -1L, -3L, -5L, -7L, -9L, -999999999L, - -1.0, -3.0, -5.0, -7.0, -9.0, -999999999.0 ] - _bad_values = [0, 2, -2, 1j, None, '1', [1],(1,), {1: 1}] - -#------------------------------------------------------------------------------- -# Trait that has various notifiers attached: -#------------------------------------------------------------------------------- + _good_values = [1, 3, 5, 7, 9, 999999999, + 1L, 3L, 5L, 7L, 9L, 999999999L, + 1.0, 3.0, 5.0, 7.0, 9.0, 999999999.0, + -1, -3, -5, -7, -9, -999999999, + -1L, -3L, -5L, -7L, -9L, -999999999L, + -1.0, -3.0, -5.0, -7.0, -9.0, -999999999.0] + _bad_values = [0, 2, -2, 1j, None, '1', [1], (1,), {1: 1}] -class NotifierTraits(HasTraits): - # Trait definitions: - value1 = Int - value2 = Int +class NotifierTraits(HasTraits): + value1 = Int + value2 = Int value1_count = Int value2_count = Int @@ -635,8 +588,8 @@ def _value1_changed(self, old, new): def _value2_changed(self, old, new): self.value2_count += 1 -class NotifierTests(unittest.TestCase): +class NotifierTests(unittest.TestCase): obj = NotifierTraits() def __init__(self, value): @@ -644,22 +597,22 @@ def __init__(self, value): def setUp(self): obj = self.obj - obj.value1 = 0 - obj.value2 = 0 + obj.value1 = 0 + obj.value2 = 0 obj.value1_count = 0 obj.value2_count = 0 def tearDown(self): obj = self.obj - obj.on_trait_change(self.on_value1_changed, 'value1', remove = True) - obj.on_trait_change(self.on_value2_changed, 'value2', remove = True) - obj.on_trait_change(self.on_anytrait_changed, remove = True) + obj.on_trait_change(self.on_value1_changed, 'value1', remove=True) + obj.on_trait_change(self.on_value2_changed, 'value2', remove=True) + obj.on_trait_change(self.on_anytrait_changed, remove=True) def on_anytrait_changed(self, object, trait_name, old, new): if trait_name == 'value1': - self.obj.value1_count += 1 + self.obj.value1_count += 1 elif trait_name == 'value2': - self.obj.value2_count += 1 + self.obj.value2_count += 1 def on_value1_changed(self): self.obj.value1_count += 1 @@ -705,17 +658,17 @@ def test_complex(self): self.assertEqual(obj.value1_count, 7) self.assertEqual(obj.value2_count, 7) - obj.on_trait_change(self.on_value1_changed, 'value1', remove = True) + obj.on_trait_change(self.on_value1_changed, 'value1', remove=True) obj.value1 = 3 self.assertEqual(obj.value1_count, 10) self.assertEqual(obj.value2_count, 7) - obj.on_trait_change(self.on_value2_changed, 'value2', remove = True) + obj.on_trait_change(self.on_value2_changed, 'value2', remove=True) obj.value2 = 3 self.assertEqual(obj.value1_count, 10) self.assertEqual(obj.value2_count, 10) - obj.on_trait_change(self.on_anytrait_changed, remove = True) + obj.on_trait_change(self.on_anytrait_changed, remove=True) obj.value1 = 4 self.assertEqual(obj.value1_count, 12) @@ -725,12 +678,14 @@ def test_complex(self): self.assertEqual(obj.value1_count, 12) self.assertEqual(obj.value2_count, 12) + class RaisesArgumentlessRuntimeError(HasTraits): x = Int(0) def _x_changed(self): raise RuntimeError + class TestRuntimeError(unittest.TestCase): def setUp(self): @@ -743,31 +698,24 @@ def test_runtime_error(self): f = RaisesArgumentlessRuntimeError() self.assertRaises(RuntimeError, setattr, f, 'x', 5) -#------------------------------------------------------------------------------- -# Trait that uses delegation: -#------------------------------------------------------------------------------- class DelegatedFloatTrait(HasTraits): - - # Trait definitions: value = Trait(99.0) -class DelegateTrait(HasTraits): - # Trait definitions: - value = Delegate('delegate') +class DelegateTrait(HasTraits): + value = Delegate('delegate') delegate = Trait(DelegatedFloatTrait()) -class DelegateTrait2(DelegateTrait): - # Trait definitions: +class DelegateTrait2(DelegateTrait): delegate = Trait(DelegateTrait()) -class DelegateTrait3(DelegateTrait): - # Trait definitions: +class DelegateTrait3(DelegateTrait): delegate = Trait(DelegateTrait2()) + class DelegateTests(unittest.TestCase): def test_delegation(self): @@ -778,26 +726,26 @@ def test_delegation(self): parent2 = parent1.delegate parent3 = parent2.delegate parent3.value = 3.0 - self.assertEqual(obj.value, 3.0) + self.assertEqual(obj.value, 3.0) parent2.value = 2.0 - self.assertEqual(obj.value, 2.0) + self.assertEqual(obj.value, 2.0) self.assertEqual(parent3.value, 3.0) parent1.value = 1.0 - self.assertEqual(obj.value, 1.0) + self.assertEqual(obj.value, 1.0) self.assertEqual(parent2.value, 2.0) self.assertEqual(parent3.value, 3.0) obj.value = 0.0 - self.assertEqual(obj.value, 0.0) + self.assertEqual(obj.value, 0.0) self.assertEqual(parent1.value, 1.0) self.assertEqual(parent2.value, 2.0) self.assertEqual(parent3.value, 3.0) del obj.value - self.assertEqual(obj.value, 1.0) + self.assertEqual(obj.value, 1.0) del parent1.value - self.assertEqual(obj.value, 2.0) + self.assertEqual(obj.value, 2.0) self.assertEqual(parent1.value, 2.0) del parent2.value - self.assertEqual(obj.value, 3.0) + self.assertEqual(obj.value, 3.0) self.assertEqual(parent1.value, 3.0) self.assertEqual(parent2.value, 3.0) del parent3.value @@ -806,14 +754,12 @@ def test_delegation(self): # may not be intended behavior, so keeping # the line commented. #del parent2.value - self.assertEqual(obj.value, 99.0) + self.assertEqual(obj.value, 99.0) self.assertEqual(parent1.value, 99.0) self.assertEqual(parent2.value, 99.0) self.assertEqual(parent3.value, 99.0) -#------------------------------------------------------------------------------- # Complex(i.e. 'composite') Traits tests: -#------------------------------------------------------------------------------- # Make a TraitCompound handler that does not have a fast_validate so we can # check for a particular regression. @@ -823,79 +769,48 @@ def test_delegation(self): except AttributeError: pass -class complex_value(HasTraits): - # Trait definitions: +class complex_value(HasTraits): num1 = Trait(1, TraitRange(1, 5), TraitRange(-5, -1)) num2 = Trait(1, TraitRange(1, 5), - TraitPrefixList('one', 'two', 'three', 'four', 'five')) + TraitPrefixList('one', 'two', 'three', 'four', 'five')) num3 = Trait(1, TraitRange(1, 5), - TraitPrefixMap({ 'one': 1, 'two': 2, 'three': 3, - 'four': 4, 'five': 5 })) + TraitPrefixMap({'one': 1, 'two': 2, 'three': 3, + 'four': 4, 'five': 5})) num4 = Trait(1, Trait(1, Tuple, slow), 10) num5 = Trait(1, 10, Trait(1, Tuple, slow)) -class test_complex_value(test_base2): - # Trait definitions: +class test_complex_value(test_base2): obj = complex_value() def test_num1(self): - self.check_values('num1', 1, - [ 1, 2, 3, 4, 5, -1, -2, -3, -4, -5 ], - [ 0, 6, -6, '0', '6', '-6', 0.0, 6.0, -6.0, [ 1 ],(1,), - { 1: 1 }, None ], - [ 1, 2, 3, 4, 5, -1, -2, -3, -4, -5 ]) + self.check_values('num1', 1, [1, 2, 3, 4, 5, -1, -2, -3, -4, -5], + [0, 6, -6, '0', '6', '-6', 0.0, 6.0, -6.0, [1], (1,), + {1: 1}, None], + [1, 2, 3, 4, 5, -1, -2, -3, -4, -5]) def test_enum_exceptions(self): - """ Check that enumerated values can be combined with nested TraitCompound handlers. + """ Check that enumerated values can be combined with nested + TraitCompound handlers. """ - self.check_values('num4', 1, - [1,2,3,-3,-2,-1, 10, ()], - [0, 4, 5, -5, -4, 11], - ) - self.check_values('num5', 1, - [1,2,3,-3,-2,-1, 10, ()], - [0, 4, 5, -5, -4, 11], - ) - -## def check_num2(self): -## self.check_values('num2', 1, -## [ 1, 2, 3, 4, 5, -## 'one', 'two', 'three', 'four', 'five', 'o', 'on', 'tw', -## 'th', 'thr', 'thre', 'fo', 'fou', 'fi', 'fiv' ], -## [ 0, 6, '0', '6', 0.0, 6.0, 't', 'f', 'six', [ 1 ],(1,), -## { 1: 1 }, None ], -## [ 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 'one', 'two', -## 'three', 'four', 'five', 'one', 'one', 'two', 'three', 'three', -## 'three', 'four', 'four', 'five', 'five' ]) - -## def check_num3(self): -## self.check_values('num3', 1, -## [ 1, 2, 3, 4, 5, -## 'one', 'two', 'three', 'four', 'five', 'o', 'on', 'tw', -## 'th', 'thr', 'thre', 'fo', 'fou', 'fi', 'fiv' ], -## [ 0, 6, '0', '6', 0.0, 6.0, 't', 'f', 'six', [ 1 ],(1,), -## { 1: 1 }, None ], -## [ 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 'one', 'two', -## 'three', 'four', 'five', 'one', 'one', 'two', 'three', 'three', -## 'three', 'four', 'four', 'five', 'five' ], -## [ 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, -## 1, 1, 2, 3, 3, 3, 4, 4, 5, 5 ]) - -#------------------------------------------------------------------------------- -# Test traits which are lists: -#------------------------------------------------------------------------------- + self.check_values('num4', 1, [1, 2, 3, -3, -2, -1, 10, ()], + [0, 4, 5, -5, -4, 11], + ) + self.check_values('num5', 1, [1, 2, 3, -3, -2, -1, 10, ()], + [0, 4, 5, -5, -4, 11], + ) -class list_value(HasTraits): +class list_value(HasTraits): # Trait definitions: - list1 = Trait([ 2 ], TraitList(Trait([ 1, 2, 3, 4 ]), - maxlen = 4)) - list2 = Trait([ 2 ], TraitList(Trait([ 1, 2, 3, 4 ]), - minlen = 1, maxlen = 4)) + list1 = Trait([2], TraitList(Trait([1, 2, 3, 4]), + maxlen=4)) + list2 = Trait([2], TraitList(Trait([1, 2, 3, 4]), + minlen=1, maxlen=4)) alist = List() + class test_list_value(test_base2): obj = list_value() @@ -908,13 +823,13 @@ def tearDown(self): del self.last_event def del_range(self, list, index1, index2): - del list[ index1: index2 ] + del list[index1: index2] def del_extended_slice(self, list, index1, index2, step): del list[index1:index2:step] def check_list(self, list): - self.assertEqual(list, [ 2 ]) + self.assertEqual(list, [2]) self.assertEqual(len(list), 1) list.append(3) self.assertEqual(len(list), 2) @@ -926,25 +841,25 @@ def check_list(self, list): self.assertEqual(len(list), 2) self.assertRaises(TraitError, self.indexed_assign, list, 0, 5) self.assertRaises(TraitError, list.append, 5) - self.assertRaises(TraitError, list.extend, [ 1, 2, 3 ]) - list.extend([ 3, 4 ]) - self.assertEqual(list, [ 1 ,2, 3, 4 ]) + self.assertRaises(TraitError, list.extend, [1, 2, 3]) + list.extend([3, 4]) + self.assertEqual(list, [1, 2, 3, 4]) self.assertRaises(TraitError, list.append, 1) self.assertRaises(ValueError, self.extended_slice_assign, list, 0, 4, 2, [4, 5, 6]) del list[1] - self.assertEqual(list, [ 1, 3, 4 ]) + self.assertEqual(list, [1, 3, 4]) del list[0] - self.assertEqual(list, [ 3, 4 ]) - list[:0] = [ 1, 2 ] - self.assertEqual(list, [ 1 ,2, 3, 4 ]) + self.assertEqual(list, [3, 4]) + list[:0] = [1, 2] + self.assertEqual(list, [1, 2, 3, 4]) self.assertRaises(TraitError, - self.indexed_range_assign, list, 0, 0, [ 1 ]) + self.indexed_range_assign, list, 0, 0, [1]) del list[0:3] - self.assertEqual(list, [ 4 ]) + self.assertEqual(list, [4]) self.assertRaises(TraitError, - self.indexed_range_assign, list, 0, 0, [ 4, 5 ]) + self.indexed_range_assign, list, 0, 0, [4, 5]) def test_list1(self): self.check_list(self.obj.list1) @@ -991,7 +906,8 @@ def test_trait_list_event(self): # If no values changed, no new TraitListEvent will be generated. self.assertIs(self.last_event, old_event) self.obj.alist[0:4:2] = [10, 11] - self.assertLastTraitListEventEqual(slice(0, 4, 2), [[8, 4]], [[10, 11]]) + self.assertLastTraitListEventEqual( + slice(0, 4, 2), [[8, 4]], [[10, 11]]) del self.obj.alist[1:4:2] self.assertLastTraitListEventEqual(slice(1, 4, 2), [[9, 5]], []) self.obj.alist = [1, 2, 3, 4] diff --git a/traits/tests/test_ui_notifiers.py b/traits/tests/test_ui_notifiers.py index 264e60b3d..64783e780 100644 --- a/traits/tests/test_ui_notifiers.py +++ b/traits/tests/test_ui_notifiers.py @@ -65,7 +65,6 @@ def on_foo_notifications(self, obj, name, old, new): #### Tests ################################################################ - @unittest.skipIf( not QT_FOUND, "Qt event loop not found, UI dispatch not possible.") def test_notification_from_main_thread(self): diff --git a/traits/tests/test_undefined.py b/traits/tests/test_undefined.py index d2c3325a0..be1a0a5c9 100644 --- a/traits/tests/test_undefined.py +++ b/traits/tests/test_undefined.py @@ -1,4 +1,4 @@ -#------------------------------------------------------------------------------- +#------------------------------------------------------------------------------ # # Copyright (c) 2007, Enthought, Inc. # All rights reserved. @@ -10,7 +10,7 @@ # # Thanks for using Enthought open source! # -#------------------------------------------------------------------------------- +#------------------------------------------------------------------------------ from __future__ import absolute_import @@ -18,6 +18,7 @@ from ..api import HasTraits, Str, Undefined, ReadOnly, Float + class Foo(HasTraits): name = Str() original_name = ReadOnly @@ -29,19 +30,21 @@ def _name_changed(self): if self.original_name is Undefined: self.original_name = self.name + class Bar(HasTraits): name = Str(Undefined) + class UndefinedTestCase(unittest.TestCase): def test_initial_value(self): b = Bar() - self.failUnlessEqual( b.name, Undefined ) + self.failUnlessEqual(b.name, Undefined) return def test_name_change(self): b = Bar() b.name = 'first' - self.failUnlessEqual( b.name, 'first' ) + self.failUnlessEqual(b.name, 'first') return def test_read_only_write_once(self): diff --git a/traits/tests/test_weak_ref.py b/traits/tests/test_weak_ref.py index 9ff629fad..342238d05 100644 --- a/traits/tests/test_weak_ref.py +++ b/traits/tests/test_weak_ref.py @@ -18,7 +18,7 @@ from traits.testing.unittest_tools import unittest, UnittestTools -from ..trait_types import Instance, List, Str, WeakRef +from ..trait_types import Str, WeakRef from ..has_traits import HasTraits @@ -30,7 +30,6 @@ class Spam(HasTraits): eggs = WeakRef(Eggs) - @contextlib.contextmanager def restore_gc_state(): """Ensure that gc state is restored on exit of the with statement."""