diff options
author | DongHun Kwak <dh0128.kwak@samsung.com> | 2017-07-12 08:46:30 +0900 |
---|---|---|
committer | DongHun Kwak <dh0128.kwak@samsung.com> | 2017-07-12 08:46:33 +0900 |
commit | dca4e6423c560689ee831785473ad3ab48e7548a (patch) | |
tree | 048ddb6edb0826be8ff180c027d45acb6dac67db /tests | |
parent | 392945d666d2cfb31a844826a72b1eb65a52546f (diff) | |
download | pygobject2-dca4e6423c560689ee831785473ad3ab48e7548a.tar.gz pygobject2-dca4e6423c560689ee831785473ad3ab48e7548a.tar.bz2 pygobject2-dca4e6423c560689ee831785473ad3ab48e7548a.zip |
Imported Upstream version 3.3.1
Change-Id: I7e59d7cf82217b545ec40115122a83ebf79763cb
Signed-off-by: DongHun Kwak <dh0128.kwak@samsung.com>
Diffstat (limited to 'tests')
51 files changed, 2254 insertions, 11643 deletions
diff --git a/tests/Makefile.am b/tests/Makefile.am index ff10433..f54a8bb 100644 --- a/tests/Makefile.am +++ b/tests/Makefile.am @@ -1,71 +1,23 @@ CLEANFILES = -test_ltlibraries = libgimarshallingtests.la -test_typelibs = GIMarshallingTests-1.0.typelib -extension_ltlibraries = -extension_libadd = - -common_ldflags = \ - -avoid-version \ - -rpath $(abs_builddir) \ - -shared - -if OS_WIN32 -extension_libadd += \ - $(PYTHON_LIBS) - -common_ldflags += \ - -no-undefined -endif - -# Note for Python extensions we need to use .so on Mac OSX, not .dylib -extension_ldflags = \ - $(common_ldflags) \ - -module \ - -shrext $(PYTHON_SO) - -nodist_libgimarshallingtests_la_SOURCES = \ - $(GI_DATADIR)/tests/gimarshallingtests.c \ - $(GI_DATADIR)/tests/gimarshallingtests.h - -dist_libgimarshallingtests_la_SOURCES = \ - $(srcdir)/gimarshallingtestsextra.c \ - $(srcdir)/gimarshallingtestsextra.h - -# We don't control the source so don't pass WARN_CFLAGS etc -libgimarshallingtests_la_CFLAGS = $(GLIB_CFLAGS) -libgimarshallingtests_la_LDFLAGS = $(common_ldflags) -libgimarshallingtests_la_LIBADD = $(GLIB_LIBS) +noinst_LTLIBRARIES = libregress.la libgimarshallingtests.la -GIMarshallingTests-1.0.gir: libgimarshallingtests.la Makefile - $(AM_V_GEN) $(INTROSPECTION_SCANNER) --include=Gio-2.0 \ - --namespace=GIMarshallingTests --nsversion=1.0 --symbol-prefix=gi_marshalling_tests \ - --warn-all --warn-error \ - --library=libgimarshallingtests.la \ - --libtool="$(top_builddir)/libtool" \ - --output $@ \ - $(nodist_libgimarshallingtests_la_SOURCES) \ - $(dist_libgimarshallingtests_la_SOURCES) +nodist_libregress_la_SOURCES = $(GI_DATADIR)/tests/regress.c $(GI_DATADIR)/tests/regress.h +libregress_la_CFLAGS = $(GIO_CFLAGS) $(PYCAIRO_CFLAGS) +libregress_la_LDFLAGS = -module -avoid-version $(GIO_LIBS) $(PYCAIRO_LIBS) +nodist_libgimarshallingtests_la_SOURCES = $(GI_DATADIR)/tests/gimarshallingtests.c $(GI_DATADIR)/tests/gimarshallingtests.h +libgimarshallingtests_la_CFLAGS = $(GLIB_CFLAGS) +libgimarshallingtests_la_LDFLAGS = -module -avoid-version $(GLIB_LIBS) -GIMarshallingTests-1.0.typelib: GIMarshallingTests-1.0.gir Makefile - $(AM_V_GEN) $(INTROSPECTION_COMPILER) $< -o $@ +# This is a hack to make sure a shared library is built +libregress.la: $(libregress_la_OBJECTS) $(libregress_la_DEPENDENCIES) + $(LINK) -rpath $(pkgpyexecdir) $(libregress_la_LDFLAGS) $(libregress_la_OBJECTS) $(libregress_la_LIBADD) $(LIBS) -# regress.c needs cairo -test_ltlibraries += libregress.la -test_typelibs += Regress-1.0.typelib -nodist_libregress_la_SOURCES = $(GI_DATADIR)/tests/regress.c $(GI_DATADIR)/tests/regress.h -# We don't control the source so don't pass WARN_CFLAGS etc -if ENABLE_CAIRO -libregress_la_CFLAGS = $(GIO_CFLAGS) $(CAIRO_CFLAGS) -libregress_la_LIBADD = $(GIO_LIBS) $(CAIRO_LIBS) -else -libregress_la_CFLAGS = $(GIO_CFLAGS) -D_GI_DISABLE_CAIRO -libregress_la_LIBADD = $(GIO_LIBS) $(CAIRO_LIBS) -endif -libregress_la_LDFLAGS = $(common_ldflags) +libgimarshallingtests.la: $(libgimarshallingtests_la_OBJECTS) $(libgimarshallingtests_la_DEPENDENCIES) + $(LINK) -rpath $(pkgpyexecdir) $(libgimarshallingtests_la_LDFLAGS) $(libgimarshallingtests_la_OBJECTS) $(libgimarhallingtests_la_LIBADD) $(LIBS) # g-i doesn't ship these as shared libraries anymore; we build them here Regress-1.0.gir: libregress.la Makefile - $(AM_V_GEN) $(INTROSPECTION_SCANNER) --include=cairo-1.0 --include=Gio-2.0 \ + $(AM_V_GEN) g-ir-scanner --include=cairo-1.0 --include=Gio-2.0 \ --namespace=Regress --nsversion=1.0 \ --warn-all --warn-error \ --library=libregress.la \ @@ -73,104 +25,90 @@ Regress-1.0.gir: libregress.la Makefile --output $@ \ $(nodist_libregress_la_SOURCES) Regress-1.0.typelib: Regress-1.0.gir Makefile - $(AM_V_GEN) $(INTROSPECTION_COMPILER) $< -o $@ + $(AM_V_GEN) g-ir-compiler $< -o $@ + +GIMarshallingTests-1.0.gir: libgimarshallingtests.la Makefile + $(AM_V_GEN) g-ir-scanner --include=Gio-2.0 \ + --namespace=GIMarshallingTests --nsversion=1.0 --symbol-prefix=gi_marshalling_tests \ + --warn-all --warn-error \ + --library=libgimarshallingtests.la \ + --libtool="$(top_builddir)/libtool" \ + --output $@ \ + $(nodist_libgimarshallingtests_la_SOURCES) +GIMarshallingTests-1.0.typelib: GIMarshallingTests-1.0.gir Makefile + $(AM_V_GEN) g-ir-compiler $< -o $@ gschemas.compiled: org.gnome.test.gschema.xml glib-compile-schemas --targetdir=. --schema-file=$< CLEANFILES += Regress-1.0.gir Regress-1.0.typelib GIMarshallingTests-1.0.gir GIMarshallingTests-1.0.typelib gschemas.compiled -extension_ltlibraries += testhelper.la - -testhelper_la_CFLAGS = $(CODE_COVERAGE_CFLAGS) $(WARN_CFLAGS) -I$(top_srcdir)/gi $(PYTHON_INCLUDES) $(GLIB_CFLAGS) -testhelper_la_CPPFLAGS = $(CODE_COVERAGE_CPPFLAGS) -testhelper_la_LDFLAGS = $(WARN_LDFLAGS) $(extension_ldflags) -testhelper_la_LIBADD = $(CODE_COVERAGE_LIBS) $(GLIB_LIBS) $(extension_libadd) +noinst_LTLIBRARIES += testhelper.la +testhelper_la_CFLAGS = -I$(top_srcdir)/gi/_gobject -I$(top_srcdir)/gi/_glib $(PYTHON_INCLUDES) $(GLIB_CFLAGS) +testhelper_la_LDFLAGS = -module -avoid-version +testhelper_la_LIBADD = $(GLIB_LIBS) testhelper_la_SOURCES = \ testhelpermodule.c \ test-floating.c \ test-thread.c \ test-unknown.c -check_LTLIBRARIES = $(test_ltlibraries) $(extension_ltlibraries) +# This is a hack to make sure a shared library is built +testhelper.la: $(testhelper_la_OBJECTS) $(testhelper_la_DEPENDENCIES) + $(LINK) -rpath $(pkgpyexecdir) $(testhelper_la_LDFLAGS) $(testhelper_la_OBJECTS) $(testhelper_la_LIBADD) $(LIBS) -target_libraries = \ - $(test_ltlibraries:.la=.$(OS_EXT)) \ - $(extension_ltlibraries:.la=$(PYTHON_SO)) -$(target_libraries): +.la.so: test -L $@ || $(LN_S) .libs/$@ $@ + +all: $(LTLIBRARIES:.la=.so) + EXTRA_DIST = \ - helper.py \ compathelper.py \ runtests.py \ + runtests-windows.py \ testmodule.py \ test-floating.h \ test-thread.h \ test-unknown.h \ te_ST@nouppera \ org.gnome.test.gschema.xml \ - test_cairo.py \ - test_error.py \ - test_fields.py \ - test_gio.py \ - test_glib.py \ test_gobject.py \ - test_gtype.py \ test_interface.py \ - test_internal_api.py \ - test_iochannel.py \ test_mainloop.py \ - test_object_marshaling.py \ test_option.py \ test_properties.py \ test_signal.py \ test_source.py \ test_subprocess.py \ test_thread.py \ - test_typeclass.py \ + test_uris.py \ test_everything.py \ test_gi.py \ test_gdbus.py \ - test_import_machinery.py \ - test_overrides_glib.py \ - test_overrides_pango.py \ - test_overrides_gdk.py \ - test_overrides_gtk.py \ + test_overrides.py \ test_atoms.py \ - test_generictreemodel.py \ - test_docstring.py \ - test_repository.py \ - test_resulttuple.py \ - compat_test_pygtk.py \ - gi/__init__.py \ - gi/overrides/__init__.py \ - gi/overrides/Regress.py \ - $(NULL) + test_pygtkcompat.py clean-local: - rm -f $(target_libraries) file.txt~ + rm -f $(LTLIBRARIES:.la=.so) file.txt~ -# Unsetting MSYSTEM prevents msys2 from changing os.path.sep to "/" +DBUS_LAUNCH=$(shell which dbus-launch) RUN_TESTS_ENV_VARS= \ - MALLOC_PERTURB_=85 \ - MALLOC_CHECK_=3 \ - G_SLICE=debug-blocks \ - MSYSTEM= \ + PYTHONPATH=$(top_builddir):$(top_builddir)/tests:$${PYTHONPATH:+:$$PYTHONPATH} \ + LD_LIBRARY_PATH=$(builddir)/.libs:$$LD_LIBRARY_PATH \ + GI_TYPELIB_PATH=$(builddir):$$GI_TYPELIB_PATH \ + XDG_DATA_DIRS=$$XDG_DATA_DIRS:/usr/share \ TESTS_BUILDDIR=$(builddir) -# if dbus-run-session is available, use it, otherwise disable DBUS -check-local: - DBUS_ENV=$$(dbus-run-session true && echo "dbus-run-session --" || echo "DBUS_SESSION_BUS_ADDRESS=.") $(MAKE) check.real - -# pygtkcompat tests need to be run in a separate process as they -# clobber global name space -check.real: $(target_libraries) $(test_typelibs) gschemas.compiled - $(RUN_TESTS_ENV_VARS) $(EXTRA_ENV) $(DBUS_ENV) $(EXEC_NAME) $(PYTHON) -Wd $(srcdir)/runtests.py; rc=$$?; \ - [ "$$rc" -ne 0 ] || [ -n "$$TEST_NAMES" ] || { TEST_NAMES=compat_test_pygtk $(RUN_TESTS_ENV_VARS) $(EXTRA_ENV) $(DBUS_ENV) $(EXEC_NAME) $(PYTHON) -Wd -Werror::PendingDeprecationWarning -Werror::DeprecationWarning -Werror::RuntimeWarning $(srcdir)/runtests.py; rc=$$?; }; \ - exit $$rc +check-local: $(LTLIBRARIES:.la=.so) Regress-1.0.typelib GIMarshallingTests-1.0.typelib gschemas.compiled + @echo " CHECK Pyflakes" + @pyflakes $(top_srcdir) + @echo " CHECK PEP8" + @pep8 --ignore=E501 --repeat --show-source $(top_srcdir) + $(RUN_TESTS_ENV_VARS) $(DBUS_LAUNCH) $(EXEC_NAME) $(PYTHON) -Wd -Werror::PendingDeprecationWarning -Werror::DeprecationWarning $(srcdir)/runtests.py check.gdb: EXEC_NAME="gdb --args" $(MAKE) check @@ -178,30 +116,7 @@ check.gdb: check.nemiver: EXEC_NAME="nemiver" $(MAKE) check -# Note G_SLICE in these check variations is intended to clobber the default set in RUN_TESTS_ENV_VARS check.valgrind: - EXTRA_ENV="G_SLICE=always-malloc G_DEBUG=gc-friendly PYTHONMALLOC=malloc" \ - EXEC_NAME="valgrind --leak-check=full --show-possibly-lost=no --num-callers=20 \ - --suppressions=$(top_srcdir)/tests/$(PYTHON_VALGRIND_SUPP).supp \ - " \ - $(MAKE) check - -check.valgrindlog: - mkdir -p $(top_builddir)/tmp - EXTRA_ENV="G_SLICE=always-malloc G_DEBUG=gc-friendly PYTHONMALLOC=malloc" \ - EXEC_NAME="valgrind --leak-check=full --show-possibly-lost=no --num-callers=20 \ - --suppressions=$(top_srcdir)/tests/$(PYTHON_VALGRIND_SUPP).supp \ - --child-silent-after-fork=yes \ - --log-file=$(top_builddir)/tmp/`git rev-parse HEAD | cut -c1-8`-$$TEST_NAMES.log \ - " \ - $(MAKE) check - -check.valgrindxml: - mkdir -p $(top_builddir)/tmp - EXTRA_ENV="G_SLICE=always-malloc G_DEBUG=gc-friendly PYTHONMALLOC=malloc" \ - EXEC_NAME="valgrind --leak-check=full --show-possibly-lost=no --num-callers=20 \ - --suppressions=$(top_srcdir)/tests/$(PYTHON_VALGRIND_SUPP).supp \ - --child-silent-after-fork=yes \ - --xml=yes --xml-file=$(top_builddir)/tmp/`git rev-parse HEAD | cut -c1-8`-$$TEST_NAMES.xml \ - " \ - $(MAKE) check + EXEC_NAME="valgrind --suppressions=python.supp" G_SLICE=always-malloc G_DEBUG=gc-friendly $(MAKE) check + +-include $(top_srcdir)/git.mk diff --git a/tests/Makefile.in b/tests/Makefile.in index 3e34139..4e90e86 100644 --- a/tests/Makefile.in +++ b/tests/Makefile.in @@ -1,8 +1,9 @@ -# Makefile.in generated by automake 1.15 from Makefile.am. +# Makefile.in generated by automake 1.11.3 from Makefile.am. # @configure_input@ -# Copyright (C) 1994-2014 Free Software Foundation, Inc. - +# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, +# 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software +# Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. @@ -13,62 +14,8 @@ # PARTICULAR PURPOSE. @SET_MAKE@ + VPATH = @srcdir@ -am__is_gnu_make = { \ - if test -z '$(MAKELEVEL)'; then \ - false; \ - elif test -n '$(MAKE_HOST)'; then \ - true; \ - elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ - true; \ - else \ - false; \ - fi; \ -} -am__make_running_with_option = \ - case $${target_option-} in \ - ?) ;; \ - *) echo "am__make_running_with_option: internal error: invalid" \ - "target option '$${target_option-}' specified" >&2; \ - exit 1;; \ - esac; \ - has_opt=no; \ - sane_makeflags=$$MAKEFLAGS; \ - if $(am__is_gnu_make); then \ - sane_makeflags=$$MFLAGS; \ - else \ - case $$MAKEFLAGS in \ - *\\[\ \ ]*) \ - bs=\\; \ - sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ - | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ - esac; \ - fi; \ - skip_next=no; \ - strip_trailopt () \ - { \ - flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ - }; \ - for flg in $$sane_makeflags; do \ - test $$skip_next = yes && { skip_next=no; continue; }; \ - case $$flg in \ - *=*|--*) continue;; \ - -*I) strip_trailopt 'I'; skip_next=yes;; \ - -*I?*) strip_trailopt 'I';; \ - -*O) strip_trailopt 'O'; skip_next=yes;; \ - -*O?*) strip_trailopt 'O';; \ - -*l) strip_trailopt 'l'; skip_next=yes;; \ - -*l?*) strip_trailopt 'l';; \ - -[dEDm]) skip_next=yes;; \ - -[JT]) skip_next=yes;; \ - esac; \ - case $$flg in \ - *$$target_option*) has_opt=yes; break;; \ - esac; \ - done; \ - test $$has_opt = yes -am__make_dryrun = (target_option=n; $(am__make_running_with_option)) -am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ @@ -87,69 +34,41 @@ PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ -@OS_WIN32_TRUE@am__append_1 = \ -@OS_WIN32_TRUE@ $(PYTHON_LIBS) - -@OS_WIN32_TRUE@am__append_2 = \ -@OS_WIN32_TRUE@ -no-undefined - subdir = tests +DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/m4/ax_append_compile_flags.m4 \ - $(top_srcdir)/m4/ax_append_flag.m4 \ - $(top_srcdir)/m4/ax_append_link_flags.m4 \ - $(top_srcdir)/m4/ax_check_compile_flag.m4 \ - $(top_srcdir)/m4/ax_check_link_flag.m4 \ - $(top_srcdir)/m4/ax_code_coverage.m4 \ - $(top_srcdir)/m4/ax_compiler_flags.m4 \ - $(top_srcdir)/m4/ax_compiler_flags_cflags.m4 \ - $(top_srcdir)/m4/ax_compiler_flags_gir.m4 \ - $(top_srcdir)/m4/ax_compiler_flags_ldflags.m4 \ - $(top_srcdir)/m4/ax_is_release.m4 \ - $(top_srcdir)/m4/ax_require_defined.m4 \ - $(top_srcdir)/m4/glib-2.0.m4 $(top_srcdir)/m4/introspection.m4 \ - $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ - $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ - $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/m4/pkg.m4 \ +am__aclocal_m4_deps = $(top_srcdir)/m4/as-ac-expand.m4 \ + $(top_srcdir)/m4/jhflags.m4 $(top_srcdir)/m4/libtool.m4 \ + $(top_srcdir)/m4/ltoptions.m4 $(top_srcdir)/m4/ltsugar.m4 \ + $(top_srcdir)/m4/ltversion.m4 $(top_srcdir)/m4/lt~obsolete.m4 \ $(top_srcdir)/m4/python.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) -DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = -am__DEPENDENCIES_1 = -libgimarshallingtests_la_DEPENDENCIES = $(am__DEPENDENCIES_1) -dist_libgimarshallingtests_la_OBJECTS = \ - libgimarshallingtests_la-gimarshallingtestsextra.lo +LTLIBRARIES = $(noinst_LTLIBRARIES) +libgimarshallingtests_la_LIBADD = nodist_libgimarshallingtests_la_OBJECTS = \ libgimarshallingtests_la-gimarshallingtests.lo libgimarshallingtests_la_OBJECTS = \ - $(dist_libgimarshallingtests_la_OBJECTS) \ $(nodist_libgimarshallingtests_la_OBJECTS) AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent -am__v_lt_1 = libgimarshallingtests_la_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \ $(libgimarshallingtests_la_CFLAGS) $(CFLAGS) \ $(libgimarshallingtests_la_LDFLAGS) $(LDFLAGS) -o $@ -@ENABLE_CAIRO_FALSE@libregress_la_DEPENDENCIES = \ -@ENABLE_CAIRO_FALSE@ $(am__DEPENDENCIES_1) \ -@ENABLE_CAIRO_FALSE@ $(am__DEPENDENCIES_1) -@ENABLE_CAIRO_TRUE@libregress_la_DEPENDENCIES = $(am__DEPENDENCIES_1) \ -@ENABLE_CAIRO_TRUE@ $(am__DEPENDENCIES_1) +libregress_la_LIBADD = nodist_libregress_la_OBJECTS = libregress_la-regress.lo libregress_la_OBJECTS = $(nodist_libregress_la_OBJECTS) libregress_la_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(libregress_la_CFLAGS) \ $(CFLAGS) $(libregress_la_LDFLAGS) $(LDFLAGS) -o $@ -@OS_WIN32_TRUE@am__DEPENDENCIES_2 = $(am__DEPENDENCIES_1) -am__DEPENDENCIES_3 = $(am__DEPENDENCIES_2) -testhelper_la_DEPENDENCIES = $(am__DEPENDENCIES_1) \ - $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_3) +am__DEPENDENCIES_1 = +testhelper_la_DEPENDENCIES = $(am__DEPENDENCIES_1) am_testhelper_la_OBJECTS = testhelper_la-testhelpermodule.lo \ testhelper_la-test-floating.lo testhelper_la-test-thread.lo \ testhelper_la-test-unknown.lo @@ -157,18 +76,6 @@ testhelper_la_OBJECTS = $(am_testhelper_la_OBJECTS) testhelper_la_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(testhelper_la_CFLAGS) \ $(CFLAGS) $(testhelper_la_LDFLAGS) $(LDFLAGS) -o $@ -AM_V_P = $(am__v_P_@AM_V@) -am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) -am__v_P_0 = false -am__v_P_1 = : -AM_V_GEN = $(am__v_GEN_@AM_V@) -am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) -am__v_GEN_0 = @echo " GEN " $@; -am__v_GEN_1 = -AM_V_at = $(am__v_at_@AM_V@) -am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) -am__v_at_0 = @ -am__v_at_1 = DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/depcomp am__depfiles_maybe = depfiles @@ -181,48 +88,28 @@ LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_@AM_V@) am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@) -am__v_CC_0 = @echo " CC " $@; -am__v_CC_1 = +am__v_CC_0 = @echo " CC " $@; +AM_V_at = $(am__v_at_@AM_V@) +am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) +am__v_at_0 = @ CCLD = $(CC) LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_@AM_V@) am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) -am__v_CCLD_0 = @echo " CCLD " $@; -am__v_CCLD_1 = -SOURCES = $(dist_libgimarshallingtests_la_SOURCES) \ - $(nodist_libgimarshallingtests_la_SOURCES) \ +am__v_CCLD_0 = @echo " CCLD " $@; +AM_V_GEN = $(am__v_GEN_@AM_V@) +am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) +am__v_GEN_0 = @echo " GEN " $@; +SOURCES = $(nodist_libgimarshallingtests_la_SOURCES) \ $(nodist_libregress_la_SOURCES) $(testhelper_la_SOURCES) -DIST_SOURCES = $(dist_libgimarshallingtests_la_SOURCES) \ - $(testhelper_la_SOURCES) -am__can_run_installinfo = \ - case $$AM_UPDATE_INFO_DIR in \ - n|no|NO) false;; \ - *) (install-info --version) >/dev/null 2>&1;; \ - esac -am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) -# Read a list of newline-separated strings from the standard input, -# and print each of them once, without duplicates. Input order is -# *not* preserved. -am__uniquify_input = $(AWK) '\ - BEGIN { nonempty = 0; } \ - { items[$$0] = 1; nonempty = 1; } \ - END { if (nonempty) { for (i in items) print i; }; } \ -' -# Make sure the list of sources is unique. This is necessary because, -# e.g., the same source file might be shared among _SOURCES variables -# for different programs/libraries. -am__define_uniq_tagged_files = \ - list='$(am__tagged_files)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | $(am__uniquify_input)` +DIST_SOURCES = $(testhelper_la_SOURCES) ETAGS = etags CTAGS = ctags -am__DIST_COMMON = $(srcdir)/Makefile.in $(top_srcdir)/depcomp DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ +ACLOCAL_AMFLAGS = @ACLOCAL_AMFLAGS@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ @@ -231,20 +118,13 @@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ -CAIRO_CFLAGS = @CAIRO_CFLAGS@ -CAIRO_LIBS = @CAIRO_LIBS@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ -CODE_COVERAGE_CFLAGS = @CODE_COVERAGE_CFLAGS@ -CODE_COVERAGE_CPPFLAGS = @CODE_COVERAGE_CPPFLAGS@ -CODE_COVERAGE_CXXFLAGS = @CODE_COVERAGE_CXXFLAGS@ -CODE_COVERAGE_ENABLED = @CODE_COVERAGE_ENABLED@ -CODE_COVERAGE_LDFLAGS = @CODE_COVERAGE_LDFLAGS@ -CODE_COVERAGE_LIBS = @CODE_COVERAGE_LIBS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CYGPATH_W = @CYGPATH_W@ +DATADIR = @DATADIR@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ @@ -258,8 +138,6 @@ EXEEXT = @EXEEXT@ FFI_CFLAGS = @FFI_CFLAGS@ FFI_LIBS = @FFI_LIBS@ FGREP = @FGREP@ -GCOV = @GCOV@ -GENHTML = @GENHTML@ GIO_CFLAGS = @GIO_CFLAGS@ GIO_LIBS = @GIO_LIBS@ GI_CFLAGS = @GI_CFLAGS@ @@ -277,15 +155,8 @@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ -INTROSPECTION_CFLAGS = @INTROSPECTION_CFLAGS@ INTROSPECTION_COMPILER = @INTROSPECTION_COMPILER@ -INTROSPECTION_GENERATE = @INTROSPECTION_GENERATE@ -INTROSPECTION_GIRDIR = @INTROSPECTION_GIRDIR@ -INTROSPECTION_LIBS = @INTROSPECTION_LIBS@ -INTROSPECTION_MAKEFILE = @INTROSPECTION_MAKEFILE@ INTROSPECTION_SCANNER = @INTROSPECTION_SCANNER@ -INTROSPECTION_TYPELIBDIR = @INTROSPECTION_TYPELIBDIR@ -LCOV = @LCOV@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBFFI_PC = @LIBFFI_PC@ @@ -295,7 +166,7 @@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ -LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ +MAINT = @MAINT@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ @@ -303,7 +174,6 @@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ -OS_EXT = @OS_EXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ @@ -317,30 +187,28 @@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ +PLATFORM = @PLATFORM@ PYCAIRO_CFLAGS = @PYCAIRO_CFLAGS@ PYCAIRO_LIBS = @PYCAIRO_LIBS@ PYGOBJECT_MAJOR_VERSION = @PYGOBJECT_MAJOR_VERSION@ PYGOBJECT_MICRO_VERSION = @PYGOBJECT_MICRO_VERSION@ PYGOBJECT_MINOR_VERSION = @PYGOBJECT_MINOR_VERSION@ PYTHON = @PYTHON@ +PYTHON_BASENAME = @PYTHON_BASENAME@ PYTHON_EXEC_PREFIX = @PYTHON_EXEC_PREFIX@ PYTHON_INCLUDES = @PYTHON_INCLUDES@ PYTHON_LIBS = @PYTHON_LIBS@ PYTHON_LIB_LOC = @PYTHON_LIB_LOC@ PYTHON_PLATFORM = @PYTHON_PLATFORM@ PYTHON_PREFIX = @PYTHON_PREFIX@ -PYTHON_SO = @PYTHON_SO@ -PYTHON_VALGRIND_SUPP = @PYTHON_VALGRIND_SUPP@ PYTHON_VERSION = @PYTHON_VERSION@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ +THREADING_CFLAGS = @THREADING_CFLAGS@ VERSION = @VERSION@ -WARN_CFLAGS = @WARN_CFLAGS@ -WARN_LDFLAGS = @WARN_LDFLAGS@ -WARN_SCANNERFLAGS = @WARN_SCANNERFLAGS@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ @@ -389,7 +257,6 @@ program_transform_name = @program_transform_name@ psdir = @psdir@ pyexecdir = @pyexecdir@ pythondir = @pythondir@ -runstatedir = @runstatedir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ @@ -401,118 +268,63 @@ top_srcdir = @top_srcdir@ CLEANFILES = Regress-1.0.gir Regress-1.0.typelib \ GIMarshallingTests-1.0.gir GIMarshallingTests-1.0.typelib \ gschemas.compiled - -# regress.c needs cairo -test_ltlibraries = libgimarshallingtests.la libregress.la -test_typelibs = GIMarshallingTests-1.0.typelib Regress-1.0.typelib -extension_ltlibraries = testhelper.la -extension_libadd = $(am__append_1) -common_ldflags = -avoid-version -rpath $(abs_builddir) -shared \ - $(am__append_2) - -# Note for Python extensions we need to use .so on Mac OSX, not .dylib -extension_ldflags = \ - $(common_ldflags) \ - -module \ - -shrext $(PYTHON_SO) - -nodist_libgimarshallingtests_la_SOURCES = \ - $(GI_DATADIR)/tests/gimarshallingtests.c \ - $(GI_DATADIR)/tests/gimarshallingtests.h - -dist_libgimarshallingtests_la_SOURCES = \ - $(srcdir)/gimarshallingtestsextra.c \ - $(srcdir)/gimarshallingtestsextra.h - - -# We don't control the source so don't pass WARN_CFLAGS etc -libgimarshallingtests_la_CFLAGS = $(GLIB_CFLAGS) -libgimarshallingtests_la_LDFLAGS = $(common_ldflags) -libgimarshallingtests_la_LIBADD = $(GLIB_LIBS) +noinst_LTLIBRARIES = libregress.la libgimarshallingtests.la \ + testhelper.la nodist_libregress_la_SOURCES = $(GI_DATADIR)/tests/regress.c $(GI_DATADIR)/tests/regress.h -@ENABLE_CAIRO_FALSE@libregress_la_CFLAGS = $(GIO_CFLAGS) -D_GI_DISABLE_CAIRO -# We don't control the source so don't pass WARN_CFLAGS etc -@ENABLE_CAIRO_TRUE@libregress_la_CFLAGS = $(GIO_CFLAGS) $(CAIRO_CFLAGS) -@ENABLE_CAIRO_FALSE@libregress_la_LIBADD = $(GIO_LIBS) $(CAIRO_LIBS) -@ENABLE_CAIRO_TRUE@libregress_la_LIBADD = $(GIO_LIBS) $(CAIRO_LIBS) -libregress_la_LDFLAGS = $(common_ldflags) -testhelper_la_CFLAGS = $(CODE_COVERAGE_CFLAGS) $(WARN_CFLAGS) -I$(top_srcdir)/gi $(PYTHON_INCLUDES) $(GLIB_CFLAGS) -testhelper_la_CPPFLAGS = $(CODE_COVERAGE_CPPFLAGS) -testhelper_la_LDFLAGS = $(WARN_LDFLAGS) $(extension_ldflags) -testhelper_la_LIBADD = $(CODE_COVERAGE_LIBS) $(GLIB_LIBS) $(extension_libadd) +libregress_la_CFLAGS = $(GIO_CFLAGS) $(PYCAIRO_CFLAGS) +libregress_la_LDFLAGS = -module -avoid-version $(GIO_LIBS) $(PYCAIRO_LIBS) +nodist_libgimarshallingtests_la_SOURCES = $(GI_DATADIR)/tests/gimarshallingtests.c $(GI_DATADIR)/tests/gimarshallingtests.h +libgimarshallingtests_la_CFLAGS = $(GLIB_CFLAGS) +libgimarshallingtests_la_LDFLAGS = -module -avoid-version $(GLIB_LIBS) +testhelper_la_CFLAGS = -I$(top_srcdir)/gi/_gobject -I$(top_srcdir)/gi/_glib $(PYTHON_INCLUDES) $(GLIB_CFLAGS) +testhelper_la_LDFLAGS = -module -avoid-version +testhelper_la_LIBADD = $(GLIB_LIBS) testhelper_la_SOURCES = \ testhelpermodule.c \ test-floating.c \ test-thread.c \ test-unknown.c -check_LTLIBRARIES = $(test_ltlibraries) $(extension_ltlibraries) -target_libraries = \ - $(test_ltlibraries:.la=.$(OS_EXT)) \ - $(extension_ltlibraries:.la=$(PYTHON_SO)) - EXTRA_DIST = \ - helper.py \ compathelper.py \ runtests.py \ + runtests-windows.py \ testmodule.py \ test-floating.h \ test-thread.h \ test-unknown.h \ te_ST@nouppera \ org.gnome.test.gschema.xml \ - test_cairo.py \ - test_error.py \ - test_fields.py \ - test_gio.py \ - test_glib.py \ test_gobject.py \ - test_gtype.py \ test_interface.py \ - test_internal_api.py \ - test_iochannel.py \ test_mainloop.py \ - test_object_marshaling.py \ test_option.py \ test_properties.py \ test_signal.py \ test_source.py \ test_subprocess.py \ test_thread.py \ - test_typeclass.py \ + test_uris.py \ test_everything.py \ test_gi.py \ test_gdbus.py \ - test_import_machinery.py \ - test_overrides_glib.py \ - test_overrides_pango.py \ - test_overrides_gdk.py \ - test_overrides_gtk.py \ + test_overrides.py \ test_atoms.py \ - test_generictreemodel.py \ - test_docstring.py \ - test_repository.py \ - test_resulttuple.py \ - compat_test_pygtk.py \ - gi/__init__.py \ - gi/overrides/__init__.py \ - gi/overrides/Regress.py \ - $(NULL) - - -# Unsetting MSYSTEM prevents msys2 from changing os.path.sep to "/" + test_pygtkcompat.py + +DBUS_LAUNCH = $(shell which dbus-launch) RUN_TESTS_ENV_VARS = \ - MALLOC_PERTURB_=85 \ - MALLOC_CHECK_=3 \ - G_SLICE=debug-blocks \ - MSYSTEM= \ + PYTHONPATH=$(top_builddir):$(top_builddir)/tests:$${PYTHONPATH:+:$$PYTHONPATH} \ + LD_LIBRARY_PATH=$(builddir)/.libs:$$LD_LIBRARY_PATH \ + GI_TYPELIB_PATH=$(builddir):$$GI_TYPELIB_PATH \ + XDG_DATA_DIRS=$$XDG_DATA_DIRS:/usr/share \ TESTS_BUILDDIR=$(builddir) all: all-am .SUFFIXES: -.SUFFIXES: .c .lo .o .obj -$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) +.SUFFIXES: .c .la .lo .o .obj .so +$(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ @@ -524,6 +336,7 @@ $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign tests/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign tests/Makefile +.PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ @@ -536,31 +349,20 @@ Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh -$(top_srcdir)/configure: $(am__configure_deps) +$(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh -$(ACLOCAL_M4): $(am__aclocal_m4_deps) +$(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): -clean-checkLTLIBRARIES: - -test -z "$(check_LTLIBRARIES)" || rm -f $(check_LTLIBRARIES) - @list='$(check_LTLIBRARIES)'; \ - locs=`for p in $$list; do echo $$p; done | \ - sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \ - sort -u`; \ - test -z "$$locs" || { \ - echo rm -f $${locs}; \ - rm -f $${locs}; \ - } - -libgimarshallingtests.la: $(libgimarshallingtests_la_OBJECTS) $(libgimarshallingtests_la_DEPENDENCIES) $(EXTRA_libgimarshallingtests_la_DEPENDENCIES) - $(AM_V_CCLD)$(libgimarshallingtests_la_LINK) $(libgimarshallingtests_la_OBJECTS) $(libgimarshallingtests_la_LIBADD) $(LIBS) - -libregress.la: $(libregress_la_OBJECTS) $(libregress_la_DEPENDENCIES) $(EXTRA_libregress_la_DEPENDENCIES) - $(AM_V_CCLD)$(libregress_la_LINK) $(libregress_la_OBJECTS) $(libregress_la_LIBADD) $(LIBS) - -testhelper.la: $(testhelper_la_OBJECTS) $(testhelper_la_DEPENDENCIES) $(EXTRA_testhelper_la_DEPENDENCIES) - $(AM_V_CCLD)$(testhelper_la_LINK) $(testhelper_la_OBJECTS) $(testhelper_la_LIBADD) $(LIBS) +clean-noinstLTLIBRARIES: + -test -z "$(noinst_LTLIBRARIES)" || rm -f $(noinst_LTLIBRARIES) + @list='$(noinst_LTLIBRARIES)'; for p in $$list; do \ + dir="`echo $$p | sed -e 's|/[^/]*$$||'`"; \ + test "$$dir" != "$$p" || dir=.; \ + echo "rm -f \"$${dir}/so_locations\""; \ + rm -f "$${dir}/so_locations"; \ + done mostlyclean-compile: -rm -f *.$(OBJEXT) @@ -569,7 +371,6 @@ distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libgimarshallingtests_la-gimarshallingtests.Plo@am__quote@ -@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libgimarshallingtests_la-gimarshallingtestsextra.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libregress_la-regress.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testhelper_la-test-floating.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/testhelper_la-test-thread.Plo@am__quote@ @@ -581,14 +382,14 @@ distclean-compile: @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $< +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c $< .c.obj: @am__fastdepCC_TRUE@ $(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'` +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c `$(CYGPATH_W) '$<'` .c.lo: @am__fastdepCC_TRUE@ $(AM_V_CC)$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @@ -597,13 +398,6 @@ distclean-compile: @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $< -libgimarshallingtests_la-gimarshallingtestsextra.lo: $(srcdir)/gimarshallingtestsextra.c -@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libgimarshallingtests_la_CFLAGS) $(CFLAGS) -MT libgimarshallingtests_la-gimarshallingtestsextra.lo -MD -MP -MF $(DEPDIR)/libgimarshallingtests_la-gimarshallingtestsextra.Tpo -c -o libgimarshallingtests_la-gimarshallingtestsextra.lo `test -f '$(srcdir)/gimarshallingtestsextra.c' || echo '$(srcdir)/'`$(srcdir)/gimarshallingtestsextra.c -@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libgimarshallingtests_la-gimarshallingtestsextra.Tpo $(DEPDIR)/libgimarshallingtests_la-gimarshallingtestsextra.Plo -@AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$(srcdir)/gimarshallingtestsextra.c' object='libgimarshallingtests_la-gimarshallingtestsextra.lo' libtool=yes @AMDEPBACKSLASH@ -@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libgimarshallingtests_la_CFLAGS) $(CFLAGS) -c -o libgimarshallingtests_la-gimarshallingtestsextra.lo `test -f '$(srcdir)/gimarshallingtestsextra.c' || echo '$(srcdir)/'`$(srcdir)/gimarshallingtestsextra.c - libgimarshallingtests_la-gimarshallingtests.lo: $(GI_DATADIR)/tests/gimarshallingtests.c @am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libgimarshallingtests_la_CFLAGS) $(CFLAGS) -MT libgimarshallingtests_la-gimarshallingtests.lo -MD -MP -MF $(DEPDIR)/libgimarshallingtests_la-gimarshallingtests.Tpo -c -o libgimarshallingtests_la-gimarshallingtests.lo `test -f '$(GI_DATADIR)/tests/gimarshallingtests.c' || echo '$(srcdir)/'`$(GI_DATADIR)/tests/gimarshallingtests.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/libgimarshallingtests_la-gimarshallingtests.Tpo $(DEPDIR)/libgimarshallingtests_la-gimarshallingtests.Plo @@ -619,32 +413,32 @@ libregress_la-regress.lo: $(GI_DATADIR)/tests/regress.c @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(libregress_la_CFLAGS) $(CFLAGS) -c -o libregress_la-regress.lo `test -f '$(GI_DATADIR)/tests/regress.c' || echo '$(srcdir)/'`$(GI_DATADIR)/tests/regress.c testhelper_la-testhelpermodule.lo: testhelpermodule.c -@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testhelper_la_CPPFLAGS) $(CPPFLAGS) $(testhelper_la_CFLAGS) $(CFLAGS) -MT testhelper_la-testhelpermodule.lo -MD -MP -MF $(DEPDIR)/testhelper_la-testhelpermodule.Tpo -c -o testhelper_la-testhelpermodule.lo `test -f 'testhelpermodule.c' || echo '$(srcdir)/'`testhelpermodule.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(testhelper_la_CFLAGS) $(CFLAGS) -MT testhelper_la-testhelpermodule.lo -MD -MP -MF $(DEPDIR)/testhelper_la-testhelpermodule.Tpo -c -o testhelper_la-testhelpermodule.lo `test -f 'testhelpermodule.c' || echo '$(srcdir)/'`testhelpermodule.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/testhelper_la-testhelpermodule.Tpo $(DEPDIR)/testhelper_la-testhelpermodule.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='testhelpermodule.c' object='testhelper_la-testhelpermodule.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testhelper_la_CPPFLAGS) $(CPPFLAGS) $(testhelper_la_CFLAGS) $(CFLAGS) -c -o testhelper_la-testhelpermodule.lo `test -f 'testhelpermodule.c' || echo '$(srcdir)/'`testhelpermodule.c +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(testhelper_la_CFLAGS) $(CFLAGS) -c -o testhelper_la-testhelpermodule.lo `test -f 'testhelpermodule.c' || echo '$(srcdir)/'`testhelpermodule.c testhelper_la-test-floating.lo: test-floating.c -@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testhelper_la_CPPFLAGS) $(CPPFLAGS) $(testhelper_la_CFLAGS) $(CFLAGS) -MT testhelper_la-test-floating.lo -MD -MP -MF $(DEPDIR)/testhelper_la-test-floating.Tpo -c -o testhelper_la-test-floating.lo `test -f 'test-floating.c' || echo '$(srcdir)/'`test-floating.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(testhelper_la_CFLAGS) $(CFLAGS) -MT testhelper_la-test-floating.lo -MD -MP -MF $(DEPDIR)/testhelper_la-test-floating.Tpo -c -o testhelper_la-test-floating.lo `test -f 'test-floating.c' || echo '$(srcdir)/'`test-floating.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/testhelper_la-test-floating.Tpo $(DEPDIR)/testhelper_la-test-floating.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test-floating.c' object='testhelper_la-test-floating.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testhelper_la_CPPFLAGS) $(CPPFLAGS) $(testhelper_la_CFLAGS) $(CFLAGS) -c -o testhelper_la-test-floating.lo `test -f 'test-floating.c' || echo '$(srcdir)/'`test-floating.c +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(testhelper_la_CFLAGS) $(CFLAGS) -c -o testhelper_la-test-floating.lo `test -f 'test-floating.c' || echo '$(srcdir)/'`test-floating.c testhelper_la-test-thread.lo: test-thread.c -@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testhelper_la_CPPFLAGS) $(CPPFLAGS) $(testhelper_la_CFLAGS) $(CFLAGS) -MT testhelper_la-test-thread.lo -MD -MP -MF $(DEPDIR)/testhelper_la-test-thread.Tpo -c -o testhelper_la-test-thread.lo `test -f 'test-thread.c' || echo '$(srcdir)/'`test-thread.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(testhelper_la_CFLAGS) $(CFLAGS) -MT testhelper_la-test-thread.lo -MD -MP -MF $(DEPDIR)/testhelper_la-test-thread.Tpo -c -o testhelper_la-test-thread.lo `test -f 'test-thread.c' || echo '$(srcdir)/'`test-thread.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/testhelper_la-test-thread.Tpo $(DEPDIR)/testhelper_la-test-thread.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test-thread.c' object='testhelper_la-test-thread.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testhelper_la_CPPFLAGS) $(CPPFLAGS) $(testhelper_la_CFLAGS) $(CFLAGS) -c -o testhelper_la-test-thread.lo `test -f 'test-thread.c' || echo '$(srcdir)/'`test-thread.c +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(testhelper_la_CFLAGS) $(CFLAGS) -c -o testhelper_la-test-thread.lo `test -f 'test-thread.c' || echo '$(srcdir)/'`test-thread.c testhelper_la-test-unknown.lo: test-unknown.c -@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testhelper_la_CPPFLAGS) $(CPPFLAGS) $(testhelper_la_CFLAGS) $(CFLAGS) -MT testhelper_la-test-unknown.lo -MD -MP -MF $(DEPDIR)/testhelper_la-test-unknown.Tpo -c -o testhelper_la-test-unknown.lo `test -f 'test-unknown.c' || echo '$(srcdir)/'`test-unknown.c +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(testhelper_la_CFLAGS) $(CFLAGS) -MT testhelper_la-test-unknown.lo -MD -MP -MF $(DEPDIR)/testhelper_la-test-unknown.Tpo -c -o testhelper_la-test-unknown.lo `test -f 'test-unknown.c' || echo '$(srcdir)/'`test-unknown.c @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/testhelper_la-test-unknown.Tpo $(DEPDIR)/testhelper_la-test-unknown.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='test-unknown.c' object='testhelper_la-test-unknown.lo' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ -@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(testhelper_la_CPPFLAGS) $(CPPFLAGS) $(testhelper_la_CFLAGS) $(CFLAGS) -c -o testhelper_la-test-unknown.lo `test -f 'test-unknown.c' || echo '$(srcdir)/'`test-unknown.c +@am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(testhelper_la_CFLAGS) $(CFLAGS) -c -o testhelper_la-test-unknown.lo `test -f 'test-unknown.c' || echo '$(srcdir)/'`test-unknown.c mostlyclean-libtool: -rm -f *.lo @@ -652,15 +446,26 @@ mostlyclean-libtool: clean-libtool: -rm -rf .libs _libs -ID: $(am__tagged_files) - $(am__define_uniq_tagged_files); mkid -fID $$unique -tags: tags-am -TAGS: tags - -tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) +ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + mkid -fID $$unique +tags: TAGS + +TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) set x; \ here=`pwd`; \ - $(am__define_uniq_tagged_files); \ + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ @@ -672,11 +477,15 @@ tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $$unique; \ fi; \ fi -ctags: ctags-am - -CTAGS: ctags -ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) - $(am__define_uniq_tagged_files); \ +ctags: CTAGS +CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique @@ -685,21 +494,6 @@ GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" -cscopelist: cscopelist-am - -cscopelist-am: $(am__tagged_files) - list='$(am__tagged_files)'; \ - case "$(srcdir)" in \ - [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ - *) sdir=$(subdir)/$(srcdir) ;; \ - esac; \ - for i in $$list; do \ - if test -f "$$i"; then \ - echo "$(subdir)/$$i"; \ - else \ - echo "$$sdir/$$i"; \ - fi; \ - done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags @@ -735,10 +529,9 @@ distdir: $(DISTFILES) fi; \ done check-am: all-am - $(MAKE) $(AM_MAKEFLAGS) $(check_LTLIBRARIES) $(MAKE) $(AM_MAKEFLAGS) check-local check: check-am -all-am: Makefile +all-am: Makefile $(LTLIBRARIES) installdirs: install: install-am install-exec: install-exec-am @@ -773,8 +566,8 @@ maintainer-clean-generic: @echo "it deletes files that may require special tools to rebuild." clean: clean-am -clean-am: clean-checkLTLIBRARIES clean-generic clean-libtool \ - clean-local mostlyclean-am +clean-am: clean-generic clean-libtool clean-local \ + clean-noinstLTLIBRARIES mostlyclean-am distclean: distclean-am -rm -rf ./$(DEPDIR) @@ -844,9 +637,9 @@ uninstall-am: .MAKE: check-am install-am install-strip -.PHONY: CTAGS GTAGS TAGS all all-am check check-am check-local clean \ - clean-checkLTLIBRARIES clean-generic clean-libtool clean-local \ - cscopelist-am ctags ctags-am distclean distclean-compile \ +.PHONY: CTAGS GTAGS all all-am check check-am check-local clean \ + clean-generic clean-libtool clean-local \ + clean-noinstLTLIBRARIES ctags distclean distclean-compile \ distclean-generic distclean-libtool distclean-tags distdir dvi \ dvi-am html html-am info info-am install install-am \ install-data install-data-am install-dvi install-dvi-am \ @@ -856,27 +649,19 @@ uninstall-am: installcheck installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ - tags tags-am uninstall uninstall-am - -.PRECIOUS: Makefile + tags uninstall uninstall-am -GIMarshallingTests-1.0.gir: libgimarshallingtests.la Makefile - $(AM_V_GEN) $(INTROSPECTION_SCANNER) --include=Gio-2.0 \ - --namespace=GIMarshallingTests --nsversion=1.0 --symbol-prefix=gi_marshalling_tests \ - --warn-all --warn-error \ - --library=libgimarshallingtests.la \ - --libtool="$(top_builddir)/libtool" \ - --output $@ \ - $(nodist_libgimarshallingtests_la_SOURCES) \ - $(dist_libgimarshallingtests_la_SOURCES) +# This is a hack to make sure a shared library is built +libregress.la: $(libregress_la_OBJECTS) $(libregress_la_DEPENDENCIES) + $(LINK) -rpath $(pkgpyexecdir) $(libregress_la_LDFLAGS) $(libregress_la_OBJECTS) $(libregress_la_LIBADD) $(LIBS) -GIMarshallingTests-1.0.typelib: GIMarshallingTests-1.0.gir Makefile - $(AM_V_GEN) $(INTROSPECTION_COMPILER) $< -o $@ +libgimarshallingtests.la: $(libgimarshallingtests_la_OBJECTS) $(libgimarshallingtests_la_DEPENDENCIES) + $(LINK) -rpath $(pkgpyexecdir) $(libgimarshallingtests_la_LDFLAGS) $(libgimarshallingtests_la_OBJECTS) $(libgimarhallingtests_la_LIBADD) $(LIBS) # g-i doesn't ship these as shared libraries anymore; we build them here Regress-1.0.gir: libregress.la Makefile - $(AM_V_GEN) $(INTROSPECTION_SCANNER) --include=cairo-1.0 --include=Gio-2.0 \ + $(AM_V_GEN) g-ir-scanner --include=cairo-1.0 --include=Gio-2.0 \ --namespace=Regress --nsversion=1.0 \ --warn-all --warn-error \ --library=libregress.la \ @@ -884,27 +669,40 @@ Regress-1.0.gir: libregress.la Makefile --output $@ \ $(nodist_libregress_la_SOURCES) Regress-1.0.typelib: Regress-1.0.gir Makefile - $(AM_V_GEN) $(INTROSPECTION_COMPILER) $< -o $@ + $(AM_V_GEN) g-ir-compiler $< -o $@ + +GIMarshallingTests-1.0.gir: libgimarshallingtests.la Makefile + $(AM_V_GEN) g-ir-scanner --include=Gio-2.0 \ + --namespace=GIMarshallingTests --nsversion=1.0 --symbol-prefix=gi_marshalling_tests \ + --warn-all --warn-error \ + --library=libgimarshallingtests.la \ + --libtool="$(top_builddir)/libtool" \ + --output $@ \ + $(nodist_libgimarshallingtests_la_SOURCES) +GIMarshallingTests-1.0.typelib: GIMarshallingTests-1.0.gir Makefile + $(AM_V_GEN) g-ir-compiler $< -o $@ gschemas.compiled: org.gnome.test.gschema.xml glib-compile-schemas --targetdir=. --schema-file=$< -$(target_libraries): +# This is a hack to make sure a shared library is built +testhelper.la: $(testhelper_la_OBJECTS) $(testhelper_la_DEPENDENCIES) + $(LINK) -rpath $(pkgpyexecdir) $(testhelper_la_LDFLAGS) $(testhelper_la_OBJECTS) $(testhelper_la_LIBADD) $(LIBS) + +.la.so: test -L $@ || $(LN_S) .libs/$@ $@ -clean-local: - rm -f $(target_libraries) file.txt~ +all: $(LTLIBRARIES:.la=.so) -# if dbus-run-session is available, use it, otherwise disable DBUS -check-local: - DBUS_ENV=$$(dbus-run-session true && echo "dbus-run-session --" || echo "DBUS_SESSION_BUS_ADDRESS=.") $(MAKE) check.real +clean-local: + rm -f $(LTLIBRARIES:.la=.so) file.txt~ -# pygtkcompat tests need to be run in a separate process as they -# clobber global name space -check.real: $(target_libraries) $(test_typelibs) gschemas.compiled - $(RUN_TESTS_ENV_VARS) $(EXTRA_ENV) $(DBUS_ENV) $(EXEC_NAME) $(PYTHON) -Wd $(srcdir)/runtests.py; rc=$$?; \ - [ "$$rc" -ne 0 ] || [ -n "$$TEST_NAMES" ] || { TEST_NAMES=compat_test_pygtk $(RUN_TESTS_ENV_VARS) $(EXTRA_ENV) $(DBUS_ENV) $(EXEC_NAME) $(PYTHON) -Wd -Werror::PendingDeprecationWarning -Werror::DeprecationWarning -Werror::RuntimeWarning $(srcdir)/runtests.py; rc=$$?; }; \ - exit $$rc +check-local: $(LTLIBRARIES:.la=.so) Regress-1.0.typelib GIMarshallingTests-1.0.typelib gschemas.compiled + @echo " CHECK Pyflakes" + @pyflakes $(top_srcdir) + @echo " CHECK PEP8" + @pep8 --ignore=E501 --repeat --show-source $(top_srcdir) + $(RUN_TESTS_ENV_VARS) $(DBUS_LAUNCH) $(EXEC_NAME) $(PYTHON) -Wd -Werror::PendingDeprecationWarning -Werror::DeprecationWarning $(srcdir)/runtests.py check.gdb: EXEC_NAME="gdb --args" $(MAKE) check @@ -912,33 +710,10 @@ check.gdb: check.nemiver: EXEC_NAME="nemiver" $(MAKE) check -# Note G_SLICE in these check variations is intended to clobber the default set in RUN_TESTS_ENV_VARS check.valgrind: - EXTRA_ENV="G_SLICE=always-malloc G_DEBUG=gc-friendly PYTHONMALLOC=malloc" \ - EXEC_NAME="valgrind --leak-check=full --show-possibly-lost=no --num-callers=20 \ - --suppressions=$(top_srcdir)/tests/$(PYTHON_VALGRIND_SUPP).supp \ - " \ - $(MAKE) check - -check.valgrindlog: - mkdir -p $(top_builddir)/tmp - EXTRA_ENV="G_SLICE=always-malloc G_DEBUG=gc-friendly PYTHONMALLOC=malloc" \ - EXEC_NAME="valgrind --leak-check=full --show-possibly-lost=no --num-callers=20 \ - --suppressions=$(top_srcdir)/tests/$(PYTHON_VALGRIND_SUPP).supp \ - --child-silent-after-fork=yes \ - --log-file=$(top_builddir)/tmp/`git rev-parse HEAD | cut -c1-8`-$$TEST_NAMES.log \ - " \ - $(MAKE) check - -check.valgrindxml: - mkdir -p $(top_builddir)/tmp - EXTRA_ENV="G_SLICE=always-malloc G_DEBUG=gc-friendly PYTHONMALLOC=malloc" \ - EXEC_NAME="valgrind --leak-check=full --show-possibly-lost=no --num-callers=20 \ - --suppressions=$(top_srcdir)/tests/$(PYTHON_VALGRIND_SUPP).supp \ - --child-silent-after-fork=yes \ - --xml=yes --xml-file=$(top_builddir)/tmp/`git rev-parse HEAD | cut -c1-8`-$$TEST_NAMES.xml \ - " \ - $(MAKE) check + EXEC_NAME="valgrind --suppressions=python.supp" G_SLICE=always-malloc G_DEBUG=gc-friendly $(MAKE) check + +-include $(top_srcdir)/git.mk # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. diff --git a/tests/compat_test_pygtk.py b/tests/compat_test_pygtk.py deleted file mode 100644 index 6552256..0000000 --- a/tests/compat_test_pygtk.py +++ /dev/null @@ -1,181 +0,0 @@ -# -*- Mode: Python; py-indent-offset: 4 -*- -# vim: tabstop=4 shiftwidth=4 expandtab - -import unittest -import base64 - -try: - from gi.repository import Gtk - from gi.repository import Pango - from gi.repository import Atk - from gi.repository import Gdk - (Atk, Gtk, Pango) # pyflakes - - import pygtkcompat - - pygtkcompat.enable() - pygtkcompat.enable_gtk(version=Gtk._version) - - import atk - import pango - import pangocairo - import gtk - import gtk.gdk -except (ValueError, ImportError): - Gtk = None - -from helper import capture_gi_deprecation_warnings, capture_glib_warnings - - -@unittest.skipUnless(Gtk, 'Gtk not available') -class TestMultipleEnable(unittest.TestCase): - - def test_main(self): - pygtkcompat.enable() - pygtkcompat.enable() - - def test_gtk(self): - pygtkcompat.enable_gtk("3.0") - pygtkcompat.enable_gtk("3.0") - - # https://bugzilla.gnome.org/show_bug.cgi?id=759009 - w = gtk.Window() - w.realize() - self.assertEqual(len(w.window.get_origin()), 2) - w.destroy() - - def test_gtk_version_conflict(self): - self.assertRaises(ValueError, pygtkcompat.enable_gtk, version='2.0') - - -@unittest.skipUnless(Gtk, 'Gtk not available') -class TestATKCompat(unittest.TestCase): - def test_object(self): - self.assertTrue(hasattr(atk, 'Object')) - - -@unittest.skipUnless(Gtk, 'Gtk not available') -class TestPangoCompat(unittest.TestCase): - def test_layout(self): - self.assertTrue(hasattr(pango, 'Layout')) - - -@unittest.skipUnless(Gtk, 'Gtk not available') -class TestPangoCairoCompat(unittest.TestCase): - def test_error_underline_path(self): - self.assertTrue(hasattr(pangocairo, 'error_underline_path')) - - -@unittest.skipUnless(Gtk, 'Gtk not available') -class TestGTKCompat(unittest.TestCase): - def test_buttons(self): - self.assertEqual(Gdk._2BUTTON_PRESS, 5) - self.assertEqual(Gdk.BUTTON_PRESS, 4) - - def test_enums(self): - self.assertEqual(gtk.WINDOW_TOPLEVEL, Gtk.WindowType.TOPLEVEL) - self.assertEqual(gtk.PACK_START, Gtk.PackType.START) - - def test_flags(self): - self.assertEqual(gtk.EXPAND, Gtk.AttachOptions.EXPAND) - self.assertEqual(gtk.gdk.SHIFT_MASK, Gdk.ModifierType.SHIFT_MASK) - - def test_keysyms(self): - import gtk.keysyms - self.assertEqual(gtk.keysyms.Escape, Gdk.KEY_Escape) - self.assertTrue(gtk.keysyms._0, Gdk.KEY_0) - - def test_style(self): - widget = gtk.Button() - with capture_gi_deprecation_warnings(): - widget.get_style_context().set_state(gtk.STATE_NORMAL) - self.assertTrue(isinstance(widget.style.base[gtk.STATE_NORMAL], - gtk.gdk.Color)) - - def test_alignment(self): - # Creation of pygtk.Alignment causes hard warnings, ignore this in testing. - with capture_glib_warnings(allow_warnings=True): - a = gtk.Alignment() - - self.assertEqual(a.props.xalign, 0.0) - self.assertEqual(a.props.yalign, 0.0) - self.assertEqual(a.props.xscale, 0.0) - self.assertEqual(a.props.yscale, 0.0) - - def test_box(self): - box = gtk.Box() - child = gtk.Button() - - box.pack_start(child) - expand, fill, padding, pack_type = box.query_child_packing(child) - self.assertTrue(expand) - self.assertTrue(fill) - self.assertEqual(padding, 0) - self.assertEqual(pack_type, gtk.PACK_START) - - child = gtk.Button() - box.pack_end(child) - expand, fill, padding, pack_type = box.query_child_packing(child) - self.assertTrue(expand) - self.assertTrue(fill) - self.assertEqual(padding, 0) - self.assertEqual(pack_type, gtk.PACK_END) - - def test_combobox_entry(self): - liststore = gtk.ListStore(int, str) - liststore.append((1, 'One')) - liststore.append((2, 'Two')) - liststore.append((3, 'Three')) - # might cause a Pango warning, do not break on this - with capture_glib_warnings(allow_warnings=True): - combo = gtk.ComboBoxEntry(model=liststore) - combo.set_text_column(1) - combo.set_active(0) - self.assertEqual(combo.get_text_column(), 1) - self.assertEqual(combo.get_child().get_text(), 'One') - combo = gtk.combo_box_entry_new() - combo.set_model(liststore) - combo.set_text_column(1) - combo.set_active(0) - self.assertEqual(combo.get_text_column(), 1) - self.assertEqual(combo.get_child().get_text(), 'One') - combo = gtk.combo_box_entry_new_with_model(liststore) - combo.set_text_column(1) - combo.set_active(0) - self.assertEqual(combo.get_text_column(), 1) - self.assertEqual(combo.get_child().get_text(), 'One') - - def test_size_request(self): - box = gtk.Box() - with capture_gi_deprecation_warnings(): - self.assertEqual(box.size_request(), [0, 0]) - - def test_pixbuf(self): - gtk.gdk.Pixbuf() - - def test_pixbuf_loader(self): - # load a 1x1 pixel PNG from memory - data = base64.b64decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP4n8Dw' - 'HwAGIAJf85Z3XgAAAABJRU5ErkJggg==') - loader = gtk.gdk.PixbufLoader('png') - loader.write(data) - loader.close() - - pixbuf = loader.get_pixbuf() - self.assertEqual(pixbuf.get_width(), 1) - self.assertEqual(pixbuf.get_height(), 1) - - def test_pixbuf_formats(self): - formats = gtk.gdk.pixbuf_get_formats() - self.assertEqual(type(formats[0]), dict) - self.assertTrue('name' in formats[0]) - self.assertTrue('description' in formats[0]) - self.assertTrue('mime_types' in formats[0]) - self.assertEqual(type(formats[0]['extensions']), list) - - def test_gdk_window(self): - w = gtk.Window() - w.realize() - origin = w.get_window().get_origin() - self.assertTrue(isinstance(origin, tuple)) - self.assertEqual(len(origin), 2) diff --git a/tests/compathelper.py b/tests/compathelper.py index d4f4d27..668e60a 100644 --- a/tests/compathelper.py +++ b/tests/compathelper.py @@ -1,7 +1,5 @@ import sys -PY2 = PY3 = False - if sys.version_info >= (3, 0): ''' for tests that need to test long values in python 2 @@ -30,12 +28,42 @@ if sys.version_info >= (3, 0): ''' _basestring = str - from io import StringIO - StringIO - PY3 = True + ''' + for tests that need to write to intefaces that take bytes in + python 3 + + python 3 has a seperate bytes type for low level functions like os.write + + python 2 treats these as strings + + any tests that need to write a string of bytes should do something like + this: + + from compathelper import _bytes + os.write(_bytes("hello")) + ''' + + _bytes = lambda s: s.encode() + + ''' + for tests that need to write to intefaces that take unicode in + python 2 + + python 3 strings are unicode encoded as UTF-8 so the unicode object + doesn't exist + + python 2 differs between a string an unicode string and you must specify + an encoding. This macro will specify UTF-8 in python 2 + + any tests that need to use unicode should do this + + from compathelper import _unicode + unicode_string = _unicode('this is a unicode string') + ''' + + _unicode = lambda s: str(s) else: _long = long _basestring = basestring - from StringIO import StringIO - StringIO - PY2 = True + _bytes = str + _unicode = lambda s: unicode(s, 'UTF-8') diff --git a/tests/gi/__init__.py b/tests/gi/__init__.py deleted file mode 100644 index 3ad9513..0000000 --- a/tests/gi/__init__.py +++ /dev/null @@ -1,2 +0,0 @@ -from pkgutil import extend_path -__path__ = extend_path(__path__, __name__) diff --git a/tests/gi/overrides/Regress.py b/tests/gi/overrides/Regress.py deleted file mode 100644 index cb38631..0000000 --- a/tests/gi/overrides/Regress.py +++ /dev/null @@ -1,26 +0,0 @@ -# -*- Mode: Python; py-indent-offset: 4 -*- -# vim: tabstop=4 shiftwidth=4 expandtab -# -# Copyright (C) 2012 Martin Pitt <martinpitt@gnome.org> -# -# This library is free software; you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public -# License as published by the Free Software Foundation; either -# version 2.1 of the License, or (at your option) any later version. -# -# This library is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 -# USA - -from ..importer import modules - -Regress = modules['Regress']._introspection_module - -REGRESS_OVERRIDE = 42 -__all__ = ['REGRESS_OVERRIDE'] diff --git a/tests/gi/overrides/__init__.py b/tests/gi/overrides/__init__.py deleted file mode 100644 index 3ad9513..0000000 --- a/tests/gi/overrides/__init__.py +++ /dev/null @@ -1,2 +0,0 @@ -from pkgutil import extend_path -__path__ = extend_path(__path__, __name__) diff --git a/tests/gimarshallingtestsextra.c b/tests/gimarshallingtestsextra.c deleted file mode 100644 index eee3a14..0000000 --- a/tests/gimarshallingtestsextra.c +++ /dev/null @@ -1,106 +0,0 @@ -/* gimarshallingtestsextra.c - * - * Copyright (C) 2016 Thibault Saunier <tsaunier@gnome.org> - * - * This file is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 3 of the - * License, or (at your option) any later version. - * - * This file is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - */ - -#include "gimarshallingtestsextra.h" -#include <string.h> - -void -gi_marshalling_tests_compare_two_gerrors_in_gvalue (GValue *v, GValue *v1) -{ - GError *error, * error1; - - g_assert_cmpstr (g_type_name (G_VALUE_TYPE (v)), ==, - g_type_name (G_TYPE_ERROR)); - g_assert_cmpstr (g_type_name (G_VALUE_TYPE (v1)), ==, - g_type_name (G_TYPE_ERROR)); - - error = (GError*) g_value_get_boxed (v); - error1 = (GError*) g_value_get_boxed (v1); - - g_assert_cmpint (error->domain, ==, error1->domain); - g_assert_cmpint (error->code, ==, error1->code); - g_assert_cmpstr (error->message, ==, error1->message); -} - -/** - * gi_marshalling_tests_ghashtable_enum_none_in: - * @hash_table: (element-type gint GIMarshallingTestsExtraEnum) (transfer none): - */ -void -gi_marshalling_tests_ghashtable_enum_none_in (GHashTable *hash_table) -{ - g_assert_cmpint (GPOINTER_TO_INT (g_hash_table_lookup (hash_table, GINT_TO_POINTER (1))), ==, GI_MARSHALLING_TESTS_EXTRA_ENUM_VALUE1); - g_assert_cmpint (GPOINTER_TO_INT (g_hash_table_lookup (hash_table, GINT_TO_POINTER (2))), ==, GI_MARSHALLING_TESTS_EXTRA_ENUM_VALUE2); - g_assert_cmpint (GPOINTER_TO_INT (g_hash_table_lookup (hash_table, GINT_TO_POINTER (3))), ==, GI_MARSHALLING_TESTS_EXTRA_ENUM_VALUE3); -} - -/** - * gi_marshalling_tests_ghashtable_enum_none_return: - * - * Returns: (element-type gint GIMarshallingTestsExtraEnum) (transfer none): - */ -GHashTable * -gi_marshalling_tests_ghashtable_enum_none_return (void) -{ - static GHashTable *hash_table = NULL; - - if (hash_table == NULL) - { - hash_table = g_hash_table_new (NULL, NULL); - g_hash_table_insert (hash_table, GINT_TO_POINTER (1), GINT_TO_POINTER (GI_MARSHALLING_TESTS_EXTRA_ENUM_VALUE1)); - g_hash_table_insert (hash_table, GINT_TO_POINTER (2), GINT_TO_POINTER (GI_MARSHALLING_TESTS_EXTRA_ENUM_VALUE2)); - g_hash_table_insert (hash_table, GINT_TO_POINTER (3), GINT_TO_POINTER (GI_MARSHALLING_TESTS_EXTRA_ENUM_VALUE3)); - } - - return hash_table; -} - -/** - * gi_marshalling_tests_filename_copy: - * @path_in: (type filename) (nullable) - * - * Returns: (type filename) (nullable) - */ -gchar * -gi_marshalling_tests_filename_copy (gchar *path_in) -{ - return g_strdup (path_in); -} - -/** - * gi_marshalling_tests_filename_to_glib_repr: - * @path_in: (type filename) (nullable) - * - * Returns: (array length=len) (element-type guint8) - */ -gchar * -gi_marshalling_tests_filename_to_glib_repr (gchar *path_in, gsize *len) -{ - *len = strlen(path_in); - return g_strdup (path_in); -} - -/** - * gi_marshalling_tests_filename_exists: - * @path: (type filename) - */ -gboolean -gi_marshalling_tests_filename_exists (gchar *path) -{ - return g_file_test (path, G_FILE_TEST_EXISTS); -} diff --git a/tests/gimarshallingtestsextra.h b/tests/gimarshallingtestsextra.h deleted file mode 100644 index 5452688..0000000 --- a/tests/gimarshallingtestsextra.h +++ /dev/null @@ -1,40 +0,0 @@ -/* gimarshallingtestsextra.h - * - * Copyright (C) 2016 Thibault Saunier <tsaunier@gnome.org> - * - * This file is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 3 of the - * License, or (at your option) any later version. - * - * This file is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - */ - -#ifndef EXTRA_TESTS -#define EXTRA_TESTS - -#include <glib-object.h> - -typedef enum -{ - GI_MARSHALLING_TESTS_EXTRA_ENUM_VALUE1, - GI_MARSHALLING_TESTS_EXTRA_ENUM_VALUE2, - GI_MARSHALLING_TESTS_EXTRA_ENUM_VALUE3 = 42 -} GIMarshallingTestsExtraEnum; - - -void gi_marshalling_tests_compare_two_gerrors_in_gvalue (GValue *v, GValue *v1); -void gi_marshalling_tests_ghashtable_enum_none_in (GHashTable *hash_table); -GHashTable * gi_marshalling_tests_ghashtable_enum_none_return (void); - -gchar * gi_marshalling_tests_filename_copy (gchar *path_in); -gboolean gi_marshalling_tests_filename_exists (gchar *path); -gchar * gi_marshalling_tests_filename_to_glib_repr (gchar *path_in, gsize *len); - -#endif /* EXTRA_TESTS */ diff --git a/tests/helper.py b/tests/helper.py deleted file mode 100644 index 0d2f204..0000000 --- a/tests/helper.py +++ /dev/null @@ -1,132 +0,0 @@ -import contextlib -import unittest -import inspect -import warnings -import functools -import sys -from collections import namedtuple - -import gi -from gi import PyGIDeprecationWarning -from gi.repository import GLib - -from compathelper import StringIO - - -ExceptionInfo = namedtuple("ExceptionInfo", ["type", "value", "traceback"]) -"""The type used for storing exceptions used by capture_exceptions()""" - - -@contextlib.contextmanager -def capture_exceptions(): - """Installs a temporary sys.excepthook which records all exceptions - instead of printing them. - """ - - exceptions = [] - - def custom_excepthook(*args): - exceptions.append(ExceptionInfo(*args)) - - old_hook = sys.excepthook - sys.excepthook = custom_excepthook - try: - yield exceptions - finally: - sys.excepthook = old_hook - - -def ignore_gi_deprecation_warnings(func_or_class): - """A unittest class and function decorator which makes them ignore - PyGIDeprecationWarning. - """ - - if inspect.isclass(func_or_class): - assert issubclass(func_or_class, unittest.TestCase) - cls = func_or_class - for name, value in cls.__dict__.items(): - if callable(value) and name.startswith("test_"): - new_value = ignore_gi_deprecation_warnings(value) - setattr(cls, name, new_value) - return cls - else: - func = func_or_class - - @functools.wraps(func) - def wrapper(*args, **kwargs): - with capture_gi_deprecation_warnings(): - return func(*args, **kwargs) - - return wrapper - - -@contextlib.contextmanager -def capture_gi_deprecation_warnings(): - """Temporarily suppress PyGIDeprecationWarning output and record them""" - - with warnings.catch_warnings(record=True) as warn: - warnings.simplefilter('always', category=PyGIDeprecationWarning) - yield warn - - -@contextlib.contextmanager -def capture_glib_warnings(allow_warnings=False, allow_criticals=False): - """Temporarily suppress glib warning output and record them. - - The test suite is run with G_DEBUG="fatal-warnings fatal-criticals" - by default. Setting allow_warnings and allow_criticals will temporarily - allow warnings or criticals without terminating the test run. - """ - - old_mask = GLib.log_set_always_fatal(GLib.LogLevelFlags(0)) - - new_mask = old_mask - if allow_warnings: - new_mask &= ~GLib.LogLevelFlags.LEVEL_WARNING - if allow_criticals: - new_mask &= ~GLib.LogLevelFlags.LEVEL_CRITICAL - - GLib.log_set_always_fatal(GLib.LogLevelFlags(new_mask)) - - GLibWarning = gi._gi.Warning - try: - with warnings.catch_warnings(record=True) as warn: - warnings.filterwarnings('always', category=GLibWarning) - yield warn - finally: - GLib.log_set_always_fatal(old_mask) - - -@contextlib.contextmanager -def capture_glib_deprecation_warnings(): - """Temporarily suppress glib deprecation warning output and record them""" - - GLibWarning = gi._gi.Warning - with warnings.catch_warnings(record=True) as warn: - warnings.filterwarnings( - 'always', category=GLibWarning, - message=".+ is deprecated and shouldn't be used anymore\\. " - "It will be removed in a future version\\.") - yield warn - - -@contextlib.contextmanager -def capture_output(): - """ - with capture_output as (stdout, stderr): - some_action() - print(stdout.getvalue(), stderr.getvalue()) - """ - - err = StringIO() - out = StringIO() - old_err = sys.stderr - old_out = sys.stdout - sys.stderr = err - sys.stdout = out - - try: - yield (out, err) - finally: - sys.stderr = old_err - sys.stdout = old_out diff --git a/tests/org.gnome.test.gschema.xml b/tests/org.gnome.test.gschema.xml index eb9aab8..221b87a 100644 --- a/tests/org.gnome.test.gschema.xml +++ b/tests/org.gnome.test.gschema.xml @@ -1,10 +1,4 @@ <schemalist> - <enum id="org.gnome.test.FruitType"> - <value nick="banana" value="0"/> - <value nick="apple" value="1"/> - <value nick="pear" value="2"/> - </enum> - <schema id="org.gnome.test" path="/tests/"> <key name="test-boolean" type="b"> <default>true</default> @@ -18,9 +12,6 @@ <key name="test-array" type="ai"> <default>[1,2]</default> </key> - <key name="test-enum" enum="org.gnome.test.FruitType"> - <default>'banana'</default> - </key> </schema> <schema id="org.gnome.nopathtest"> diff --git a/tests/runtests-windows.py b/tests/runtests-windows.py new file mode 100644 index 0000000..ae81202 --- /dev/null +++ b/tests/runtests-windows.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + + +import os +import sys +import glob +import unittest + +os.environ['PYGTK_USE_GIL_STATE_API'] = '' +sys.path.insert(0, os.path.dirname(__file__)) +sys.argv.append('--g-fatal-warnings') + +from gi.repository import GObject +GObject.threads_init() + + +SKIP_FILES = ['runtests', + 'test_mainloop', # no os.fork on windows + 'test_subprocess'] # blocks on testChildWatch + + +if __name__ == '__main__': + testdir = os.path.split(os.path.abspath(__file__))[0] + os.chdir(testdir) + + def gettestnames(): + files = glob.glob('*.py') + names = map(lambda x: x[:-3], files) + map(names.remove, SKIP_FILES) + return names + + suite = unittest.TestSuite() + loader = unittest.TestLoader() + + for name in gettestnames(): + try: + suite.addTest(loader.loadTestsFromName(name)) + except Exception, e: + print 'Could not load %s: %s' % (name, e) + + testRunner = unittest.TextTestRunner() + testRunner.verbosity = 2 + testRunner.run(suite) diff --git a/tests/runtests.py b/tests/runtests.py index fda4dd1..4dddc72 100755 --- a/tests/runtests.py +++ b/tests/runtests.py @@ -7,76 +7,22 @@ import sys import unittest -# this was renamed in Python 3, provide backwards compatible name -if sys.version_info[:2] == (2, 7): - unittest.TestCase.assertRaisesRegex = unittest.TestCase.assertRaisesRegexp - -if sys.version_info[0] == 3: - unittest.TestCase.assertRegexpMatches = unittest.TestCase.assertRegex - unittest.TestCase.assertRaisesRegexp = unittest.TestCase.assertRaisesRegex - - if '--help' in sys.argv: print("Usage: ./runtests.py <testfiles>") sys.exit(0) mydir = os.path.dirname(os.path.abspath(__file__)) -tests_builddir = os.path.abspath(os.environ.get('TESTS_BUILDDIR', os.path.dirname(__file__))) -builddir = os.path.dirname(tests_builddir) -tests_srcdir = os.path.abspath(os.path.dirname(__file__)) -srcdir = os.path.dirname(tests_srcdir) - -sys.path.insert(0, tests_srcdir) -sys.path.insert(0, srcdir) -sys.path.insert(0, tests_builddir) -sys.path.insert(0, builddir) # force untranslated messages, as we check for them in some tests os.environ['LC_MESSAGES'] = 'C' os.environ['G_DEBUG'] = 'fatal-warnings fatal-criticals' -if sys.platform == "darwin": - # gtk 3.22 has warnings and ciriticals on OS X, ignore for now - os.environ['G_DEBUG'] = '' # make Gio able to find our gschemas.compiled in tests/. This needs to be set # before importing Gio. Support a separate build tree, so look in build dir # first. os.environ['GSETTINGS_BACKEND'] = 'memory' -os.environ['GSETTINGS_SCHEMA_DIR'] = tests_builddir -os.environ['G_FILENAME_ENCODING'] = 'UTF-8' - -import gi -gi.require_version("GIRepository", "2.0") -from gi.repository import GIRepository -repo = GIRepository.Repository.get_default() -repo.prepend_library_path(os.path.join(tests_builddir, ".libs")) -repo.prepend_search_path(tests_builddir) - - -def try_require_version(namespace, version): - try: - gi.require_version(namespace, version) - except ValueError: - # prevent tests from running with the wrong version - sys.modules["gi.repository." + namespace] = None - - -# Optional -try_require_version("Gtk", os.environ.get("TEST_GTK_VERSION", "3.0")) -try_require_version("Gdk", os.environ.get("TEST_GTK_VERSION", "3.0")) -try_require_version("GdkPixbuf", "2.0") -try_require_version("Pango", "1.0") -try_require_version("PangoCairo", "1.0") -try_require_version("Atk", "1.0") - -# Required -gi.require_versions({ - "GIMarshallingTests": "1.0", - "Regress": "1.0", - "GLib": "2.0", - "Gio": "2.0", - "GObject": "2.0", -}) +os.environ['GSETTINGS_SCHEMA_DIR'] = os.environ.get('TESTS_BUILDDIR', + os.path.dirname(__file__)) # Load tests. if 'TEST_NAMES' in os.environ: diff --git a/tests/test-thread.c b/tests/test-thread.c index 438cb97..0f5b909 100644 --- a/tests/test-thread.c +++ b/tests/test-thread.c @@ -43,7 +43,8 @@ other_thread_cb (TestThread *self) static void test_thread_emit_signal (TestThread *self) { - self->thread = g_thread_new ("t", (GThreadFunc)other_thread_cb, self); + self->thread = g_thread_create ((GThreadFunc)other_thread_cb, + self, TRUE, NULL); } static void test_thread_init (TestThread *self) {} diff --git a/tests/test-unknown.c b/tests/test-unknown.c index f1c3139..85aba73 100644 --- a/tests/test-unknown.c +++ b/tests/test-unknown.c @@ -53,7 +53,7 @@ test_interface_get_type (void) return gtype; } -static void test_unknown_iface_method (TestInterface *iface) +void test_unknown_iface_method (TestInterface *iface) { } diff --git a/tests/test_atoms.py b/tests/test_atoms.py index a2c2d5b..851368f 100644 --- a/tests/test_atoms.py +++ b/tests/test_atoms.py @@ -1,38 +1,13 @@ -import os -import sys import unittest -try: - from gi.repository import Gtk, Atk, Gdk -except ImportError: - Gdk = None - Atk = None - Gtk = None +from gi.repository import Gdk, Gtk -from helper import capture_glib_deprecation_warnings - -@unittest.skipUnless(Gdk, 'Gdk not available') class TestGdkAtom(unittest.TestCase): def test_create(self): atom = Gdk.Atom.intern('my_string', False) self.assertEqual(atom.name(), 'my_string') - def test_str(self): - atom = Gdk.Atom.intern('my_string', False) - self.assertEqual(str(atom), 'my_string') - - self.assertEqual(str(Gdk.SELECTION_CLIPBOARD), 'CLIPBOARD') - - def test_repr(self): - # __repr__ should generate a string which is parsable when possible - # http://docs.python.org/2/reference/datamodel.html#object.__repr__ - atom = Gdk.Atom.intern('my_string', False) - self.assertEqual(repr(atom), 'Gdk.Atom.intern("my_string", False)') - self.assertEqual(eval(repr(atom)), atom) - - self.assertEqual(repr(Gdk.SELECTION_CLIPBOARD), 'Gdk.Atom.intern("CLIPBOARD", False)') - def test_in_single(self): a_selection = Gdk.Atom.intern('test_clipboard', False) clipboard = Gtk.Clipboard.get(a_selection) @@ -56,34 +31,10 @@ class TestGdkAtom(unittest.TestCase): self.assertTrue(Gtk.targets_include_image([a_jpeg], False)) self.assertTrue(Gtk.targets_include_image([a_jpeg, a_plain], False)) - @unittest.skipIf(sys.platform == "darwin", "fails on OSX") - def test_out_array(self): - a_selection = Gdk.Atom.intern('my_clipboard', False) - clipboard = Gtk.Clipboard.get(a_selection) - - # empty - (res, targets) = clipboard.wait_for_targets() - self.assertEqual(res, False) - self.assertEqual(targets, []) - - # text - clipboard.set_text('hello', 5) - (res, targets) = clipboard.wait_for_targets() - self.assertEqual(res, True) - self.assertNotEqual(targets, []) - self.assertEqual(type(targets[0]), Gdk.Atom) - names = [t.name() for t in targets] - self.assertFalse(None in names, names) - self.assertTrue('TEXT' in names, names) - - @unittest.skipIf(sys.platform == "darwin" or os.name == "nt", - "fails on OSX/Windows") - @unittest.skipIf(not Gdk or Gdk._version == "4.0", "not in gdk4") def test_out_glist(self): display = Gdk.Display.get_default() - with capture_glib_deprecation_warnings(): - dm = display.get_device_manager() - device = dm.get_client_pointer() + dm = display.get_device_manager() + device = dm.get_client_pointer() axes = device.list_axes() axes_names = [atom.name() for atom in axes] self.assertNotEqual(axes_names, []) diff --git a/tests/test_cairo.py b/tests/test_cairo.py deleted file mode 100644 index 3edf5d5..0000000 --- a/tests/test_cairo.py +++ /dev/null @@ -1,164 +0,0 @@ -# -*- Mode: Python; py-indent-offset: 4 -*- -# coding=utf-8 -# vim: tabstop=4 shiftwidth=4 expandtab - -import unittest - -import gi - -try: - gi.require_foreign('cairo') - import cairo - has_cairo = True -except ImportError: - has_cairo = False - -has_region = has_cairo and hasattr(cairo, "Region") - -try: - from gi.repository import Gtk, Gdk - Gtk, Gdk # pyflakes -except: - Gtk = None - Gdk = None - -from gi.repository import GObject, Regress - - -@unittest.skipUnless(has_cairo, 'built without cairo support') -class Test(unittest.TestCase): - def test_cairo_context(self): - context = Regress.test_cairo_context_full_return() - self.assertTrue(isinstance(context, cairo.Context)) - - surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 10, 10) - context = cairo.Context(surface) - Regress.test_cairo_context_none_in(context) - - def test_cairo_surface(self): - surface = Regress.test_cairo_surface_none_return() - self.assertTrue(isinstance(surface, cairo.ImageSurface)) - self.assertTrue(isinstance(surface, cairo.Surface)) - self.assertEqual(surface.get_format(), cairo.FORMAT_ARGB32) - self.assertEqual(surface.get_width(), 10) - self.assertEqual(surface.get_height(), 10) - - surface = Regress.test_cairo_surface_full_return() - self.assertTrue(isinstance(surface, cairo.ImageSurface)) - self.assertTrue(isinstance(surface, cairo.Surface)) - self.assertEqual(surface.get_format(), cairo.FORMAT_ARGB32) - self.assertEqual(surface.get_width(), 10) - self.assertEqual(surface.get_height(), 10) - - surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 10, 10) - Regress.test_cairo_surface_none_in(surface) - - surface = Regress.test_cairo_surface_full_out() - self.assertTrue(isinstance(surface, cairo.ImageSurface)) - self.assertTrue(isinstance(surface, cairo.Surface)) - self.assertEqual(surface.get_format(), cairo.FORMAT_ARGB32) - self.assertEqual(surface.get_width(), 10) - self.assertEqual(surface.get_height(), 10) - - def test_require_foreign(self): - self.assertEqual(gi.require_foreign('cairo'), None) - self.assertEqual(gi.require_foreign('cairo', 'Context'), None) - self.assertRaises(ImportError, gi.require_foreign, 'invalid_module') - self.assertRaises(ImportError, gi.require_foreign, 'invalid_module', 'invalid_symbol') - self.assertRaises(ImportError, gi.require_foreign, 'cairo', 'invalid_symbol') - - -@unittest.skipUnless(has_cairo, 'built without cairo support') -@unittest.skipUnless(has_region, 'built without cairo.Region support') -@unittest.skipUnless(Gdk, 'Gdk not available') -class TestRegion(unittest.TestCase): - - def test_region_to_py(self): - surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 10, 10) - context = cairo.Context(surface) - context.paint() - region = Gdk.cairo_region_create_from_surface(surface) - r = region.get_extents() - self.assertEqual((r.height, r.width), (10, 10)) - - def test_region_from_py(self): - surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 10, 10) - context = cairo.Context(surface) - region = cairo.Region(cairo.RectangleInt(0, 0, 42, 42)) - Gdk.cairo_region(context, region) - self.assertTrue("42" in repr(list(context.copy_path()))) - - -@unittest.skipUnless(has_cairo, 'built without cairo support') -@unittest.skipUnless(Gtk, 'Gtk not available') -class TestPango(unittest.TestCase): - def test_cairo_font_options(self): - screen = Gtk.Window().get_screen() - font_opts = screen.get_font_options() - self.assertEqual(type(font_opts.get_subpixel_order()), int) - - -if has_cairo: - from gi.repository import cairo as CairoGObject - - # Use PyGI signals to test non-introspected foreign marshaling. - class CairoSignalTester(GObject.Object): - sig_context = GObject.Signal(arg_types=[CairoGObject.Context]) - sig_surface = GObject.Signal(arg_types=[CairoGObject.Surface]) - sig_font_face = GObject.Signal(arg_types=[CairoGObject.FontFace]) - sig_scaled_font = GObject.Signal(arg_types=[CairoGObject.ScaledFont]) - sig_pattern = GObject.Signal(arg_types=[CairoGObject.Pattern]) - - -@unittest.skipUnless(has_cairo, 'built without cairo support') -class TestSignalMarshaling(unittest.TestCase): - # Tests round tripping of cairo objects through non-introspected signals. - - def setUp(self): - self.surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 10, 10) - self.context = cairo.Context(self.surface) - self.tester = CairoSignalTester() - - def pass_object_through_signal(self, obj, signal): - """Pass the given `obj` through the `signal` emission storing the - `obj` passed through the signal and returning it.""" - passthrough_result = [] - - def callback(instance, passthrough): - passthrough_result.append(passthrough) - - signal.connect(callback) - signal.emit(obj) - - return passthrough_result[0] - - def test_context(self): - result = self.pass_object_through_signal(self.context, self.tester.sig_context) - self.assertTrue(isinstance(result, cairo.Context)) - - def test_surface(self): - result = self.pass_object_through_signal(self.surface, self.tester.sig_surface) - self.assertTrue(isinstance(result, cairo.Surface)) - - def test_font_face(self): - font_face = self.context.get_font_face() - result = self.pass_object_through_signal(font_face, self.tester.sig_font_face) - self.assertTrue(isinstance(result, cairo.FontFace)) - - def test_scaled_font(self): - scaled_font = cairo.ScaledFont(self.context.get_font_face(), - cairo.Matrix(), - cairo.Matrix(), - self.context.get_font_options()) - result = self.pass_object_through_signal(scaled_font, self.tester.sig_scaled_font) - self.assertTrue(isinstance(result, cairo.ScaledFont)) - - def test_pattern(self): - pattern = cairo.SolidPattern(1, 1, 1, 1) - result = self.pass_object_through_signal(pattern, self.tester.sig_pattern) - self.assertTrue(isinstance(result, cairo.Pattern)) - self.assertTrue(isinstance(result, cairo.SolidPattern)) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/test_docstring.py b/tests/test_docstring.py deleted file mode 100644 index 29b7e5e..0000000 --- a/tests/test_docstring.py +++ /dev/null @@ -1,132 +0,0 @@ -import unittest - -import gi.docstring - -from gi.repository import Regress -from gi.repository import GIMarshallingTests -from gi.repository import Gio -from gi.repository import GObject -from gi.repository import GLib - -try: - from gi.repository import Gtk -except ImportError: - Gtk = None - - -class Test(unittest.TestCase): - def test_api(self): - new_func = lambda info: 'docstring test' - old_func = gi.docstring.get_doc_string_generator() - - gi.docstring.set_doc_string_generator(new_func) - self.assertEqual(gi.docstring.get_doc_string_generator(), - new_func) - self.assertEqual(gi.docstring.generate_doc_string(None), - 'docstring test') - - # Set back to original generator - gi.docstring.set_doc_string_generator(old_func) - self.assertEqual(gi.docstring.get_doc_string_generator(), - old_func) - - def test_final_signature_with_full_inout(self): - self.assertEqual(GIMarshallingTests.Object.full_inout.__doc__, - 'full_inout(object:GIMarshallingTests.Object) -> object:GIMarshallingTests.Object') - - def test_overridden_doc_is_not_clobbered(self): - self.assertEqual(GIMarshallingTests.OverridesObject.method.__doc__, - 'Overridden doc string.') - - def test_allow_none_with_user_data_defaults(self): - g_file_copy_doc = 'copy(self, destination:Gio.File, ' \ - 'flags:Gio.FileCopyFlags, ' \ - 'cancellable:Gio.Cancellable=None, ' \ - 'progress_callback:Gio.FileProgressCallback=None, ' \ - 'progress_callback_data=None) -> bool' - - self.assertEqual(Gio.File.copy.__doc__, g_file_copy_doc) - - def test_array_length_arg(self): - self.assertEqual(GIMarshallingTests.array_in.__doc__, - 'array_in(ints:list)') - - def test_init_function(self): - # This tests implicit array length args along with skipping a - # boolean return - self.assertEqual(GIMarshallingTests.init_function.__doc__, - 'init_function(argv:list=None) -> bool, argv:list') - - def test_boolean_return(self): - self.assertEqual(GIMarshallingTests.boolean_return_true.__doc__, - 'boolean_return_true() -> bool') - - @unittest.skipUnless((GLib.MAJOR_VERSION, GLib.MINOR_VERSION) >= (2, 42), - "nullable was added in newer glib/gi") - # https://bugzilla.gnome.org/show_bug.cgi?id=740301 - def test_may_return_none(self): - self.assertEqual(Gio.File.get_basename.__doc__, - 'get_basename(self) -> str or None') - - def test_class_doc_constructors(self): - doc = GIMarshallingTests.Object.__doc__ - self.assertTrue('new(int_:int)' in doc) - - def test_struct_doc_constructors(self): - doc = GIMarshallingTests.BoxedStruct.__doc__ - self.assertTrue('new()' in doc) - self.assertTrue('BoxedStruct()' in doc) - - def test_private_struct_constructors(self): - # Structs without a size or constructor should have no constructor docs. - doc = Regress.TestBoxedPrivate.__doc__ - self.assertEqual(doc, '') - - def test_array_inout_etc(self): - self.assertEqual(GIMarshallingTests.array_inout_etc.__doc__, - 'array_inout_etc(first:int, ints:list, last:int) -> ints:list, sum:int') - - def test_array_out_etc(self): - self.assertEqual(GIMarshallingTests.array_out_etc.__doc__, - 'array_out_etc(first:int, last:int) -> ints:list, sum:int') - - @unittest.skipUnless(Gtk, 'no Gtk') - def test_shared_array_length_with_prior_out_arg(self): - # Test the 'iter' out argument does not effect length argument skipping. - self.assertEqual(Gtk.ListStore.insert_with_valuesv.__doc__, - 'insert_with_valuesv(self, position:int, columns:list, values:list) -> iter:Gtk.TreeIter') - - def test_sub_class_doc(self): - class A(GObject.Object): - """first doc""" - pass - - class B(A): - """second doc""" - pass - - self.assertEqual(A.__doc__, "first doc") - self.assertEqual(B.__doc__, "second doc") - - def test_sub_class_no_doc(self): - class A(GObject.Object): - pass - - class B(A): - """sub-class doc""" - - self.assertEqual(A.__doc__, None) - self.assertEqual(B.__doc__, "sub-class doc") - - @unittest.expectedFailure # https://bugzilla.gnome.org/show_bug.cgi?id=734926 - def test_sub_class_doc_setattr(self): - class A(GObject.Object): - pass - - class B(A): - pass - - A.__doc__ = 'custom doc' - - self.assertEqual(A.__doc__, "custom doc") - self.assertEqual(B.__doc__, "custom doc") diff --git a/tests/test_error.py b/tests/test_error.py deleted file mode 100644 index 5702490..0000000 --- a/tests/test_error.py +++ /dev/null @@ -1,144 +0,0 @@ -# -*- Mode: Python; py-indent-offset: 4 -*- -# vim: tabstop=4 shiftwidth=4 expandtab -# -# test_error.py: Tests for GError wrapper implementation -# -# Copyright (C) 2012 Will Thompson -# Copyright (C) 2013 Martin Pitt -# Copyright (C) 2014 Simon Feltman <sfeltman@gnome.org> -# -# This library is free software; you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public -# License as published by the Free Software Foundation; either -# version 2.1 of the License, or (at your option) any later version. -# -# This library is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 -# USA - -import unittest - -from gi.repository import GLib -from gi.repository import GIMarshallingTests - - -class TestType(unittest.TestCase): - def test_attributes(self): - e = GLib.Error('test message', 'mydomain', 42) - self.assertEqual(e.message, 'test message') - self.assertEqual(e.domain, 'mydomain') - self.assertEqual(e.code, 42) - - def test_new_literal(self): - mydomain = GLib.quark_from_string('mydomain') - e = GLib.Error.new_literal(mydomain, 'test message', 42) - self.assertEqual(e.message, 'test message') - self.assertEqual(e.domain, 'mydomain') - self.assertEqual(e.code, 42) - - def test_matches(self): - mydomain = GLib.quark_from_string('mydomain') - notmydomain = GLib.quark_from_string('notmydomain') - e = GLib.Error('test message', 'mydomain', 42) - self.assertTrue(e.matches(mydomain, 42)) - self.assertFalse(e.matches(notmydomain, 42)) - self.assertFalse(e.matches(mydomain, 40)) - - def test_str(self): - e = GLib.Error('test message', 'mydomain', 42) - self.assertEqual(str(e), - 'mydomain: test message (42)') - - def test_repr(self): - e = GLib.Error('test message', 'mydomain', 42) - self.assertEqual(repr(e), - "GLib.Error('test message', 'mydomain', 42)") - - def test_inheritance(self): - self.assertTrue(issubclass(GLib.Error, RuntimeError)) - - -class ObjectWithVFuncException(GIMarshallingTests.Object): - def do_vfunc_meth_with_err(self, x): - if x == 42: - return True - - raise GLib.Error('unexpected value %d' % x, 'mydomain', 42) - - -class TestMarshalling(unittest.TestCase): - def test_array_in_crash(self): - # Previously there was a bug in invoke, in which C arrays were unwrapped - # from inside GArrays to be passed to the C function. But when a GError was - # set, invoke would attempt to free the C array as if it were a GArray. - # This crash is only for C arrays. It does not happen for C functions which - # take in GArrays. See https://bugzilla.gnome.org/show_bug.cgi?id=642708 - self.assertRaises(GLib.Error, GIMarshallingTests.gerror_array_in, [1, 2, 3]) - - def test_out(self): - # See https://bugzilla.gnome.org/show_bug.cgi?id=666098 - error, debug = GIMarshallingTests.gerror_out() - - self.assertIsInstance(error, GLib.Error) - self.assertEqual(error.domain, GIMarshallingTests.CONSTANT_GERROR_DOMAIN) - self.assertEqual(error.code, GIMarshallingTests.CONSTANT_GERROR_CODE) - self.assertEqual(error.message, GIMarshallingTests.CONSTANT_GERROR_MESSAGE) - self.assertEqual(debug, GIMarshallingTests.CONSTANT_GERROR_DEBUG_MESSAGE) - - def test_out_transfer_none(self): - # See https://bugzilla.gnome.org/show_bug.cgi?id=666098 - error, debug = GIMarshallingTests.gerror_out_transfer_none() - - self.assertIsInstance(error, GLib.Error) - self.assertEqual(error.domain, GIMarshallingTests.CONSTANT_GERROR_DOMAIN) - self.assertEqual(error.code, GIMarshallingTests.CONSTANT_GERROR_CODE) - self.assertEqual(error.message, GIMarshallingTests.CONSTANT_GERROR_MESSAGE) - self.assertEqual(GIMarshallingTests.CONSTANT_GERROR_DEBUG_MESSAGE, debug) - - def test_return(self): - # See https://bugzilla.gnome.org/show_bug.cgi?id=666098 - error = GIMarshallingTests.gerror_return() - - self.assertIsInstance(error, GLib.Error) - self.assertEqual(error.domain, GIMarshallingTests.CONSTANT_GERROR_DOMAIN) - self.assertEqual(error.code, GIMarshallingTests.CONSTANT_GERROR_CODE) - self.assertEqual(error.message, GIMarshallingTests.CONSTANT_GERROR_MESSAGE) - - def test_exception(self): - with self.assertRaises(GLib.Error) as context: - GIMarshallingTests.gerror() - - e = context.exception - self.assertEqual(e.domain, GIMarshallingTests.CONSTANT_GERROR_DOMAIN) - self.assertEqual(e.code, GIMarshallingTests.CONSTANT_GERROR_CODE) - self.assertEqual(e.message, GIMarshallingTests.CONSTANT_GERROR_MESSAGE) - - def test_vfunc_no_exception(self): - obj = ObjectWithVFuncException() - self.assertTrue(obj.vfunc_meth_with_error(42)) - - def test_vfunc_gerror_exception(self): - obj = ObjectWithVFuncException() - with self.assertRaises(GLib.Error) as context: - obj.vfunc_meth_with_error(-1) - - e = context.exception - self.assertEqual(e.message, 'unexpected value -1') - self.assertEqual(e.domain, 'mydomain') - self.assertEqual(e.code, 42) - - def tests_compare_two_gerrors_in_gvalue(self): - error = GLib.Error.new_literal(1, "error", 1) - error1 = GLib.Error.new_literal(1, "error", 1) - - GIMarshallingTests.compare_two_gerrors_in_gvalue(error, error1) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/test_everything.py b/tests/test_everything.py index 0378781..563936b 100644 --- a/tests/test_everything.py +++ b/tests/test_everything.py @@ -3,24 +3,18 @@ # vim: tabstop=4 shiftwidth=4 expandtab import unittest -import traceback -import ctypes -import warnings + import sys +sys.path.insert(0, "../") +from sys import getrefcount + +import copy +import cairo -from gi.repository import Regress as Everything from gi.repository import GObject from gi.repository import GLib from gi.repository import Gio - -try: - from gi.repository import Gtk - Gtk # pyflakes -except: - Gtk = None - -from helper import capture_exceptions - +from gi.repository import Regress as Everything if sys.version_info < (3, 0): UNICHAR = "\xe2\x99\xa5" @@ -29,149 +23,40 @@ else: UNICHAR = "♥" -const_str = b'const \xe2\x99\xa5 utf8' -if sys.version_info >= (3, 0): - const_str = const_str.decode('UTF-8') -noconst_str = 'non' + const_str - - -class RawGList(ctypes.Structure): - _fields_ = [('data', ctypes.c_void_p), - ('next', ctypes.c_void_p), - ('prev', ctypes.c_void_p)] - - @classmethod - def from_wrapped(cls, obj): - offset = sys.getsizeof(object()) # size of PyObject_HEAD - return ctypes.POINTER(cls).from_address(id(obj) + offset) - - -class TestInstanceTransfer(unittest.TestCase): - - def test_main(self): - obj = Everything.TestObj() - for _ in range(10): - obj.instance_method_full() - - class TestEverything(unittest.TestCase): - def test_bool(self): - self.assertEqual(Everything.test_boolean(False), False) - self.assertEqual(Everything.test_boolean(True), True) - self.assertEqual(Everything.test_boolean('hello'), True) - self.assertEqual(Everything.test_boolean(''), False) - - self.assertEqual(Everything.test_boolean_true(True), True) - self.assertEqual(Everything.test_boolean_false(False), False) - - def test_int8(self): - self.assertEqual(Everything.test_int8(GLib.MAXINT8), - GLib.MAXINT8) - self.assertEqual(Everything.test_int8(GLib.MININT8), - GLib.MININT8) - self.assertRaises(OverflowError, Everything.test_int8, GLib.MAXINT8 + 1) - - self.assertEqual(Everything.test_uint8(GLib.MAXUINT8), - GLib.MAXUINT8) - self.assertEqual(Everything.test_uint8(0), 0) - self.assertRaises(OverflowError, Everything.test_uint8, -1) - self.assertRaises(OverflowError, Everything.test_uint8, GLib.MAXUINT8 + 1) - - def test_int16(self): - self.assertEqual(Everything.test_int16(GLib.MAXINT16), - GLib.MAXINT16) - self.assertEqual(Everything.test_int16(GLib.MININT16), - GLib.MININT16) - self.assertRaises(OverflowError, Everything.test_int16, GLib.MAXINT16 + 1) - - self.assertEqual(Everything.test_uint16(GLib.MAXUINT16), - GLib.MAXUINT16) - self.assertEqual(Everything.test_uint16(0), 0) - self.assertRaises(OverflowError, Everything.test_uint16, -1) - self.assertRaises(OverflowError, Everything.test_uint16, GLib.MAXUINT16 + 1) - - def test_int32(self): - self.assertEqual(Everything.test_int32(GLib.MAXINT32), - GLib.MAXINT32) - self.assertEqual(Everything.test_int32(GLib.MININT32), - GLib.MININT32) - self.assertRaises(OverflowError, Everything.test_int32, GLib.MAXINT32 + 1) - - self.assertEqual(Everything.test_uint32(GLib.MAXUINT32), - GLib.MAXUINT32) - self.assertEqual(Everything.test_uint32(0), 0) - self.assertRaises(OverflowError, Everything.test_uint32, -1) - self.assertRaises(OverflowError, Everything.test_uint32, GLib.MAXUINT32 + 1) - - def test_int64(self): - self.assertEqual(Everything.test_int64(GLib.MAXINT64), - GLib.MAXINT64) - self.assertEqual(Everything.test_int64(GLib.MININT64), - GLib.MININT64) - self.assertRaises(OverflowError, Everything.test_int64, GLib.MAXINT64 + 1) - - self.assertEqual(Everything.test_uint64(GLib.MAXUINT64), - GLib.MAXUINT64) - self.assertEqual(Everything.test_uint64(0), 0) - self.assertRaises(OverflowError, Everything.test_uint64, -1) - self.assertRaises(OverflowError, Everything.test_uint64, GLib.MAXUINT64 + 1) - - def test_int(self): - self.assertEqual(Everything.test_int(GLib.MAXINT), - GLib.MAXINT) - self.assertEqual(Everything.test_int(GLib.MININT), - GLib.MININT) - self.assertRaises(OverflowError, Everything.test_int, GLib.MAXINT + 1) - - self.assertEqual(Everything.test_uint(GLib.MAXUINT), - GLib.MAXUINT) - self.assertEqual(Everything.test_uint(0), 0) - self.assertRaises(OverflowError, Everything.test_uint, -1) - self.assertRaises(OverflowError, Everything.test_uint, GLib.MAXUINT + 1) - - def test_short(self): - self.assertEqual(Everything.test_short(GLib.MAXSHORT), - GLib.MAXSHORT) - self.assertEqual(Everything.test_short(GLib.MINSHORT), - GLib.MINSHORT) - self.assertRaises(OverflowError, Everything.test_short, GLib.MAXSHORT + 1) - - self.assertEqual(Everything.test_ushort(GLib.MAXUSHORT), - GLib.MAXUSHORT) - self.assertEqual(Everything.test_ushort(0), 0) - self.assertRaises(OverflowError, Everything.test_ushort, -1) - self.assertRaises(OverflowError, Everything.test_ushort, GLib.MAXUSHORT + 1) - - def test_long(self): - self.assertEqual(Everything.test_long(GLib.MAXLONG), - GLib.MAXLONG) - self.assertEqual(Everything.test_long(GLib.MINLONG), - GLib.MINLONG) - self.assertRaises(OverflowError, Everything.test_long, GLib.MAXLONG + 1) - - self.assertEqual(Everything.test_ulong(GLib.MAXULONG), - GLib.MAXULONG) - self.assertEqual(Everything.test_ulong(0), 0) - self.assertRaises(OverflowError, Everything.test_ulong, -1) - self.assertRaises(OverflowError, Everything.test_ulong, GLib.MAXULONG + 1) - - def test_size(self): - self.assertEqual(Everything.test_ssize(GLib.MAXSSIZE), - GLib.MAXSSIZE) - self.assertEqual(Everything.test_ssize(GLib.MINSSIZE), - GLib.MINSSIZE) - self.assertRaises(OverflowError, Everything.test_ssize, GLib.MAXSSIZE + 1) - - self.assertEqual(Everything.test_size(GLib.MAXSIZE), - GLib.MAXSIZE) - self.assertEqual(Everything.test_size(0), 0) - self.assertRaises(OverflowError, Everything.test_size, -1) - self.assertRaises(OverflowError, Everything.test_size, GLib.MAXSIZE + 1) - - def test_timet(self): - self.assertEqual(Everything.test_timet(42), 42) - self.assertRaises(OverflowError, Everything.test_timet, GLib.MAXUINT64 + 1) + def test_cairo_context(self): + context = Everything.test_cairo_context_full_return() + self.assertTrue(isinstance(context, cairo.Context)) + + surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 10, 10) + context = cairo.Context(surface) + Everything.test_cairo_context_none_in(context) + + def test_cairo_surface(self): + surface = Everything.test_cairo_surface_none_return() + self.assertTrue(isinstance(surface, cairo.ImageSurface)) + self.assertTrue(isinstance(surface, cairo.Surface)) + self.assertEqual(surface.get_format(), cairo.FORMAT_ARGB32) + self.assertEqual(surface.get_width(), 10) + self.assertEqual(surface.get_height(), 10) + + surface = Everything.test_cairo_surface_full_return() + self.assertTrue(isinstance(surface, cairo.ImageSurface)) + self.assertTrue(isinstance(surface, cairo.Surface)) + self.assertEqual(surface.get_format(), cairo.FORMAT_ARGB32) + self.assertEqual(surface.get_width(), 10) + self.assertEqual(surface.get_height(), 10) + + surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 10, 10) + Everything.test_cairo_surface_none_in(surface) + + surface = Everything.test_cairo_surface_full_out() + self.assertTrue(isinstance(surface, cairo.ImageSurface)) + self.assertTrue(isinstance(surface, cairo.Surface)) + self.assertEqual(surface.get_format(), cairo.FORMAT_ARGB32) + self.assertEqual(surface.get_width(), 10) + self.assertEqual(surface.get_height(), 10) def test_unichar(self): self.assertEqual("c", Everything.test_unichar("c")) @@ -182,102 +67,6 @@ class TestEverything(unittest.TestCase): self.assertRaises(TypeError, Everything.test_unichar, "") self.assertRaises(TypeError, Everything.test_unichar, "morethanonechar") - def test_float(self): - self.assertEqual(Everything.test_float(GLib.MAXFLOAT), - GLib.MAXFLOAT) - self.assertEqual(Everything.test_float(GLib.MINFLOAT), - GLib.MINFLOAT) - self.assertRaises(OverflowError, Everything.test_float, GLib.MAXFLOAT * 2) - - def test_double(self): - self.assertEqual(Everything.test_double(GLib.MAXDOUBLE), - GLib.MAXDOUBLE) - self.assertEqual(Everything.test_double(GLib.MINDOUBLE), - GLib.MINDOUBLE) - - (two, three) = Everything.test_multi_double_args(2.5) - self.assertAlmostEqual(two, 5.0) - self.assertAlmostEqual(three, 7.5) - - def test_value(self): - self.assertEqual(Everything.test_int_value_arg(GLib.MAXINT), GLib.MAXINT) - self.assertEqual(Everything.test_value_return(GLib.MAXINT), GLib.MAXINT) - - def test_variant(self): - v = Everything.test_gvariant_i() - self.assertEqual(v.get_type_string(), 'i') - self.assertEqual(v.get_int32(), 1) - - v = Everything.test_gvariant_s() - self.assertEqual(v.get_type_string(), 's') - self.assertEqual(v.get_string(), 'one') - - v = Everything.test_gvariant_v() - self.assertEqual(v.get_type_string(), 'v') - vi = v.get_variant() - self.assertEqual(vi.get_type_string(), 's') - self.assertEqual(vi.get_string(), 'contents') - - v = Everything.test_gvariant_as() - self.assertEqual(v.get_type_string(), 'as') - self.assertEqual(v.get_strv(), ['one', 'two', 'three']) - - v = Everything.test_gvariant_asv() - self.assertEqual(v.get_type_string(), 'a{sv}') - self.assertEqual(v.lookup_value('nosuchkey', None), None) - name = v.lookup_value('name', None) - self.assertEqual(name.get_string(), 'foo') - timeout = v.lookup_value('timeout', None) - self.assertEqual(timeout.get_int32(), 10) - - def test_utf8_const_return(self): - self.assertEqual(Everything.test_utf8_const_return(), const_str) - - def test_utf8_nonconst_return(self): - self.assertEqual(Everything.test_utf8_nonconst_return(), noconst_str) - - def test_utf8_out(self): - self.assertEqual(Everything.test_utf8_out(), noconst_str) - - def test_utf8_const_in(self): - Everything.test_utf8_const_in(const_str) - - def test_utf8_inout(self): - self.assertEqual(Everything.test_utf8_inout(const_str), noconst_str) - - def test_filename_return(self): - self.assertEqual(Everything.test_filename_return(), ['åäö', '/etc/fstab']) - - def test_int_out_utf8(self): - # returns g_utf8_strlen() in out argument - self.assertEqual(Everything.test_int_out_utf8(''), 0) - self.assertEqual(Everything.test_int_out_utf8('hello world'), 11) - self.assertEqual(Everything.test_int_out_utf8('åäö'), 3) - - def test_utf8_out_out(self): - self.assertEqual(Everything.test_utf8_out_out(), ('first', 'second')) - - def test_utf8_out_nonconst_return(self): - self.assertEqual(Everything.test_utf8_out_nonconst_return(), ('first', 'second')) - - def test_enum(self): - self.assertEqual(Everything.test_enum_param(Everything.TestEnum.VALUE1), 'value1') - self.assertEqual(Everything.test_enum_param(Everything.TestEnum.VALUE3), 'value3') - self.assertRaises(TypeError, Everything.test_enum_param, 'hello') - - # FIXME: ValueError: invalid enum value: 2147483648 - @unittest.expectedFailure - def test_enum_unsigned(self): - self.assertEqual(Everything.test_unsigned_enum_param(Everything.TestEnumUnsigned.VALUE1), 'value1') - self.assertEqual(Everything.test_unsigned_enum_param(Everything.TestEnumUnsigned.VALUE3), 'value3') - self.assertRaises(TypeError, Everything.test_unsigned_enum_param, 'hello') - - def test_flags(self): - result = Everything.global_get_flags_out() - # assert that it's not an int - self.assertEqual(type(result), Everything.TestFlags) - self.assertEqual(result, Everything.TestFlags.FLAG1 | Everything.TestFlags.FLAG3) - def test_floating(self): e = Everything.TestFloating() self.assertEqual(e.__grefcount__, 1) @@ -317,15 +106,12 @@ class TestEverything(unittest.TestCase): self.assertEqual(struct_b.nested_a.some_double, struct_b_clone.nested_a.some_double) self.assertEqual(struct_b.nested_a.some_enum, struct_b_clone.nested_a.some_enum) - struct_a = Everything.test_struct_a_parse('ignored') - self.assertEqual(struct_a.some_int, 23) - def test_wrong_type_of_arguments(self): try: Everything.test_int8() except TypeError: (e_type, e) = sys.exc_info()[:2] - self.assertEqual(e.args, ("Regress.test_int8() takes exactly 1 argument (0 given)",)) + self.assertEqual(e.args, ("test_int8() takes exactly 1 argument (0 given)",)) def test_gtypes(self): gchararray_gtype = GObject.type_from_name('gchararray') @@ -372,123 +158,18 @@ class TestEverything(unittest.TestCase): # test that there are no duplicates returned self.assertEqual(len(attr_list), len(set(attr_list))) - def test_array_int_in_empty(self): - self.assertEqual(Everything.test_array_int_in([]), 0) - - def test_array_int_in(self): - self.assertEqual(Everything.test_array_int_in([1, 5, -2]), 4) - - def test_array_int_out(self): - self.assertEqual(Everything.test_array_int_out(), [0, 1, 2, 3, 4]) - - def test_array_int_full_out(self): - self.assertEqual(Everything.test_array_int_full_out(), [0, 1, 2, 3, 4]) - - def test_array_int_none_out(self): - self.assertEqual(Everything.test_array_int_none_out(), [1, 2, 3, 4, 5]) - - def test_array_int_inout(self): - self.assertEqual(Everything.test_array_int_inout([1, 5, 42, -8]), [6, 43, -7]) - - def test_array_int_inout_empty(self): - self.assertEqual(Everything.test_array_int_inout([]), []) - - def test_array_gint8_in(self): - if sys.version_info >= (3, 0): - self.assertEqual(Everything.test_array_gint8_in(b'\x01\x03\x05'), 9) - self.assertEqual(Everything.test_array_gint8_in([1, 3, 5, -50]), -41) - - def test_array_gint16_in(self): - self.assertEqual(Everything.test_array_gint16_in([256, 257, -1000, 10000]), 9513) - - def test_array_gint32_in(self): - self.assertEqual(Everything.test_array_gint32_in([30000, 1, -2]), 29999) - - def test_array_gint64_in(self): - self.assertEqual(Everything.test_array_gint64_in([2 ** 33, 2 ** 34]), 2 ** 33 + 2 ** 34) - - def test_array_gtype_in(self): - self.assertEqual(Everything.test_array_gtype_in( - [GObject.TYPE_STRING, GObject.TYPE_UINT64, GObject.TYPE_VARIANT]), - '[gchararray,guint64,GVariant,]') - - def test_array_fixed_size_int_in(self): - # fixed length of 5 - self.assertEqual(Everything.test_array_fixed_size_int_in([1, 2, -10, 5, 3]), 1) - - def test_array_fixed_size_int_in_error(self): - self.assertRaises(ValueError, Everything.test_array_fixed_size_int_in, [1, 2, 3, 4]) - self.assertRaises(ValueError, Everything.test_array_fixed_size_int_in, [1, 2, 3, 4, 5, 6]) - - def test_array_fixed_size_int_out(self): - self.assertEqual(Everything.test_array_fixed_size_int_out(), [0, 1, 2, 3, 4]) - - def test_array_fixed_size_int_return(self): - self.assertEqual(Everything.test_array_fixed_size_int_return(), [0, 1, 2, 3, 4]) - - def test_garray_container_return(self): - # GPtrArray transfer container + def test_ptrarray(self): + # transfer container result = Everything.test_garray_container_return() self.assertEqual(result, ['regress']) result = None - def test_garray_full_return(self): - # GPtrArray transfer full + # transfer full result = Everything.test_garray_full_return() self.assertEqual(result, ['regress']) result = None - def test_strv_out(self): - self.assertEqual(Everything.test_strv_out(), ['thanks', 'for', 'all', 'the', 'fish']) - - def test_strv_out_c(self): - self.assertEqual(Everything.test_strv_out_c(), ['thanks', 'for', 'all', 'the', 'fish']) - - def test_strv_out_container(self): - self.assertEqual(Everything.test_strv_out_container(), ['1', '2', '3']) - - def test_strv_outarg(self): - self.assertEqual(Everything.test_strv_outarg(), ['1', '2', '3']) - - def test_strv_in_gvalue(self): - self.assertEqual(Everything.test_strv_in_gvalue(), ['one', 'two', 'three']) - - def test_strv_in(self): - Everything.test_strv_in(['1', '2', '3']) - - def test_glist(self): - self.assertEqual(Everything.test_glist_nothing_return(), ['1', '2', '3']) - self.assertEqual(Everything.test_glist_nothing_return2(), ['1', '2', '3']) - self.assertEqual(Everything.test_glist_container_return(), ['1', '2', '3']) - self.assertEqual(Everything.test_glist_everything_return(), ['1', '2', '3']) - - Everything.test_glist_nothing_in(['1', '2', '3']) - Everything.test_glist_nothing_in2(['1', '2', '3']) - - @unittest.skipUnless(hasattr(Everything, 'test_glist_gtype_container_in'), - 'Requires newer version of GI') - def test_glist_gtype(self): - Everything.test_glist_gtype_container_in( - [Everything.TestObj, Everything.TestSubObj]) - - def test_gslist(self): - self.assertEqual(Everything.test_gslist_nothing_return(), ['1', '2', '3']) - self.assertEqual(Everything.test_gslist_nothing_return2(), ['1', '2', '3']) - self.assertEqual(Everything.test_gslist_container_return(), ['1', '2', '3']) - self.assertEqual(Everything.test_gslist_everything_return(), ['1', '2', '3']) - - Everything.test_gslist_nothing_in(['1', '2', '3']) - Everything.test_gslist_nothing_in2(['1', '2', '3']) - def test_hash_return(self): - expected = {'foo': 'bar', 'baz': 'bat', 'qux': 'quux'} - - self.assertEqual(Everything.test_ghash_null_return(), None) - self.assertEqual(Everything.test_ghash_nothing_return(), expected) - self.assertEqual(Everything.test_ghash_nothing_return(), expected) - self.assertEqual(Everything.test_ghash_container_return(), expected) - self.assertEqual(Everything.test_ghash_everything_return(), expected) - result = Everything.test_ghash_gvalue_return() self.assertEqual(result['integer'], 12) self.assertEqual(result['boolean'], True) @@ -498,20 +179,12 @@ class TestEverything(unittest.TestCase): self.assertEqual(result['enum'], Everything.TestEnum.VALUE2) result = None - # FIXME: CRITICAL **: Unsupported type ghash - def disabled_test_hash_return_nested(self): - self.assertEqual(Everything.test_ghash_nested_everything_return(), {}) - self.assertEqual(Everything.test_ghash_nested_everything_return2(), {}) - def test_hash_in(self): - expected = {'foo': 'bar', 'baz': 'bat', 'qux': 'quux'} - - Everything.test_ghash_nothing_in(expected) - Everything.test_ghash_nothing_in2(expected) - - def test_hash_in_with_typed_strv(self): + # specifying a simple string array for "strings" does not work due to + # https://bugzilla.gnome.org/show_bug.cgi?id=666636 + # workaround by explicitly building a GStrv object class GStrv(list): - __gtype__ = GObject.TYPE_STRV + __gtype__ = GObject.type_from_name('GStrv') data = {'integer': 12, 'boolean': True, @@ -523,50 +196,25 @@ class TestEverything(unittest.TestCase): Everything.test_ghash_gvalue_in(data) data = None - def test_hash_in_with_gvalue_strv(self): - data = {'integer': 12, - 'boolean': True, - 'string': 'some text', - 'strings': GObject.Value(GObject.TYPE_STRV, ['first', 'second', 'third']), - 'flags': Everything.TestFlags.FLAG1 | Everything.TestFlags.FLAG3, - 'enum': Everything.TestEnum.VALUE2, - } - Everything.test_ghash_gvalue_in(data) - data = None - def test_struct_gpointer(self): - glist = GLib.List() - raw = RawGList.from_wrapped(glist) + l1 = GLib.List() + self.assertEqual(l1.data, None) + init_refcount = getrefcount(l1) - # Note that pointer fields use 0 for NULL in PyGObject and None in ctypes - self.assertEqual(glist.data, 0) - self.assertEqual(raw.contents.data, None) + l1.data = 'foo' + self.assertEqual(l1.data, 'foo') - glist.data = 123 - self.assertEqual(glist.data, 123) - self.assertEqual(raw.contents.data, 123) + l2 = l1 + self.assertEqual(l1.data, l2.data) + self.assertEqual(getrefcount(l1), init_refcount + 1) - glist.data = None - self.assertEqual(glist.data, 0) - self.assertEqual(raw.contents.data, None) - - # Setting to anything other than an int should raise - self.assertRaises(TypeError, setattr, glist.data, 'nan') - self.assertRaises(TypeError, setattr, glist.data, object()) - self.assertRaises(TypeError, setattr, glist.data, 123.321) - - def test_struct_opaque(self): - # we should get a sensible error message - try: - Everything.TestBoxedPrivate() - self.fail('allocating disguised struct without default constructor unexpectedly succeeded') - except TypeError: - (e_type, e_value, e_tb) = sys.exc_info() - self.assertEqual(e_type, TypeError) - self.assertTrue('TestBoxedPrivate' in str(e_value), str(e_value)) - self.assertTrue('constructor' in str(e_value), str(e_value)) - tb = ''.join(traceback.format_exception(e_type, e_value, e_tb)) - self.assertTrue('test_everything.py", line' in tb, tb) + l3 = copy.copy(l1) + l3.data = 'bar' + self.assertEqual(l1.data, 'foo') + self.assertEqual(l2.data, 'foo') + self.assertEqual(l3.data, 'bar') + self.assertEqual(getrefcount(l1), init_refcount + 1) + self.assertEqual(getrefcount(l3), init_refcount) class TestNullableArgs(unittest.TestCase): @@ -608,7 +256,7 @@ class TestNullableArgs(unittest.TestCase): class TestCallbacks(unittest.TestCase): called = False - main_loop = GLib.MainLoop() + main_loop = GObject.MainLoop() def test_callback(self): TestCallbacks.called = False @@ -631,10 +279,7 @@ class TestCallbacks(unittest.TestCase): # note that we do NOT expect the ZeroDivisionError to be propagated # through from the callback, as it crosses the Python<->C boundary # twice. (See GNOME #616279) - with capture_exceptions() as exc: - Everything.test_simple_callback(callback) - self.assertTrue(exc) - self.assertEqual(exc[0].type, ZeroDivisionError) + Everything.test_simple_callback(callback) def test_double_callback_exception(self): """ @@ -653,10 +298,7 @@ class TestCallbacks(unittest.TestCase): # note that we do NOT expect the ZeroDivisionError to be propagated # through from the callback, as it crosses the Python<->C boundary # twice. (See GNOME #616279) - with capture_exceptions() as exc: - Everything.test_simple_callback(callback) - self.assertTrue(exc) - self.assertEqual(exc[0].type, ZeroDivisionError) + Everything.test_simple_callback(callback) def test_return_value_callback(self): TestCallbacks.called = False @@ -668,86 +310,27 @@ class TestCallbacks(unittest.TestCase): self.assertEqual(Everything.test_callback(callback), 44) self.assertTrue(TestCallbacks.called) - def test_callback_scope_async(self): + def test_callback_async(self): TestCallbacks.called = False - ud = 'Test Value 44' - def callback(user_data): - self.assertEqual(user_data, ud) + def callback(foo): TestCallbacks.called = True - return 44 - - ud_refcount = sys.getrefcount(ud) - callback_refcount = sys.getrefcount(callback) + return foo - self.assertEqual(Everything.test_callback_async(callback, ud), None) - # Callback should not have run and the ref count is increased by 1 - self.assertEqual(TestCallbacks.called, False) - self.assertEqual(sys.getrefcount(callback), callback_refcount + 1) - self.assertEqual(sys.getrefcount(ud), ud_refcount + 1) - - # test_callback_thaw_async will run the callback previously supplied. - # references should be auto decremented after this call. - self.assertEqual(Everything.test_callback_thaw_async(), 44) + Everything.test_callback_async(callback, 44) + i = Everything.test_callback_thaw_async() + self.assertEqual(44, i) self.assertTrue(TestCallbacks.called) - # Make sure refcounts are returned to normal - self.assertEqual(sys.getrefcount(callback), callback_refcount) - self.assertEqual(sys.getrefcount(ud), ud_refcount) - - def test_callback_scope_call_multi(self): - # This tests a callback that gets called multiple times from a - # single scope call in python. + def test_callback_scope_call(self): TestCallbacks.called = 0 def callback(): TestCallbacks.called += 1 - return TestCallbacks.called + return 0 - refcount = sys.getrefcount(callback) - result = Everything.test_multi_callback(callback) - # first callback should give 1, second 2, and the function sums them up - self.assertEqual(result, 3) + Everything.test_multi_callback(callback) self.assertEqual(TestCallbacks.called, 2) - self.assertEqual(sys.getrefcount(callback), refcount) - - def test_callback_scope_call_array(self): - # This tests a callback that gets called multiple times from a - # single scope call in python with array arguments - TestCallbacks.callargs = [] - - # FIXME: would be cleaner without the explicit length args: - # def callback(one, two): - def callback(one, one_length, two, two_length): - TestCallbacks.callargs.append((one, two)) - return len(TestCallbacks.callargs) - - refcount = sys.getrefcount(callback) - result = Everything.test_array_callback(callback) - # first callback should give 1, second 2, and the function sums them up - self.assertEqual(result, 3) - self.assertEqual(TestCallbacks.callargs, - [([-1, 0, 1, 2], ['one', 'two', 'three'])] * 2) - self.assertEqual(sys.getrefcount(callback), refcount) - - @unittest.skipUnless(hasattr(Everything, 'test_array_inout_callback'), - 'Requires newer version of GI') - def test_callback_scope_call_array_inout(self): - # This tests a callback that gets called multiple times from a - # single scope call in python with inout array arguments - TestCallbacks.callargs = [] - - def callback(ints, ints_length): - TestCallbacks.callargs.append(ints) - return ints[1:], len(ints[1:]) - - refcount = sys.getrefcount(callback) - result = Everything.test_array_inout_callback(callback) - self.assertEqual(TestCallbacks.callargs, - [[-2, -1, 0, 1, 2], [-1, 0, 1, 2]]) - # first callback should give 4, second 3 - self.assertEqual(result, 3) - self.assertEqual(sys.getrefcount(callback), refcount) def test_callback_userdata(self): TestCallbacks.called = 0 @@ -763,102 +346,27 @@ class TestCallbacks(unittest.TestCase): self.assertEqual(TestCallbacks.called, 100) - def test_callback_userdata_no_user_data(self): - TestCallbacks.called = 0 - - def callback(): - TestCallbacks.called += 1 - return TestCallbacks.called - - for i in range(100): - val = Everything.test_callback_user_data(callback) - self.assertEqual(val, i + 1) - - self.assertEqual(TestCallbacks.called, 100) - - def test_callback_userdata_varargs(self): - TestCallbacks.called = 0 - collected_user_data = [] - - def callback(a, b): - collected_user_data.extend([a, b]) - TestCallbacks.called += 1 - return TestCallbacks.called - - for i in range(10): - val = Everything.test_callback_user_data(callback, 1, 2) - self.assertEqual(val, i + 1) - - self.assertEqual(TestCallbacks.called, 10) - self.assertSequenceEqual(collected_user_data, [1, 2] * 10) - - def test_callback_userdata_as_kwarg_tuple(self): - TestCallbacks.called = 0 - collected_user_data = [] - - def callback(user_data): - collected_user_data.extend(user_data) - TestCallbacks.called += 1 - return TestCallbacks.called - - for i in range(10): - val = Everything.test_callback_user_data(callback, user_data=(1, 2)) - self.assertEqual(val, i + 1) - - self.assertEqual(TestCallbacks.called, 10) - self.assertSequenceEqual(collected_user_data, [1, 2] * 10) - - def test_callback_user_data_middle_none(self): - cb_info = {} - - def callback(userdata): - cb_info['called'] = True - cb_info['userdata'] = userdata - return 1 - - (y, z, q) = Everything.test_torture_signature_2( - 42, callback, None, 'some string', 3) - self.assertEqual(y, 42) - self.assertEqual(z, 84) - self.assertEqual(q, 14) - self.assertTrue(cb_info['called']) - self.assertEqual(cb_info['userdata'], None) - - def test_callback_user_data_middle_single(self): - cb_info = {} + def test_callback_userdata_refcount(self): + TestCallbacks.called = False def callback(userdata): - cb_info['called'] = True - cb_info['userdata'] = userdata + TestCallbacks.called = True return 1 - (y, z, q) = Everything.test_torture_signature_2( - 42, callback, 'User Data', 'some string', 3) - self.assertEqual(y, 42) - self.assertEqual(z, 84) - self.assertEqual(q, 14) - self.assertTrue(cb_info['called']) - self.assertEqual(cb_info['userdata'], 'User Data') + ud = "Test User Data" - def test_callback_user_data_middle_tuple(self): - cb_info = {} + start_ref_count = getrefcount(ud) + for i in range(100): + Everything.test_callback_destroy_notify(callback, ud) - def callback(userdata): - cb_info['called'] = True - cb_info['userdata'] = userdata - return 1 + Everything.test_callback_thaw_notifications() + end_ref_count = getrefcount(ud) - (y, z, q) = Everything.test_torture_signature_2( - 42, callback, (-5, 'User Data'), 'some string', 3) - self.assertEqual(y, 42) - self.assertEqual(z, 84) - self.assertEqual(q, 14) - self.assertTrue(cb_info['called']) - self.assertEqual(cb_info['userdata'], (-5, 'User Data')) + self.assertEqual(start_ref_count, end_ref_count) def test_async_ready_callback(self): TestCallbacks.called = False - TestCallbacks.main_loop = GLib.MainLoop() + TestCallbacks.main_loop = GObject.MainLoop() def callback(obj, result, user_data): TestCallbacks.main_loop.quit() @@ -870,73 +378,15 @@ class TestCallbacks(unittest.TestCase): self.assertTrue(TestCallbacks.called) - def test_callback_scope_notified_with_destroy(self): - TestCallbacks.called = 0 - ud = 'Test scope notified data 33' - + def test_callback_destroy_notify(self): def callback(user_data): - self.assertEqual(user_data, ud) - TestCallbacks.called += 1 - return 33 - - value_refcount = sys.getrefcount(ud) - callback_refcount = sys.getrefcount(callback) - - # Callback is immediately called. - for i in range(100): - res = Everything.test_callback_destroy_notify(callback, ud) - self.assertEqual(res, 33) - - self.assertEqual(TestCallbacks.called, 100) - self.assertEqual(sys.getrefcount(callback), callback_refcount + 100) - self.assertEqual(sys.getrefcount(ud), value_refcount + 100) - - # thaw will call the callback again, this time resources should be freed - self.assertEqual(Everything.test_callback_thaw_notifications(), 33 * 100) - self.assertEqual(TestCallbacks.called, 200) - self.assertEqual(sys.getrefcount(callback), callback_refcount) - self.assertEqual(sys.getrefcount(ud), value_refcount) - - def test_callback_scope_notified_with_destroy_no_user_data(self): - TestCallbacks.called = 0 + TestCallbacks.called = True + return 42 - def callback(user_data): - self.assertEqual(user_data, None) - TestCallbacks.called += 1 - return 34 - - callback_refcount = sys.getrefcount(callback) - - # Run with warning as exception - with warnings.catch_warnings(record=True) as w: - warnings.simplefilter("error") - self.assertRaises(RuntimeWarning, - Everything.test_callback_destroy_notify_no_user_data, - callback) - - self.assertEqual(TestCallbacks.called, 0) - self.assertEqual(sys.getrefcount(callback), callback_refcount) - - # Run with warning as warning - with warnings.catch_warnings(record=True) as w: - # Cause all warnings to always be triggered. - warnings.simplefilter("default") - # Trigger a warning. - res = Everything.test_callback_destroy_notify_no_user_data(callback) - # Verify some things - self.assertEqual(len(w), 1) - self.assertTrue(issubclass(w[-1].category, RuntimeWarning)) - self.assertTrue('Callables passed to' in str(w[-1].message)) - - self.assertEqual(res, 34) - self.assertEqual(TestCallbacks.called, 1) - self.assertEqual(sys.getrefcount(callback), callback_refcount + 1) - - # thaw will call the callback again, - # refcount will not go down without user_data parameter - self.assertEqual(Everything.test_callback_thaw_notifications(), 34) - self.assertEqual(TestCallbacks.called, 2) - self.assertEqual(sys.getrefcount(callback), callback_refcount + 1) + TestCallbacks.called = False + self.assertEqual(Everything.test_callback_destroy_notify(callback, 42), 42) + self.assertTrue(TestCallbacks.called) + self.assertEqual(Everything.test_callback_thaw_notifications(), 42) def test_callback_in_methods(self): object_ = Everything.TestObj() @@ -954,17 +404,12 @@ class TestCallbacks(unittest.TestCase): self.assertTrue(TestCallbacks.called) def callbackWithUserData(user_data): - TestCallbacks.called += 1 + TestCallbacks.called = True return 42 - TestCallbacks.called = 0 + TestCallbacks.called = False Everything.TestObj.new_callback(callbackWithUserData, None) - self.assertEqual(TestCallbacks.called, 1) - # Note: using "new_callback" adds the notification to the same global - # list as Everything.test_callback_destroy_notify, so thaw the list - # so we don't get confusion between tests. - self.assertEqual(Everything.test_callback_thaw_notifications(), 42) - self.assertEqual(TestCallbacks.called, 2) + self.assertTrue(TestCallbacks.called) def test_callback_none(self): # make sure this doesn't assert or crash @@ -1015,16 +460,6 @@ class TestCallbacks(unittest.TestCase): class TestClosures(unittest.TestCase): - def test_no_arg(self): - def callback(): - self.called = True - return 42 - - self.called = False - result = Everything.test_closure(callback) - self.assertTrue(self.called) - self.assertEqual(result, 42) - def test_int_arg(self): def callback(num): self.called = True @@ -1035,12 +470,13 @@ class TestClosures(unittest.TestCase): self.assertTrue(self.called) self.assertEqual(result, 43) + # https://bugzilla.gnome.org/show_bug.cgi?id=656554 + + @unittest.expectedFailure def test_variant(self): def callback(variant): - self.called = True - if variant is None: - return None self.assertEqual(variant.get_type_string(), 'i') + self.called = True return GLib.Variant('i', variant.get_int32() + 1) self.called = False @@ -1049,32 +485,52 @@ class TestClosures(unittest.TestCase): self.assertEqual(result.get_type_string(), 'i') self.assertEqual(result.get_int32(), 43) - self.called = False - result = Everything.test_closure_variant(callback, None) - self.assertTrue(self.called) - self.assertEqual(result, None) - self.called = False - self.assertRaises(TypeError, Everything.test_closure_variant, callback, 'foo') - self.assertFalse(self.called) +class TestProperties(unittest.TestCase): - def test_variant_wrong_return_type(self): - def callback(variant): - return 'no_variant' + def test_basic(self): + object_ = Everything.TestObj() + + self.assertEqual(object_.props.int, 0) + object_.props.int = 42 + self.assertTrue(isinstance(object_.props.int, int)) + self.assertEqual(object_.props.int, 42) + + self.assertEqual(object_.props.float, 0.0) + object_.props.float = 42.42 + self.assertTrue(isinstance(object_.props.float, float)) + self.assertAlmostEquals(object_.props.float, 42.42, places=5) + + self.assertEqual(object_.props.double, 0.0) + object_.props.double = 42.42 + self.assertTrue(isinstance(object_.props.double, float)) + self.assertAlmostEquals(object_.props.double, 42.42, places=5) + + self.assertEqual(object_.props.string, None) + object_.props.string = 'mec' + self.assertTrue(isinstance(object_.props.string, str)) + self.assertEqual(object_.props.string, 'mec') + + self.assertEqual(object_.props.gtype, GObject.TYPE_INVALID) + object_.props.gtype = int + self.assertEqual(object_.props.gtype, GObject.TYPE_INT) - with capture_exceptions() as exc: - # this does not directly raise an exception (see - # https://bugzilla.gnome.org/show_bug.cgi?id=616279) - result = Everything.test_closure_variant(callback, GLib.Variant('i', 42)) - # ... but the result shouldn't be a string - self.assertEqual(result, None) - # and the error should be shown - self.assertEqual(len(exc), 1) - self.assertEqual(exc[0].type, TypeError) - self.assertTrue('return value' in str(exc[0].value), exc[0].value) + def test_hash_table(self): + object_ = Everything.TestObj() + self.assertEqual(object_.props.hash_table, None) + + object_.props.hash_table = {'mec': 56} + self.assertTrue(isinstance(object_.props.hash_table, dict)) + self.assertEqual(list(object_.props.hash_table.items())[0], ('mec', 56)) + + def test_list(self): + object_ = Everything.TestObj() + self.assertEqual(object_.props.list, []) + object_.props.list = ['1', '2', '3'] + self.assertTrue(isinstance(object_.props.list, list)) + self.assertEqual(object_.props.list, ['1', '2', '3']) -class TestBoxed(unittest.TestCase): def test_boxed(self): object_ = Everything.TestObj() self.assertEqual(object_.props.boxed, None) @@ -1086,42 +542,16 @@ class TestBoxed(unittest.TestCase): self.assertTrue(isinstance(object_.props.boxed, Everything.TestBoxed)) self.assertEqual(object_.props.boxed.some_int8, 42) - def test_boxed_alternative_constructor(self): - boxed = Everything.TestBoxed.new_alternative_constructor1(5) - self.assertEqual(boxed.some_int8, 5) - - boxed = Everything.TestBoxed.new_alternative_constructor2(5, 3) - self.assertEqual(boxed.some_int8, 8) - - boxed = Everything.TestBoxed.new_alternative_constructor3("-3") - self.assertEqual(boxed.some_int8, -3) - - def test_boxed_equality(self): - boxed42 = Everything.TestBoxed.new_alternative_constructor1(42) - boxed5 = Everything.TestBoxed.new_alternative_constructor1(5) - boxed42_2 = Everything.TestBoxed.new_alternative_constructor2(41, 1) - - self.assertFalse(boxed42.equals(boxed5)) - self.assertTrue(boxed42.equals(boxed42_2)) - self.assertTrue(boxed42_2.equals(boxed42)) - self.assertTrue(boxed42.equals(boxed42)) - - def test_boxed_b_constructor(self): - with warnings.catch_warnings(record=True) as warn: - warnings.simplefilter('always') - boxed = Everything.TestBoxedB(42, 47) - self.assertTrue(issubclass(warn[0].category, TypeError)) - - self.assertEqual(boxed.some_int8, 0) - self.assertEqual(boxed.some_long, 0) + def test_gtype(self): + object_ = Everything.TestObj() + self.assertEqual(object_.props.gtype, GObject.TYPE_INVALID) + object_.props.gtype = int + self.assertEqual(object_.props.gtype, GObject.TYPE_INT) - def test_boxed_c_equality(self): - boxed = Everything.TestBoxedC() - # TestBoxedC uses refcounting, so we know that - # the pointer is the same when copied - copy = boxed.copy() - self.assertEqual(boxed, copy) - self.assertNotEqual(id(boxed), id(copy)) + object_ = Everything.TestObj(gtype=int) + self.assertEqual(object_.props.gtype, GObject.TYPE_INT) + object_.props.gtype = str + self.assertEqual(object_.props.gtype, GObject.TYPE_STRING) class TestTortureProfile(unittest.TestCase): @@ -1171,7 +601,7 @@ class TestTortureProfile(unittest.TestCase): sys.stdout.write("\ttorture test 4 (10000 iterations): ") def callback(userdata): - return 0 + pass userdata = [1, 2, 3, 4] start_time = time.clock() @@ -1208,3 +638,15 @@ class TestAdvancedInterfaces(unittest.TestCase): ret = obj.skip_return_val_no_out(1) self.assertEqual(ret, None) + + +class TestSignals(unittest.TestCase): + def test_object_param_signal(self): + obj = Everything.TestObj() + + def callback(obj, obj_param): + self.assertEqual(obj_param.props.int, 3) + self.assertGreater(obj_param.__grefcount__, 1) + + obj.connect('sig-with-obj', callback) + obj.emit_sig_with_obj() diff --git a/tests/test_fields.py b/tests/test_fields.py deleted file mode 100644 index ac09949..0000000 --- a/tests/test_fields.py +++ /dev/null @@ -1,186 +0,0 @@ -# -*- Mode: Python; py-indent-offset: 4 -*- -# coding=utf-8 - -import math -import unittest - -from gi.repository import GLib -from gi.repository import Regress -from gi.repository import GIMarshallingTests - - -class Number(object): - - def __init__(self, value): - self.value = value - - def __int__(self): - return int(self.value) - - def __float__(self): - return float(self.value) - - -class TestFields(unittest.TestCase): - - def test_int8(self): - s = Regress.TestStructA() - s.some_int8 = 21 - self.assertEqual(s.some_int8, 21) - - s.some_int8 = b"\x42" - self.assertEqual(s.some_int8, 0x42) - - self.assertRaises(TypeError, setattr, s, "some_int8", b"ab") - self.assertRaises(TypeError, setattr, s, "some_int8", None) - self.assertRaises(OverflowError, setattr, s, "some_int8", 128) - self.assertRaises(OverflowError, setattr, s, "some_int8", -129) - - s.some_int8 = 3.6 - self.assertEqual(s.some_int8, 3) - - s.some_int8 = Number(55) - self.assertEqual(s.some_int8, 55) - - def test_int(self): - s = Regress.TestStructA() - s.some_int = GLib.MAXINT - self.assertEqual(s.some_int, GLib.MAXINT) - - self.assertRaises(TypeError, setattr, s, "some_int", b"a") - self.assertRaises(TypeError, setattr, s, "some_int", None) - self.assertRaises( - OverflowError, setattr, s, "some_int", GLib.MAXINT + 1) - self.assertRaises( - OverflowError, setattr, s, "some_int", GLib.MININT - 1) - - s.some_int = 3.6 - self.assertEqual(s.some_int, 3) - - s.some_int = Number(GLib.MININT) - self.assertEqual(s.some_int, GLib.MININT) - - def test_long(self): - s = GIMarshallingTests.SimpleStruct() - s.long_ = GLib.MAXLONG - self.assertEqual(s.long_, GLib.MAXLONG) - - self.assertRaises(TypeError, setattr, s, "long_", b"a") - self.assertRaises(TypeError, setattr, s, "long_", None) - self.assertRaises(OverflowError, setattr, s, "long_", GLib.MAXLONG + 1) - self.assertRaises(OverflowError, setattr, s, "long_", GLib.MINLONG - 1) - - s.long_ = 3.6 - self.assertEqual(s.long_, 3) - - s.long_ = Number(GLib.MINLONG) - self.assertEqual(s.long_, GLib.MINLONG) - - def test_double(self): - s = Regress.TestStructA() - s.some_double = GLib.MAXDOUBLE - self.assertEqual(s.some_double, GLib.MAXDOUBLE) - s.some_double = GLib.MINDOUBLE - self.assertEqual(s.some_double, GLib.MINDOUBLE) - - s.some_double = float("nan") - self.assertTrue(math.isnan(s.some_double)) - - self.assertRaises(TypeError, setattr, s, "some_double", b"a") - self.assertRaises(TypeError, setattr, s, "some_double", None) - - def test_gtype(self): - s = Regress.TestStructE() - - s.some_type = Regress.TestObj - self.assertEqual(s.some_type, Regress.TestObj.__gtype__) - - self.assertRaises(TypeError, setattr, s, "some_type", 42) - - def test_unichar(self): - # I can't find a unichar field.. - pass - - def test_utf8(self): - s = GIMarshallingTests.BoxedStruct() - s.string_ = "hello" - self.assertEqual(s.string_, "hello") - - s.string_ = u"hello" - self.assertEqual(s.string_, u"hello") - - s.string_ = None - self.assertEqual(s.string_, None) - - self.assertRaises(TypeError, setattr, s, "string_", 42) - - def test_array_of_structs(self): - s = Regress.TestStructD() - self.assertEqual(s.array1, []) - self.assertEqual(s.array2, []) - - def test_interface(self): - s = Regress.TestStructC() - - obj = Regress.TestObj() - s.obj = obj - self.assertTrue(s.obj is obj) - - s.obj = None - self.assertTrue(s.obj is None) - - self.assertRaises(TypeError, setattr, s, "obj", object()) - - def test_glist(self): - s = Regress.TestStructD() - self.assertEqual(s.list, []) - - self.assertRaises(TypeError, setattr, s, "list", [object()]) - - def test_gpointer(self): - glist = GLib.List() - - glist.data = 123 - self.assertEqual(glist.data, 123) - - glist.data = None - self.assertEqual(glist.data, 0) - - def test_gptrarray(self): - s = Regress.TestStructD() - self.assertEqual(s.garray, []) - - self.assertRaises(TypeError, setattr, s, "garray", [object()]) - - def test_enum(self): - s = Regress.TestStructA() - - s.some_enum = Regress.TestEnum.VALUE3 - self.assertEqual(s.some_enum, Regress.TestEnum.VALUE3) - - self.assertRaises(TypeError, setattr, s, "some_enum", object()) - - s.some_enum = 0 - self.assertEqual(s.some_enum, Regress.TestEnum.VALUE1) - - def test_union(self): - s = Regress.TestStructE() - self.assertEqual(s.some_union, [None, None]) - - def test_struct(self): - s = GIMarshallingTests.NestedStruct() - - # FIXME: segfaults - # https://bugzilla.gnome.org/show_bug.cgi?id=747002 - # s.simple_struct = None - - self.assertRaises(TypeError, setattr, s, "simple_struct", object()) - - sub = GIMarshallingTests.SimpleStruct() - sub.long_ = 42 - s.simple_struct = sub - self.assertEqual(s.simple_struct.long_, 42) - - def test_ghashtable(self): - obj = Regress.TestObj() - self.assertTrue(obj.hash_table is None) diff --git a/tests/test_gdbus.py b/tests/test_gdbus.py index 5fb4f5d..afd18c7 100644 --- a/tests/test_gdbus.py +++ b/tests/test_gdbus.py @@ -3,43 +3,35 @@ import unittest +import sys +sys.path.insert(0, "../") + +from gi.repository import GObject from gi.repository import GLib from gi.repository import Gio -try: - Gio.bus_get_sync(Gio.BusType.SESSION, None) -except GLib.Error: - has_dbus = False -else: - has_dbus = True - - -@unittest.skipUnless(has_dbus, "no dbus running") class TestGDBusClient(unittest.TestCase): def setUp(self): self.bus = Gio.bus_get_sync(Gio.BusType.SESSION, None) self.dbus_proxy = Gio.DBusProxy.new_sync(self.bus, - Gio.DBusProxyFlags.NONE, - None, - 'org.freedesktop.DBus', - '/org/freedesktop/DBus', - 'org.freedesktop.DBus', - None) + Gio.DBusProxyFlags.NONE, None, + 'org.freedesktop.DBus', + '/org/freedesktop/DBus', + 'org.freedesktop.DBus', None) def test_native_calls_sync(self): result = self.dbus_proxy.call_sync('ListNames', None, - Gio.DBusCallFlags.NO_AUTO_START, - 500, None) + Gio.DBusCallFlags.NO_AUTO_START, 500, None) self.assertTrue(isinstance(result, GLib.Variant)) result = result.unpack()[0] # result is always a tuple self.assertTrue(len(result) > 1) self.assertTrue('org.freedesktop.DBus' in result) result = self.dbus_proxy.call_sync('GetNameOwner', - GLib.Variant('(s)', ('org.freedesktop.DBus',)), - Gio.DBusCallFlags.NO_AUTO_START, 500, None) + GLib.Variant('(s)', ('org.freedesktop.DBus',)), + Gio.DBusCallFlags.NO_AUTO_START, 500, None) self.assertTrue(isinstance(result, GLib.Variant)) self.assertEqual(type(result.unpack()[0]), type('')) @@ -47,7 +39,7 @@ class TestGDBusClient(unittest.TestCase): # error case: invalid argument types try: self.dbus_proxy.call_sync('GetConnectionUnixProcessID', None, - Gio.DBusCallFlags.NO_AUTO_START, 500, None) + Gio.DBusCallFlags.NO_AUTO_START, 500, None) self.fail('call with invalid arguments should raise an exception') except Exception as e: self.assertTrue('InvalidArgs' in str(e)) @@ -55,8 +47,8 @@ class TestGDBusClient(unittest.TestCase): # error case: invalid argument try: self.dbus_proxy.call_sync('GetConnectionUnixProcessID', - GLib.Variant('(s)', (' unknown',)), - Gio.DBusCallFlags.NO_AUTO_START, 500, None) + GLib.Variant('(s)', (' unknown',)), + Gio.DBusCallFlags.NO_AUTO_START, 500, None) self.fail('call with invalid arguments should raise an exception') except Exception as e: self.assertTrue('NameHasNoOwner' in str(e)) @@ -64,7 +56,7 @@ class TestGDBusClient(unittest.TestCase): # error case: unknown method try: self.dbus_proxy.call_sync('UnknownMethod', None, - Gio.DBusCallFlags.NO_AUTO_START, 500, None) + Gio.DBusCallFlags.NO_AUTO_START, 500, None) self.fail('call for unknown method should raise an exception') except Exception as e: self.assertTrue('UnknownMethod' in str(e)) @@ -76,11 +68,11 @@ class TestGDBusClient(unittest.TestCase): finally: user_data['main_loop'].quit() - main_loop = GLib.MainLoop() + main_loop = GObject.MainLoop() data = {'main_loop': main_loop} self.dbus_proxy.call('ListNames', None, - Gio.DBusCallFlags.NO_AUTO_START, 500, None, - call_done, data) + Gio.DBusCallFlags.NO_AUTO_START, 500, None, + call_done, data) main_loop.run() self.assertTrue(isinstance(data['result'], GLib.Variant)) @@ -98,11 +90,10 @@ class TestGDBusClient(unittest.TestCase): finally: user_data['main_loop'].quit() - main_loop = GLib.MainLoop() + main_loop = GObject.MainLoop() data = {'main_loop': main_loop} self.dbus_proxy.call('UnknownMethod', None, - Gio.DBusCallFlags.NO_AUTO_START, 500, None, - call_done, data) + Gio.DBusCallFlags.NO_AUTO_START, 500, None, call_done, data) main_loop.run() def test_python_calls_sync(self): @@ -122,13 +113,12 @@ class TestGDBusClient(unittest.TestCase): # does not have any method returning multiple results, so try talking # to notification-daemon (and don't fail the test if it does not exist) try: - nd = Gio.DBusProxy.new_sync(self.bus, - Gio.DBusProxyFlags.NONE, None, - 'org.freedesktop.Notifications', - '/org/freedesktop/Notifications', - 'org.freedesktop.Notifications', - None) - result = nd.GetServerInformation('()') + notification_daemon = Gio.DBusProxy.new_sync(self.bus, + Gio.DBusProxyFlags.NONE, None, + 'org.freedesktop.Notifications', + '/org/freedesktop/Notifications', + 'org.freedesktop.Notifications', None) + result = notification_daemon.GetServerInformation('()') self.assertTrue(isinstance(result, tuple)) self.assertEqual(len(result), 4) for i in result: @@ -142,9 +132,7 @@ class TestGDBusClient(unittest.TestCase): self.dbus_proxy.GetConnectionUnixProcessID('(s)', '1', timeout=0) self.fail('call with timeout=0 should raise an exception') except Exception as e: - # FIXME: this is not very precise, but in some environments we - # do not always get an actual timeout - self.assertTrue(isinstance(e, GLib.GError), str(e)) + self.assertTrue('Timeout' in str(e), str(e)) def test_python_calls_sync_noargs(self): # methods without arguments don't need an explicit signature @@ -172,9 +160,10 @@ class TestGDBusClient(unittest.TestCase): user_data['result'] = result user_data['main_loop'].quit() - main_loop = GLib.MainLoop() + main_loop = GObject.MainLoop() data = {'main_loop': main_loop} - self.dbus_proxy.ListNames('()', result_handler=call_done, user_data=data) + self.dbus_proxy.ListNames('()', result_handler=call_done, + user_data=data) main_loop.run() result = data['result'] @@ -188,10 +177,10 @@ class TestGDBusClient(unittest.TestCase): user_data['result'] = result user_data['main_loop'].quit() - main_loop = GLib.MainLoop() + main_loop = GObject.MainLoop() data = {'main_loop': main_loop} self.dbus_proxy.ListNames('(s)', 'invalid_argument', - result_handler=call_done, user_data=data) + result_handler=call_done, user_data=data) main_loop.run() self.assertTrue(isinstance(data['result'], Exception)) @@ -207,12 +196,11 @@ class TestGDBusClient(unittest.TestCase): user_data['error'] = error user_data['main_loop'].quit() - main_loop = GLib.MainLoop() + main_loop = GObject.MainLoop() data = {'main_loop': main_loop} self.dbus_proxy.ListNames('(s)', 'invalid_argument', - result_handler=call_done, - error_handler=call_error, - user_data=data) + result_handler=call_done, error_handler=call_error, + user_data=data) main_loop.run() self.assertTrue(isinstance(data['error'], Exception)) diff --git a/tests/test_generictreemodel.py b/tests/test_generictreemodel.py deleted file mode 100644 index 30ae125..0000000 --- a/tests/test_generictreemodel.py +++ /dev/null @@ -1,420 +0,0 @@ -# -*- Mode: Python; py-indent-offset: 4 -*- -# test_generictreemodel - Tests for GenericTreeModel -# Copyright (C) 2013 Simon Feltman -# -# test_generictreemodel.py: Tests for GenericTreeModel -# -# This library is free software; you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public -# License as published by the Free Software Foundation; either -# version 2.1 of the License, or (at your option) any later version. -# -# This library is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, see <http://www.gnu.org/licenses/>. - - -# system -import gc -import sys -import weakref -import unittest - -# pygobject -from gi.repository import GObject - -try: - from gi.repository import Gtk - from pygtkcompat.generictreemodel import GenericTreeModel - from pygtkcompat.generictreemodel import _get_user_data_as_pyobject - has_gtk = True -except ImportError: - GenericTreeModel = object - has_gtk = False - - -class Node(object): - """Represents a generic node with name, value, and children.""" - def __init__(self, name, value, *children): - self.name = name - self.value = value - self.children = list(children) - self.parent = None - self.next = None - - for i, child in enumerate(children): - child.parent = weakref.ref(self) - if i < len(children) - 1: - child.next = weakref.ref(children[i + 1]) - - def __repr__(self): - return 'Node("%s", %s)' % (self.name, self.value) - - -class TesterModel(GenericTreeModel): - def __init__(self): - super(TesterModel, self).__init__() - self.root = Node('root', 0, - Node('spam', 1, - Node('sushi', 2), - Node('bread', 3) - ), - Node('eggs', 4) - ) - - def on_get_flags(self): - return 0 - - def on_get_n_columns(self): - return 2 - - def on_get_column_type(self, n): - return (str, int)[n] - - def on_get_iter(self, path): - node = self.root - path = list(path) - idx = path.pop(0) - while path: - idx = path.pop(0) - node = node.children[idx] - return node - - def on_get_path(self, node): - def rec_get_path(n): - for i, child in enumerate(n.children): - if child == node: - return [i] - else: - res = rec_get_path(child) - if res: - res.insert(0, i) - - return rec_get_path(self.root) - - def on_get_value(self, node, column): - if column == 0: - return node.name - elif column == 1: - return node.value - - def on_iter_has_child(self, node): - return bool(node.children) - - def on_iter_next(self, node): - if node.next: - return node.next() - - def on_iter_children(self, node): - if node: - return node.children[0] - else: - return self.root - - def on_iter_n_children(self, node): - if node is None: - return 1 - return len(node.children) - - def on_iter_nth_child(self, node, n): - if node is None: - assert n == 0 - return self.root - return node.children[n] - - def on_iter_parent(self, child): - if child.parent: - return child.parent() - - -@unittest.skipUnless(has_gtk, 'Gtk not available') -class TestReferences(unittest.TestCase): - def setUp(self): - pass - - def test_c_tree_iter_user_data_as_pyobject(self): - obj = object() - obj_id = id(obj) - ref_count = sys.getrefcount(obj) - - # This is essentially a stolen ref in the context of _CTreeIter.get_user_data_as_pyobject - it = Gtk.TreeIter() - it.user_data = obj_id - - obj2 = _get_user_data_as_pyobject(it) - self.assertEqual(obj, obj2) - self.assertEqual(sys.getrefcount(obj), ref_count + 1) - - def test_leak_references_on(self): - model = TesterModel() - obj_ref = weakref.ref(model.root) - # Initial refcount is 1 for model.root + the temporary - self.assertEqual(sys.getrefcount(model.root), 2) - - # Iter increases by 1 do to assignment to iter.user_data - res, it = model.do_get_iter([0]) - self.assertEqual(id(model.root), it.user_data) - self.assertEqual(sys.getrefcount(model.root), 3) - - # Verify getting a TreeIter more then once does not further increase - # the ref count. - res2, it2 = model.do_get_iter([0]) - self.assertEqual(id(model.root), it2.user_data) - self.assertEqual(sys.getrefcount(model.root), 3) - - # Deleting the iter does not decrease refcount because references - # leak by default (they are stored in the held_refs pool) - del it - gc.collect() - self.assertEqual(sys.getrefcount(model.root), 3) - - # Deleting a model should free all held references to user data - # stored by TreeIters - del model - gc.collect() - self.assertEqual(obj_ref(), None) - - def test_row_deleted_frees_refs(self): - model = TesterModel() - obj_ref = weakref.ref(model.root) - # Initial refcount is 1 for model.root + the temporary - self.assertEqual(sys.getrefcount(model.root), 2) - - # Iter increases by 1 do to assignment to iter.user_data - res, it = model.do_get_iter([0]) - self.assertEqual(id(model.root), it.user_data) - self.assertEqual(sys.getrefcount(model.root), 3) - - # Notifying the underlying model of a row_deleted should decrease the - # ref count. - model.row_deleted(Gtk.TreePath('0'), model.root) - self.assertEqual(sys.getrefcount(model.root), 2) - - # Finally deleting the actual object should collect it completely - del model.root - gc.collect() - self.assertEqual(obj_ref(), None) - - def test_leak_references_off(self): - model = TesterModel() - model.leak_references = False - - obj_ref = weakref.ref(model.root) - # Initial refcount is 1 for model.root + the temporary - self.assertEqual(sys.getrefcount(model.root), 2) - - # Iter does not increas count by 1 when leak_references is false - res, it = model.do_get_iter([0]) - self.assertEqual(id(model.root), it.user_data) - self.assertEqual(sys.getrefcount(model.root), 2) - - # Deleting the iter does not decrease refcount because assigning user_data - # eats references and does not release them. - del it - gc.collect() - self.assertEqual(sys.getrefcount(model.root), 2) - - # Deleting the model decreases the final ref, and the object is collected - del model - gc.collect() - self.assertEqual(obj_ref(), None) - - def test_iteration_refs(self): - # Pull iterators off the model using the wrapped C API which will - # then call back into the python overrides. - model = TesterModel() - nodes = [node for node in model.iter_depth_first()] - values = [node.value for node in nodes] - - # Verify depth first ordering - self.assertEqual(values, [0, 1, 2, 3, 4]) - - # Verify ref counts for each of the nodes. - # 5 refs for each node at this point: - # 1 - ref held in getrefcount function - # 2 - ref held by "node" var during iteration - # 3 - ref held by local "nodes" var - # 4 - ref held by the root/children graph itself - # 5 - ref held by the model "held_refs" instance var - for node in nodes: - self.assertEqual(sys.getrefcount(node), 5) - - # A second iteration and storage of the nodes in a new list - # should only increase refcounts by 1 even though new - # iterators are created and assigned. - nodes2 = [node for node in model.iter_depth_first()] - for node in nodes2: - self.assertEqual(sys.getrefcount(node), 6) - - # Hold weak refs and start verifying ref collection. - node_refs = [weakref.ref(node) for node in nodes] - - # First round of collection - del nodes2 - gc.collect() - for node in nodes: - self.assertEqual(sys.getrefcount(node), 5) - - # Second round of collection, no more local lists of nodes. - del nodes - gc.collect() - for ref in node_refs: - node = ref() - self.assertEqual(sys.getrefcount(node), 4) - - # Using invalidate_iters or row_deleted(path, node) will clear out - # the pooled refs held internal to the GenericTreeModel implementation. - model.invalidate_iters() - self.assertEqual(len(model._held_refs), 0) - gc.collect() - for ref in node_refs: - node = ref() - self.assertEqual(sys.getrefcount(node), 3) - - # Deleting the root node at this point should allow all nodes to be collected - # as there is no longer a way to reach the children - del node # node still in locals() from last iteration - del model.root - gc.collect() - for ref in node_refs: - self.assertEqual(ref(), None) - - -@unittest.skipUnless(has_gtk, 'Gtk not available') -class TestIteration(unittest.TestCase): - def test_iter_next_root(self): - model = TesterModel() - it = model.get_iter([0]) - self.assertEqual(it.user_data, id(model.root)) - self.assertEqual(model.root.next, None) - - it = model.iter_next(it) - self.assertEqual(it, None) - - def test_iter_next_multiple(self): - model = TesterModel() - it = model.get_iter([0, 0]) - self.assertEqual(it.user_data, id(model.root.children[0])) - - it = model.iter_next(it) - self.assertEqual(it.user_data, id(model.root.children[1])) - - it = model.iter_next(it) - self.assertEqual(it, None) - - -class ErrorModel(GenericTreeModel): - # All on_* methods will raise a NotImplementedError by default - pass - - -@unittest.skipUnless(has_gtk, 'Gtk not available') -class ExceptHook(object): - """ - Temporarily installs an exception hook in a context which - expects the given exc_type to be raised. This allows verification - of exceptions that occur within python gi callbacks but - are never bubbled through from python to C back to python. - This works because exception hooks are called in PyErr_Print. - """ - def __init__(self, *expected_exc_types): - self._expected_exc_types = expected_exc_types - self._exceptions = [] - - def _excepthook(self, exc_type, value, traceback): - self._exceptions.append((exc_type, value)) - - def __enter__(self): - self._oldhook = sys.excepthook - sys.excepthook = self._excepthook - return self - - def __exit__(self, exc_type, exc_val, exc_tb): - sys.excepthook = self._oldhook - error_message = 'Expecting the following exceptions: %s, got: %s' % \ - (str(self._expected_exc_types), '\n'.join([str(item) for item in self._exceptions])) - - assert len(self._expected_exc_types) == len(self._exceptions), error_message - - for expected, got in zip(self._expected_exc_types, [exc[0] for exc in self._exceptions]): - assert issubclass(got, expected), error_message - - -@unittest.skipUnless(has_gtk, 'Gtk not available') -class TestReturnsAfterError(unittest.TestCase): - def setUp(self): - self.model = ErrorModel() - - def test_get_flags(self): - with ExceptHook(NotImplementedError): - flags = self.model.get_flags() - self.assertEqual(flags, 0) - - def test_get_n_columns(self): - with ExceptHook(NotImplementedError): - count = self.model.get_n_columns() - self.assertEqual(count, 0) - - def test_get_column_type(self): - with ExceptHook(NotImplementedError, TypeError): - col_type = self.model.get_column_type(0) - self.assertEqual(col_type, GObject.TYPE_INVALID) - - def test_get_iter(self): - with ExceptHook(NotImplementedError): - self.assertRaises(ValueError, self.model.get_iter, Gtk.TreePath(0)) - - def test_get_path(self): - it = self.model.create_tree_iter('foo') - with ExceptHook(NotImplementedError): - path = self.model.get_path(it) - self.assertEqual(path, None) - - def test_get_value(self): - it = self.model.create_tree_iter('foo') - with ExceptHook(NotImplementedError): - try: - self.model.get_value(it, 0) - except TypeError: - pass # silence TypeError converting None to GValue - - def test_iter_has_child(self): - it = self.model.create_tree_iter('foo') - with ExceptHook(NotImplementedError): - res = self.model.iter_has_child(it) - self.assertEqual(res, False) - - def test_iter_next(self): - it = self.model.create_tree_iter('foo') - with ExceptHook(NotImplementedError): - res = self.model.iter_next(it) - self.assertEqual(res, None) - - def test_iter_children(self): - with ExceptHook(NotImplementedError): - res = self.model.iter_children(None) - self.assertEqual(res, None) - - def test_iter_n_children(self): - with ExceptHook(NotImplementedError): - res = self.model.iter_n_children(None) - self.assertEqual(res, 0) - - def test_iter_nth_child(self): - with ExceptHook(NotImplementedError): - res = self.model.iter_nth_child(None, 0) - self.assertEqual(res, None) - - def test_iter_parent(self): - child = self.model.create_tree_iter('foo') - with ExceptHook(NotImplementedError): - res = self.model.iter_parent(child) - self.assertEqual(res, None) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/test_gi.py b/tests/test_gi.py index 173744a..2b5b5a1 100644 --- a/tests/test_gi.py +++ b/tests/test_gi.py @@ -10,24 +10,21 @@ import shutil import os import locale import subprocess -import gc -import weakref -import warnings -from io import StringIO, BytesIO - -import gi -import gi.overrides -from gi import PyGIWarning -from gi import PyGIDeprecationWarning -from gi.repository import GObject, GLib, Gio +from gi.repository import GObject, GLib from gi.repository import GIMarshallingTests -from compathelper import PY2, PY3 -from helper import capture_exceptions +from compathelper import _bytes +if sys.version_info < (3, 0): + CONSTANT_UTF8 = "const \xe2\x99\xa5 utf8" + PY2_UNICODE_UTF8 = unicode(CONSTANT_UTF8, 'UTF-8') + CHAR_255 = '\xff' +else: + CONSTANT_UTF8 = "const ♥ utf8" + CHAR_255 = bytes([255]) -CONSTANT_UTF8 = "const ♥ utf8" +CONSTANT_NUMBER = 42 class Number(object): @@ -56,20 +53,12 @@ class Sequence(object): class TestConstant(unittest.TestCase): - def test_constant_utf8(self): - self.assertEqual(CONSTANT_UTF8, GIMarshallingTests.CONSTANT_UTF8) +# Blocked by https://bugzilla.gnome.org/show_bug.cgi?id=595773 +# def test_constant_utf8(self): +# self.assertEqual(CONSTANT_UTF8, GIMarshallingTests.CONSTANT_UTF8) def test_constant_number(self): - self.assertEqual(42, GIMarshallingTests.CONSTANT_NUMBER) - - def test_min_max_int(self): - self.assertEqual(GLib.MAXINT32, 2 ** 31 - 1) - self.assertEqual(GLib.MININT32, -2 ** 31) - self.assertEqual(GLib.MAXUINT32, 2 ** 32 - 1) - - self.assertEqual(GLib.MAXINT64, 2 ** 63 - 1) - self.assertEqual(GLib.MININT64, -2 ** 63) - self.assertEqual(GLib.MAXUINT64, 2 ** 64 - 1) + self.assertEqual(CONSTANT_NUMBER, GIMarshallingTests.CONSTANT_NUMBER) class TestBoolean(unittest.TestCase): @@ -96,8 +85,8 @@ class TestBoolean(unittest.TestCase): class TestInt8(unittest.TestCase): - MAX = GLib.MAXINT8 - MIN = GLib.MININT8 + MAX = GObject.G_MAXINT8 + MIN = GObject.G_MININT8 def test_int8_return(self): self.assertEqual(self.MAX, GIMarshallingTests.int8_return_max()) @@ -113,8 +102,8 @@ class TestInt8(unittest.TestCase): max.value += 1 min.value -= 1 - self.assertRaises(OverflowError, GIMarshallingTests.int8_in_max, max) - self.assertRaises(OverflowError, GIMarshallingTests.int8_in_min, min) + self.assertRaises(ValueError, GIMarshallingTests.int8_in_max, max) + self.assertRaises(ValueError, GIMarshallingTests.int8_in_min, min) self.assertRaises(TypeError, GIMarshallingTests.int8_in_max, "self.MAX") @@ -129,7 +118,7 @@ class TestInt8(unittest.TestCase): class TestUInt8(unittest.TestCase): - MAX = GLib.MAXUINT8 + MAX = GObject.G_MAXUINT8 def test_uint8_return(self): self.assertEqual(self.MAX, GIMarshallingTests.uint8_return()) @@ -138,11 +127,11 @@ class TestUInt8(unittest.TestCase): number = Number(self.MAX) GIMarshallingTests.uint8_in(number) - GIMarshallingTests.uint8_in(b'\xff') + GIMarshallingTests.uint8_in(CHAR_255) number.value += 1 - self.assertRaises(OverflowError, GIMarshallingTests.uint8_in, number) - self.assertRaises(OverflowError, GIMarshallingTests.uint8_in, Number(-1)) + self.assertRaises(ValueError, GIMarshallingTests.uint8_in, number) + self.assertRaises(ValueError, GIMarshallingTests.uint8_in, Number(-1)) self.assertRaises(TypeError, GIMarshallingTests.uint8_in, "self.MAX") @@ -155,8 +144,8 @@ class TestUInt8(unittest.TestCase): class TestInt16(unittest.TestCase): - MAX = GLib.MAXINT16 - MIN = GLib.MININT16 + MAX = GObject.G_MAXINT16 + MIN = GObject.G_MININT16 def test_int16_return(self): self.assertEqual(self.MAX, GIMarshallingTests.int16_return_max()) @@ -172,8 +161,8 @@ class TestInt16(unittest.TestCase): max.value += 1 min.value -= 1 - self.assertRaises(OverflowError, GIMarshallingTests.int16_in_max, max) - self.assertRaises(OverflowError, GIMarshallingTests.int16_in_min, min) + self.assertRaises(ValueError, GIMarshallingTests.int16_in_max, max) + self.assertRaises(ValueError, GIMarshallingTests.int16_in_min, min) self.assertRaises(TypeError, GIMarshallingTests.int16_in_max, "self.MAX") @@ -188,7 +177,7 @@ class TestInt16(unittest.TestCase): class TestUInt16(unittest.TestCase): - MAX = GLib.MAXUINT16 + MAX = GObject.G_MAXUINT16 def test_uint16_return(self): self.assertEqual(self.MAX, GIMarshallingTests.uint16_return()) @@ -200,8 +189,8 @@ class TestUInt16(unittest.TestCase): number.value += 1 - self.assertRaises(OverflowError, GIMarshallingTests.uint16_in, number) - self.assertRaises(OverflowError, GIMarshallingTests.uint16_in, Number(-1)) + self.assertRaises(ValueError, GIMarshallingTests.uint16_in, number) + self.assertRaises(ValueError, GIMarshallingTests.uint16_in, Number(-1)) self.assertRaises(TypeError, GIMarshallingTests.uint16_in, "self.MAX") @@ -214,8 +203,8 @@ class TestUInt16(unittest.TestCase): class TestInt32(unittest.TestCase): - MAX = GLib.MAXINT32 - MIN = GLib.MININT32 + MAX = GObject.G_MAXINT32 + MIN = GObject.G_MININT32 def test_int32_return(self): self.assertEqual(self.MAX, GIMarshallingTests.int32_return_max()) @@ -231,8 +220,8 @@ class TestInt32(unittest.TestCase): max.value += 1 min.value -= 1 - self.assertRaises(OverflowError, GIMarshallingTests.int32_in_max, max) - self.assertRaises(OverflowError, GIMarshallingTests.int32_in_min, min) + self.assertRaises(ValueError, GIMarshallingTests.int32_in_max, max) + self.assertRaises(ValueError, GIMarshallingTests.int32_in_min, min) self.assertRaises(TypeError, GIMarshallingTests.int32_in_max, "self.MAX") @@ -247,7 +236,7 @@ class TestInt32(unittest.TestCase): class TestUInt32(unittest.TestCase): - MAX = GLib.MAXUINT32 + MAX = GObject.G_MAXUINT32 def test_uint32_return(self): self.assertEqual(self.MAX, GIMarshallingTests.uint32_return()) @@ -259,8 +248,8 @@ class TestUInt32(unittest.TestCase): number.value += 1 - self.assertRaises(OverflowError, GIMarshallingTests.uint32_in, number) - self.assertRaises(OverflowError, GIMarshallingTests.uint32_in, Number(-1)) + self.assertRaises(ValueError, GIMarshallingTests.uint32_in, number) + self.assertRaises(ValueError, GIMarshallingTests.uint32_in, Number(-1)) self.assertRaises(TypeError, GIMarshallingTests.uint32_in, "self.MAX") @@ -290,8 +279,8 @@ class TestInt64(unittest.TestCase): max.value += 1 min.value -= 1 - self.assertRaises(OverflowError, GIMarshallingTests.int64_in_max, max) - self.assertRaises(OverflowError, GIMarshallingTests.int64_in_min, min) + self.assertRaises(ValueError, GIMarshallingTests.int64_in_max, max) + self.assertRaises(ValueError, GIMarshallingTests.int64_in_min, min) self.assertRaises(TypeError, GIMarshallingTests.int64_in_max, "self.MAX") @@ -318,8 +307,8 @@ class TestUInt64(unittest.TestCase): number.value += 1 - self.assertRaises(OverflowError, GIMarshallingTests.uint64_in, number) - self.assertRaises(OverflowError, GIMarshallingTests.uint64_in, Number(-1)) + self.assertRaises(ValueError, GIMarshallingTests.uint64_in, number) + self.assertRaises(ValueError, GIMarshallingTests.uint64_in, Number(-1)) self.assertRaises(TypeError, GIMarshallingTests.uint64_in, "self.MAX") @@ -332,8 +321,8 @@ class TestUInt64(unittest.TestCase): class TestShort(unittest.TestCase): - MAX = GLib.MAXSHORT - MIN = GLib.MINSHORT + MAX = GObject.constants.G_MAXSHORT + MIN = GObject.constants.G_MINSHORT def test_short_return(self): self.assertEqual(self.MAX, GIMarshallingTests.short_return_max()) @@ -349,8 +338,8 @@ class TestShort(unittest.TestCase): max.value += 1 min.value -= 1 - self.assertRaises(OverflowError, GIMarshallingTests.short_in_max, max) - self.assertRaises(OverflowError, GIMarshallingTests.short_in_min, min) + self.assertRaises(ValueError, GIMarshallingTests.short_in_max, max) + self.assertRaises(ValueError, GIMarshallingTests.short_in_min, min) self.assertRaises(TypeError, GIMarshallingTests.short_in_max, "self.MAX") @@ -365,7 +354,7 @@ class TestShort(unittest.TestCase): class TestUShort(unittest.TestCase): - MAX = GLib.MAXUSHORT + MAX = GObject.constants.G_MAXUSHORT def test_ushort_return(self): self.assertEqual(self.MAX, GIMarshallingTests.ushort_return()) @@ -377,8 +366,8 @@ class TestUShort(unittest.TestCase): number.value += 1 - self.assertRaises(OverflowError, GIMarshallingTests.ushort_in, number) - self.assertRaises(OverflowError, GIMarshallingTests.ushort_in, Number(-1)) + self.assertRaises(ValueError, GIMarshallingTests.ushort_in, number) + self.assertRaises(ValueError, GIMarshallingTests.ushort_in, Number(-1)) self.assertRaises(TypeError, GIMarshallingTests.ushort_in, "self.MAX") @@ -391,8 +380,8 @@ class TestUShort(unittest.TestCase): class TestInt(unittest.TestCase): - MAX = GLib.MAXINT - MIN = GLib.MININT + MAX = GObject.constants.G_MAXINT + MIN = GObject.constants.G_MININT def test_int_return(self): self.assertEqual(self.MAX, GIMarshallingTests.int_return_max()) @@ -408,8 +397,8 @@ class TestInt(unittest.TestCase): max.value += 1 min.value -= 1 - self.assertRaises(OverflowError, GIMarshallingTests.int_in_max, max) - self.assertRaises(OverflowError, GIMarshallingTests.int_in_min, min) + self.assertRaises(ValueError, GIMarshallingTests.int_in_max, max) + self.assertRaises(ValueError, GIMarshallingTests.int_in_min, min) self.assertRaises(TypeError, GIMarshallingTests.int_in_max, "self.MAX") @@ -420,12 +409,12 @@ class TestInt(unittest.TestCase): def test_int_inout(self): self.assertEqual(self.MIN, GIMarshallingTests.int_inout_max_min(Number(self.MAX))) self.assertEqual(self.MAX, GIMarshallingTests.int_inout_min_max(Number(self.MIN))) - self.assertRaises(TypeError, GIMarshallingTests.int_inout_min_max, Number(self.MIN), 42) + self.assertRaises(TypeError, GIMarshallingTests.int_inout_min_max, Number(self.MIN), CONSTANT_NUMBER) class TestUInt(unittest.TestCase): - MAX = GLib.MAXUINT + MAX = GObject.constants.G_MAXUINT def test_uint_return(self): self.assertEqual(self.MAX, GIMarshallingTests.uint_return()) @@ -437,8 +426,8 @@ class TestUInt(unittest.TestCase): number.value += 1 - self.assertRaises(OverflowError, GIMarshallingTests.uint_in, number) - self.assertRaises(OverflowError, GIMarshallingTests.uint_in, Number(-1)) + self.assertRaises(ValueError, GIMarshallingTests.uint_in, number) + self.assertRaises(ValueError, GIMarshallingTests.uint_in, Number(-1)) self.assertRaises(TypeError, GIMarshallingTests.uint_in, "self.MAX") @@ -451,8 +440,8 @@ class TestUInt(unittest.TestCase): class TestLong(unittest.TestCase): - MAX = GLib.MAXLONG - MIN = GLib.MINLONG + MAX = GObject.constants.G_MAXLONG + MIN = GObject.constants.G_MINLONG def test_long_return(self): self.assertEqual(self.MAX, GIMarshallingTests.long_return_max()) @@ -468,8 +457,8 @@ class TestLong(unittest.TestCase): max.value += 1 min.value -= 1 - self.assertRaises(OverflowError, GIMarshallingTests.long_in_max, max) - self.assertRaises(OverflowError, GIMarshallingTests.long_in_min, min) + self.assertRaises(ValueError, GIMarshallingTests.long_in_max, max) + self.assertRaises(ValueError, GIMarshallingTests.long_in_min, min) self.assertRaises(TypeError, GIMarshallingTests.long_in_max, "self.MAX") @@ -484,7 +473,7 @@ class TestLong(unittest.TestCase): class TestULong(unittest.TestCase): - MAX = GLib.MAXULONG + MAX = GObject.constants.G_MAXULONG def test_ulong_return(self): self.assertEqual(self.MAX, GIMarshallingTests.ulong_return()) @@ -496,8 +485,8 @@ class TestULong(unittest.TestCase): number.value += 1 - self.assertRaises(OverflowError, GIMarshallingTests.ulong_in, number) - self.assertRaises(OverflowError, GIMarshallingTests.ulong_in, Number(-1)) + self.assertRaises(ValueError, GIMarshallingTests.ulong_in, number) + self.assertRaises(ValueError, GIMarshallingTests.ulong_in, Number(-1)) self.assertRaises(TypeError, GIMarshallingTests.ulong_in, "self.MAX") @@ -510,8 +499,8 @@ class TestULong(unittest.TestCase): class TestSSize(unittest.TestCase): - MAX = GLib.MAXSSIZE - MIN = GLib.MINSSIZE + MAX = GObject.constants.G_MAXLONG + MIN = GObject.constants.G_MINLONG def test_ssize_return(self): self.assertEqual(self.MAX, GIMarshallingTests.ssize_return_max()) @@ -527,8 +516,8 @@ class TestSSize(unittest.TestCase): max.value += 1 min.value -= 1 - self.assertRaises(OverflowError, GIMarshallingTests.ssize_in_max, max) - self.assertRaises(OverflowError, GIMarshallingTests.ssize_in_min, min) + self.assertRaises(ValueError, GIMarshallingTests.ssize_in_max, max) + self.assertRaises(ValueError, GIMarshallingTests.ssize_in_min, min) self.assertRaises(TypeError, GIMarshallingTests.ssize_in_max, "self.MAX") @@ -543,7 +532,7 @@ class TestSSize(unittest.TestCase): class TestSize(unittest.TestCase): - MAX = GLib.MAXSIZE + MAX = GObject.constants.G_MAXULONG def test_size_return(self): self.assertEqual(self.MAX, GIMarshallingTests.size_return()) @@ -555,8 +544,8 @@ class TestSize(unittest.TestCase): number.value += 1 - self.assertRaises(OverflowError, GIMarshallingTests.size_in, number) - self.assertRaises(OverflowError, GIMarshallingTests.size_in, Number(-1)) + self.assertRaises(ValueError, GIMarshallingTests.size_in, number) + self.assertRaises(ValueError, GIMarshallingTests.size_in, Number(-1)) self.assertRaises(TypeError, GIMarshallingTests.size_in, "self.MAX") @@ -567,29 +556,13 @@ class TestSize(unittest.TestCase): self.assertEqual(0, GIMarshallingTests.size_inout(Number(self.MAX))) -class TestTimet(unittest.TestCase): - - def test_time_t_return(self): - self.assertEqual(1234567890, GIMarshallingTests.time_t_return()) - - def test_time_t_in(self): - GIMarshallingTests.time_t_in(1234567890) - self.assertRaises(TypeError, GIMarshallingTests.time_t_in, "hello") - - def test_time_t_out(self): - self.assertEqual(1234567890, GIMarshallingTests.time_t_out()) - - def test_time_t_inout(self): - self.assertEqual(0, GIMarshallingTests.time_t_inout(1234567890)) - - class TestFloat(unittest.TestCase): - MAX = GLib.MAXFLOAT - MIN = GLib.MINFLOAT + MAX = GObject.constants.G_MAXFLOAT + MIN = GObject.constants.G_MINFLOAT def test_float_return(self): - self.assertAlmostEqual(self.MAX, GIMarshallingTests.float_return()) + self.assertAlmostEquals(self.MAX, GIMarshallingTests.float_return()) def test_float_in(self): GIMarshallingTests.float_in(Number(self.MAX)) @@ -597,19 +570,19 @@ class TestFloat(unittest.TestCase): self.assertRaises(TypeError, GIMarshallingTests.float_in, "self.MAX") def test_float_out(self): - self.assertAlmostEqual(self.MAX, GIMarshallingTests.float_out()) + self.assertAlmostEquals(self.MAX, GIMarshallingTests.float_out()) def test_float_inout(self): - self.assertAlmostEqual(self.MIN, GIMarshallingTests.float_inout(Number(self.MAX))) + self.assertAlmostEquals(self.MIN, GIMarshallingTests.float_inout(Number(self.MAX))) class TestDouble(unittest.TestCase): - MAX = GLib.MAXDOUBLE - MIN = GLib.MINDOUBLE + MAX = GObject.constants.G_MAXDOUBLE + MIN = GObject.constants.G_MINDOUBLE def test_double_return(self): - self.assertAlmostEqual(self.MAX, GIMarshallingTests.double_return()) + self.assertAlmostEquals(self.MAX, GIMarshallingTests.double_return()) def test_double_in(self): GIMarshallingTests.double_in(Number(self.MAX)) @@ -617,10 +590,10 @@ class TestDouble(unittest.TestCase): self.assertRaises(TypeError, GIMarshallingTests.double_in, "self.MAX") def test_double_out(self): - self.assertAlmostEqual(self.MAX, GIMarshallingTests.double_out()) + self.assertAlmostEquals(self.MAX, GIMarshallingTests.double_out()) def test_double_inout(self): - self.assertAlmostEqual(self.MIN, GIMarshallingTests.double_inout(Number(self.MAX))) + self.assertAlmostEquals(self.MIN, GIMarshallingTests.double_inout(Number(self.MAX))) class TestGType(unittest.TestCase): @@ -664,9 +637,9 @@ class TestUtf8(unittest.TestCase): def test_utf8_none_in(self): GIMarshallingTests.utf8_none_in(CONSTANT_UTF8) if sys.version_info < (3, 0): - GIMarshallingTests.utf8_none_in(CONSTANT_UTF8.decode("utf-8")) + GIMarshallingTests.utf8_none_in(PY2_UNICODE_UTF8) - self.assertRaises(TypeError, GIMarshallingTests.utf8_none_in, 42) + self.assertRaises(TypeError, GIMarshallingTests.utf8_none_in, CONSTANT_NUMBER) self.assertRaises(TypeError, GIMarshallingTests.utf8_none_in, None) def test_utf8_none_out(self): @@ -685,185 +658,6 @@ class TestUtf8(unittest.TestCase): self.assertEqual("", GIMarshallingTests.utf8_full_inout(CONSTANT_UTF8)) -class TestFilename(unittest.TestCase): - def setUp(self): - self.workdir = tempfile.mkdtemp() - - def tearDown(self): - shutil.rmtree(self.workdir) - - def test_filename_in(self): - fname = os.path.join(self.workdir, u'testäø.txt') - self.assertRaises(GLib.GError, GLib.file_get_contents, fname) - - with open(fname.encode('UTF-8'), 'wb') as f: - f.write(b'hello world!\n\x01\x02') - - (result, contents) = GLib.file_get_contents(fname) - self.assertEqual(result, True) - self.assertEqual(contents, b'hello world!\n\x01\x02') - - def test_filename_in_nullable(self): - self.assertTrue(GIMarshallingTests.filename_copy(None) is None) - self.assertRaises(TypeError, GIMarshallingTests.filename_exists, None) - - @unittest.skipIf(os.name == "nt", "fixme") - def test_filename_out(self): - self.assertRaises(GLib.GError, GLib.Dir.make_tmp, 'test') - - dirname = GLib.Dir.make_tmp('testäø.XXXXXX') - self.assertTrue(os.path.sep + 'testäø.' in dirname, dirname) - self.assertTrue(os.path.isdir(dirname)) - os.rmdir(dirname) - - def test_wrong_types(self): - self.assertRaises(TypeError, GIMarshallingTests.filename_copy, 23) - self.assertRaises(TypeError, GIMarshallingTests.filename_copy, []) - - def test_null(self): - self.assertTrue(GIMarshallingTests.filename_copy(None) is None) - self.assertRaises(TypeError, GIMarshallingTests.filename_exists, None) - - def test_round_trip(self): - self.assertEqual(GIMarshallingTests.filename_copy(u"foo"), "foo") - self.assertEqual(GIMarshallingTests.filename_copy(b"foo"), "foo") - - def test_contains_null(self): - self.assertRaises( - (ValueError, TypeError), - GIMarshallingTests.filename_copy, b"foo\x00") - self.assertRaises( - (ValueError, TypeError), - GIMarshallingTests.filename_copy, u"foo\x00") - - def test_as_is_py2(self): - if not PY2: - return - - values = [ - b"foo", - b"\xff\xff", - b"\xc3\xb6\xc3\xa4\xc3\xbc", - b"\xed\xa0\xbd", - b"\xf0\x90\x80\x81", - ] - - for v in values: - self.assertEqual(GIMarshallingTests.filename_copy(v), v) - self.assertEqual(GIMarshallingTests.filename_to_glib_repr(v), v) - - def test_win32_surrogates(self): - if os.name != "nt": - return - - copy = GIMarshallingTests.filename_copy - glib_repr = GIMarshallingTests.filename_to_glib_repr - - if PY3: - self.assertEqual(copy(u"\ud83d"), u"\ud83d") - self.assertEqual(copy(u"\x61\uDC00"), u"\x61\uDC00") - self.assertEqual(copy(u"\uD800\uDC01"), u"\U00010001") - self.assertEqual(copy(u"\uD83D\x20\uDCA9"), u"\uD83D\x20\uDCA9") - else: - self.assertEqual(copy(u"\ud83d"), u"\ud83d".encode("utf-8")) - self.assertEqual(copy(u"\uD800\uDC01").decode("utf-8"), - u"\U00010001") - - self.assertEqual(glib_repr(u"\ud83d"), b"\xed\xa0\xbd") - self.assertEqual(glib_repr(u"\uD800\uDC01"), b"\xf0\x90\x80\x81") - - self.assertEqual( - glib_repr(u"\uD800\uDBFF"), b"\xED\xA0\x80\xED\xAF\xBF") - self.assertEqual( - glib_repr(u"\uD800\uE000"), b"\xED\xA0\x80\xEE\x80\x80") - self.assertEqual( - glib_repr(u"\uD7FF\uDC00"), b"\xED\x9F\xBF\xED\xB0\x80") - self.assertEqual(glib_repr(u"\x61\uDC00"), b"\x61\xED\xB0\x80") - self.assertEqual(glib_repr(u"\uDC00"), b"\xED\xB0\x80") - - def test_win32_bytes_py3(self): - if not (os.name == "nt" and PY3): - return - - values = [ - b"foo", - b"\xff\xff", - b"\xc3\xb6\xc3\xa4\xc3\xbc", - b"\xed\xa0\xbd", - b"\xf0\x90\x80\x81", - ] - - for v in values: - try: - uni = v.decode(sys.getfilesystemencoding(), "surrogatepass") - except UnicodeDecodeError: - continue - self.assertEqual(GIMarshallingTests.filename_copy(v), uni) - - def test_unix_various(self): - if os.name == "nt": - return - - copy = GIMarshallingTests.filename_copy - glib_repr = GIMarshallingTests.filename_to_glib_repr - - if PY3: - str_path = copy(b"\xff\xfe") - self.assertTrue(isinstance(str_path, str)) - self.assertEqual(str_path, os.fsdecode(b"\xff\xfe")) - self.assertEqual(copy(str_path), str_path) - self.assertEqual(glib_repr(b"\xff\xfe"), b"\xff\xfe") - self.assertEqual(glib_repr(str_path), b"\xff\xfe") - - # if getfilesystemencoding is ASCII, then we should fail like - # os.fsencode - try: - byte_path = os.fsencode(u"ä") - except UnicodeEncodeError: - self.assertRaises(UnicodeEncodeError, copy, u"ä") - else: - self.assertEqual(copy(u"ä"), u"ä") - self.assertEqual(glib_repr(u"ä"), byte_path) - else: - self.assertTrue(isinstance(copy(b"\xff\xfe"), bytes)) - self.assertEqual(copy(u"foo"), b"foo") - self.assertTrue(isinstance(copy(u"foo"), bytes)) - try: - byte_path = u"ä".encode(sys.getfilesystemencoding()) - except UnicodeEncodeError: - self.assertRaises(UnicodeEncodeError, copy, u"ä") - else: - self.assertEqual(copy(u"ä"), byte_path) - self.assertEqual(glib_repr(u"ä"), byte_path) - - @unittest.skip("glib can't handle non-unicode paths") - def test_win32_surrogates_exists(self): - if os.name != "nt": - return - - path = os.path.join(self.workdir, u"\ud83d") - with open(path, "wb"): - self.assertTrue(os.path.exists(path)) - self.assertTrue(GIMarshallingTests.filename_exists(path)) - os.unlink(path) - - def test_path_exists_various_types(self): - wd = self.workdir - wdb = os.fsencode(wd) if PY3 else wd - - paths = [(wdb, b"foo-1"), (wd, u"foo-2"), (wd, u"öäü-3")] - if PY3: - paths.append((wd, os.fsdecode(b"\xff\xfe-4"))) - - if os.name != "nt": - paths.append((wdb, b"\xff\xfe-5")) - - for (d, path) in paths: - path = os.path.join(d, path) - with open(path, "wb"): - self.assertTrue(GIMarshallingTests.filename_exists(path)) - - class TestArray(unittest.TestCase): def test_array_fixed_int_return(self): @@ -892,40 +686,19 @@ class TestArray(unittest.TestCase): def test_array_return(self): self.assertEqual([-1, 0, 1, 2], GIMarshallingTests.array_return()) - def test_array_return_etc(self): - self.assertEqual(([5, 0, 1, 9], 14), GIMarshallingTests.array_return_etc(5, 9)) - def test_array_in(self): GIMarshallingTests.array_in(Sequence([-1, 0, 1, 2])) - GIMarshallingTests.array_in_guint64_len(Sequence([-1, 0, 1, 2])) - GIMarshallingTests.array_in_guint8_len(Sequence([-1, 0, 1, 2])) - - def test_array_in_len_before(self): - GIMarshallingTests.array_in_len_before(Sequence([-1, 0, 1, 2])) - - def test_array_in_len_zero_terminated(self): - GIMarshallingTests.array_in_len_zero_terminated(Sequence([-1, 0, 1, 2])) def test_array_uint8_in(self): GIMarshallingTests.array_uint8_in(Sequence([97, 98, 99, 100])) - GIMarshallingTests.array_uint8_in(b"abcd") - - def test_array_string_in(self): - GIMarshallingTests.array_string_in(['foo', 'bar']) + GIMarshallingTests.array_uint8_in(_bytes("abcd")) def test_array_out(self): self.assertEqual([-1, 0, 1, 2], GIMarshallingTests.array_out()) - def test_array_out_etc(self): - self.assertEqual(([-5, 0, 1, 9], 4), GIMarshallingTests.array_out_etc(-5, 9)) - def test_array_inout(self): self.assertEqual([-2, -1, 0, 1, 2], GIMarshallingTests.array_inout(Sequence([-1, 0, 1, 2]))) - def test_array_inout_etc(self): - self.assertEqual(([-5, -1, 0, 1, 9], 4), - GIMarshallingTests.array_inout_etc(-5, Sequence([-1, 0, 1, 2]), 9)) - def test_method_array_in(self): object_ = GIMarshallingTests.Object() object_.method_array_in(Sequence([-1, 0, 1, 2])) @@ -957,55 +730,6 @@ class TestArray(unittest.TestCase): GIMarshallingTests.array_struct_in([struct1, struct2, struct3]) - def test_array_boxed_struct_in_item_marshal_failure(self): - struct1 = GIMarshallingTests.BoxedStruct() - struct1.long_ = 1 - struct2 = GIMarshallingTests.BoxedStruct() - struct2.long_ = 2 - - self.assertRaises(TypeError, GIMarshallingTests.array_struct_in, - [struct1, struct2, 'not_a_struct']) - - def test_array_boxed_struct_value_in(self): - struct1 = GIMarshallingTests.BoxedStruct() - struct1.long_ = 1 - struct2 = GIMarshallingTests.BoxedStruct() - struct2.long_ = 2 - struct3 = GIMarshallingTests.BoxedStruct() - struct3.long_ = 3 - - GIMarshallingTests.array_struct_value_in([struct1, struct2, struct3]) - - def test_array_boxed_struct_value_in_item_marshal_failure(self): - struct1 = GIMarshallingTests.BoxedStruct() - struct1.long_ = 1 - struct2 = GIMarshallingTests.BoxedStruct() - struct2.long_ = 2 - - self.assertRaises(TypeError, GIMarshallingTests.array_struct_value_in, - [struct1, struct2, 'not_a_struct']) - - def test_array_boxed_struct_take_in(self): - struct1 = GIMarshallingTests.BoxedStruct() - struct1.long_ = 1 - struct2 = GIMarshallingTests.BoxedStruct() - struct2.long_ = 2 - struct3 = GIMarshallingTests.BoxedStruct() - struct3.long_ = 3 - - GIMarshallingTests.array_struct_take_in([struct1, struct2, struct3]) - - self.assertEqual(1, struct1.long_) - - def test_array_boxed_struct_return(self): - (struct1, struct2, struct3) = GIMarshallingTests.array_zero_terminated_return_struct() - self.assertEqual(GIMarshallingTests.BoxedStruct, type(struct1)) - self.assertEqual(GIMarshallingTests.BoxedStruct, type(struct2)) - self.assertEqual(GIMarshallingTests.BoxedStruct, type(struct3)) - self.assertEqual(42, struct1.long_) - self.assertEqual(43, struct2.long_) - self.assertEqual(44, struct3.long_) - def test_array_simple_struct_in(self): struct1 = GIMarshallingTests.SimpleStruct() struct1.long_ = 1 @@ -1016,21 +740,12 @@ class TestArray(unittest.TestCase): GIMarshallingTests.array_simple_struct_in([struct1, struct2, struct3]) - def test_array_simple_struct_in_item_marshal_failure(self): - struct1 = GIMarshallingTests.SimpleStruct() - struct1.long_ = 1 - struct2 = GIMarshallingTests.SimpleStruct() - struct2.long_ = 2 - - self.assertRaises(TypeError, GIMarshallingTests.array_simple_struct_in, - [struct1, struct2, 'not_a_struct']) - def test_array_multi_array_key_value_in(self): GIMarshallingTests.multi_array_key_value_in(["one", "two", "three"], [1, 2, 3]) def test_array_in_nonzero_nonlen(self): - GIMarshallingTests.array_in_nonzero_nonlen(1, b'abcd') + GIMarshallingTests.array_in_nonzero_nonlen(1, 'abcd') def test_array_fixed_out_struct(self): struct1, struct2 = GIMarshallingTests.array_fixed_out_struct() @@ -1055,12 +770,6 @@ class TestArray(unittest.TestCase): def test_array_zero_terminated_inout(self): self.assertEqual(['-1', '0', '1', '2'], GIMarshallingTests.array_zero_terminated_inout(['0', '1', '2'])) - def test_init_function(self): - self.assertEqual((True, []), GIMarshallingTests.init_function([])) - self.assertEqual((True, []), GIMarshallingTests.init_function(['hello'])) - self.assertEqual((True, ['hello']), - GIMarshallingTests.init_function(['hello', 'world'])) - class TestGStrv(unittest.TestCase): @@ -1086,12 +795,12 @@ class TestArrayGVariant(unittest.TestCase): def test_array_gvariant_container_in(self): v = [GLib.Variant("i", 27), GLib.Variant("s", "Hello")] - returned = [GLib.Variant.unpack(r) for r in GIMarshallingTests.array_gvariant_container_in(v)] + returned = [GLib.Variant.unpack(r) for r in GIMarshallingTests.array_gvariant_none_in(v)] self.assertEqual([27, "Hello"], returned) def test_array_gvariant_full_in(self): v = [GLib.Variant("i", 27), GLib.Variant("s", "Hello")] - returned = [GLib.Variant.unpack(r) for r in GIMarshallingTests.array_gvariant_full_in(v)] + returned = [GLib.Variant.unpack(r) for r in GIMarshallingTests.array_gvariant_none_in(v)] self.assertEqual([27, "Hello"], returned) def test_bytearray_gvariant(self): @@ -1104,9 +813,6 @@ class TestGArray(unittest.TestCase): def test_garray_int_none_return(self): self.assertEqual([-1, 0, 1, 2], GIMarshallingTests.garray_int_none_return()) - def test_garray_uint64_none_return(self): - self.assertEqual([0, GLib.MAXUINT64], GIMarshallingTests.garray_uint64_none_return()) - def test_garray_utf8_none_return(self): self.assertEqual(['0', '1', '2'], GIMarshallingTests.garray_utf8_none_return()) @@ -1124,9 +830,6 @@ class TestGArray(unittest.TestCase): self.assertRaises(TypeError, GIMarshallingTests.garray_int_none_in, 42) self.assertRaises(TypeError, GIMarshallingTests.garray_int_none_in, None) - def test_garray_uint64_none_in(self): - GIMarshallingTests.garray_uint64_none_in(Sequence([0, GLib.MAXUINT64])) - def test_garray_utf8_none_in(self): GIMarshallingTests.garray_utf8_none_in(Sequence(['0', '1', '2'])) @@ -1139,9 +842,6 @@ class TestGArray(unittest.TestCase): def test_garray_utf8_full_out(self): self.assertEqual(['0', '1', '2'], GIMarshallingTests.garray_utf8_full_out()) - def test_garray_utf8_full_out_caller_allocated(self): - self.assertEqual(['0', '1', '2'], GIMarshallingTests.garray_utf8_full_out_caller_allocated()) - def test_garray_utf8_none_inout(self): self.assertEqual(['-2', '-1', '0', '1'], GIMarshallingTests.garray_utf8_none_inout(Sequence(('0', '1', '2')))) @@ -1185,75 +885,11 @@ class TestGPtrArray(unittest.TestCase): self.assertEqual(['-2', '-1', '0', '1'], GIMarshallingTests.gptrarray_utf8_full_inout(['0', '1', '2'])) -class TestGBytes(unittest.TestCase): - def test_gbytes_create(self): - b = GLib.Bytes.new(b'\x00\x01\xFF') - self.assertEqual(3, b.get_size()) - self.assertEqual(b'\x00\x01\xFF', b.get_data()) - - def test_gbytes_create_take(self): - b = GLib.Bytes.new_take(b'\x00\x01\xFF') - self.assertEqual(3, b.get_size()) - self.assertEqual(b'\x00\x01\xFF', b.get_data()) - - def test_gbytes_full_return(self): - b = GIMarshallingTests.gbytes_full_return() - self.assertEqual(4, b.get_size()) - self.assertEqual(b'\x00\x31\xFF\x33', b.get_data()) - - def test_gbytes_none_in(self): - b = GIMarshallingTests.gbytes_full_return() - GIMarshallingTests.gbytes_none_in(b) - - def test_compare(self): - a1 = GLib.Bytes.new(b'\x00\x01\xFF') - a2 = GLib.Bytes.new(b'\x00\x01\xFF') - b = GLib.Bytes.new(b'\x00\x01\xFE') - - self.assertTrue(a1.equal(a2)) - self.assertTrue(a2.equal(a1)) - self.assertFalse(a1.equal(b)) - self.assertFalse(b.equal(a2)) - - self.assertEqual(0, a1.compare(a2)) - self.assertLess(0, a1.compare(b)) - self.assertGreater(0, b.compare(a1)) - - -class TestGByteArray(unittest.TestCase): - def test_new(self): - ba = GLib.ByteArray.new() - self.assertEqual(b'', ba) - - ba = GLib.ByteArray.new_take(b'\x01\x02\xFF') - self.assertEqual(b'\x01\x02\xFF', ba) - - def test_bytearray_full_return(self): - self.assertEqual(b'\x001\xFF3', GIMarshallingTests.bytearray_full_return()) - - def test_bytearray_none_in(self): - b = b'\x00\x31\xFF\x33' - ba = GLib.ByteArray.new_take(b) - - # b should always have the same value even - # though the generated GByteArray is being modified - GIMarshallingTests.bytearray_none_in(b) - GIMarshallingTests.bytearray_none_in(b) - - # The GByteArray is just a bytes - # thus it will not reflect any changes - GIMarshallingTests.bytearray_none_in(ba) - GIMarshallingTests.bytearray_none_in(ba) - - class TestGList(unittest.TestCase): def test_glist_int_none_return(self): self.assertEqual([-1, 0, 1, 2], GIMarshallingTests.glist_int_none_return()) - def test_glist_uint32_none_return(self): - self.assertEqual([0, GLib.MAXUINT32], GIMarshallingTests.glist_uint32_none_return()) - def test_glist_utf8_none_return(self): self.assertEqual(['0', '1', '2'], GIMarshallingTests.glist_utf8_none_return()) @@ -1271,17 +907,6 @@ class TestGList(unittest.TestCase): self.assertRaises(TypeError, GIMarshallingTests.glist_int_none_in, 42) self.assertRaises(TypeError, GIMarshallingTests.glist_int_none_in, None) - def test_glist_int_none_in_error_getitem(self): - - class FailingSequence(Sequence): - def __getitem__(self, key): - raise Exception - - self.assertRaises(Exception, GIMarshallingTests.glist_int_none_in, FailingSequence((-1, 0, 1, 2))) - - def test_glist_uint32_none_in(self): - GIMarshallingTests.glist_uint32_none_in(Sequence((0, GLib.MAXUINT32))) - def test_glist_utf8_none_in(self): GIMarshallingTests.glist_utf8_none_in(Sequence(('0', '1', '2'))) @@ -1326,14 +951,6 @@ class TestGSList(unittest.TestCase): self.assertRaises(TypeError, GIMarshallingTests.gslist_int_none_in, 42) self.assertRaises(TypeError, GIMarshallingTests.gslist_int_none_in, None) - def test_gslist_int_none_in_error_getitem(self): - - class FailingSequence(Sequence): - def __getitem__(self, key): - raise Exception - - self.assertRaises(Exception, GIMarshallingTests.gslist_int_none_in, FailingSequence((-1, 0, 1, 2))) - def test_gslist_utf8_none_in(self): GIMarshallingTests.gslist_utf8_none_in(Sequence(('0', '1', '2'))) @@ -1392,30 +1009,16 @@ class TestGHashTable(unittest.TestCase): self.assertEqual({'-1': '1', '0': '0', '1': '-1', '2': '-2'}, GIMarshallingTests.ghashtable_utf8_full_out()) def test_ghashtable_utf8_none_inout(self): - i = {'-1': '1', '0': '0', '1': '-1', '2': '-2'} self.assertEqual({'-1': '1', '0': '0', '1': '1'}, - GIMarshallingTests.ghashtable_utf8_none_inout(i)) + GIMarshallingTests.ghashtable_utf8_none_inout({'-1': '1', '0': '0', '1': '-1', '2': '-2'})) def test_ghashtable_utf8_container_inout(self): - i = {'-1': '1', '0': '0', '1': '-1', '2': '-2'} self.assertEqual({'-1': '1', '0': '0', '1': '1'}, - GIMarshallingTests.ghashtable_utf8_container_inout(i)) + GIMarshallingTests.ghashtable_utf8_container_inout({'-1': '1', '0': '0', '1': '-1', '2': '-2'})) def test_ghashtable_utf8_full_inout(self): - i = {'-1': '1', '0': '0', '1': '-1', '2': '-2'} self.assertEqual({'-1': '1', '0': '0', '1': '1'}, - GIMarshallingTests.ghashtable_utf8_full_inout(i)) - - def test_ghashtable_enum_none_in(self): - GIMarshallingTests.ghashtable_enum_none_in({1: GIMarshallingTests.ExtraEnum.VALUE1, - 2: GIMarshallingTests.ExtraEnum.VALUE2, - 3: GIMarshallingTests.ExtraEnum.VALUE3}) - - def test_ghashtable_enum_none_return(self): - self.assertEqual({1: GIMarshallingTests.ExtraEnum.VALUE1, - 2: GIMarshallingTests.ExtraEnum.VALUE2, - 3: GIMarshallingTests.ExtraEnum.VALUE3}, - GIMarshallingTests.ghashtable_enum_none_return()) + GIMarshallingTests.ghashtable_utf8_full_inout({'-1': '1', '0': '0', '1': '-1', '2': '-2'})) class TestGValue(unittest.TestCase): @@ -1425,193 +1028,43 @@ class TestGValue(unittest.TestCase): def test_gvalue_in(self): GIMarshallingTests.gvalue_in(42) - value = GObject.Value(GObject.TYPE_INT, 42) + value = GObject.Value() + value.init(GObject.TYPE_INT) + value.set_int(42) GIMarshallingTests.gvalue_in(value) - def test_gvalue_in_with_modification(self): - value = GObject.Value(GObject.TYPE_INT, 42) - GIMarshallingTests.gvalue_in_with_modification(value) - self.assertEqual(value.get_int(), 24) - - def test_gvalue_int64_in(self): - value = GObject.Value(GObject.TYPE_INT64, GLib.MAXINT64) - GIMarshallingTests.gvalue_int64_in(value) - - def test_gvalue_in_with_type(self): - value = GObject.Value(GObject.TYPE_STRING, 'foo') - GIMarshallingTests.gvalue_in_with_type(value, GObject.TYPE_STRING) - - value = GObject.Value(GIMarshallingTests.Flags.__gtype__, - GIMarshallingTests.Flags.VALUE1) - GIMarshallingTests.gvalue_in_with_type(value, GObject.TYPE_FLAGS) - - def test_gvalue_in_enum(self): - value = GObject.Value(GIMarshallingTests.Enum.__gtype__, - GIMarshallingTests.Enum.VALUE3) - GIMarshallingTests.gvalue_in_enum(value) - def test_gvalue_out(self): self.assertEqual(42, GIMarshallingTests.gvalue_out()) - def test_gvalue_int64_out(self): - self.assertEqual(GLib.MAXINT64, GIMarshallingTests.gvalue_int64_out()) - - def test_gvalue_out_caller_allocates(self): - self.assertEqual(42, GIMarshallingTests.gvalue_out_caller_allocates()) - def test_gvalue_inout(self): self.assertEqual('42', GIMarshallingTests.gvalue_inout(42)) - value = GObject.Value(int, 42) + value = GObject.Value() + value.init(GObject.TYPE_INT) + value.set_int(42) self.assertEqual('42', GIMarshallingTests.gvalue_inout(value)) def test_gvalue_flat_array_in(self): # the function already asserts the correct values GIMarshallingTests.gvalue_flat_array([42, "42", True]) - def test_gvalue_flat_array_in_item_marshal_failure(self): - # Tests the failure to marshal 2^256 to a GValue mid-way through the array marshaling. - self.assertRaises(OverflowError, GIMarshallingTests.gvalue_flat_array, - [42, 2 ** 256, True]) - - self.assertRaises(OverflowError, GIMarshallingTests.gvalue_flat_array, - [GLib.MAXINT + 1, "42", True]) - self.assertRaises(OverflowError, GIMarshallingTests.gvalue_flat_array, - [GLib.MININT - 1, "42", True]) - def test_gvalue_flat_array_out(self): values = GIMarshallingTests.return_gvalue_flat_array() self.assertEqual(values, [42, '42', True]) - def test_gvalue_gobject_ref_counts(self): - # Tests a GObject held by a GValue - obj = GObject.Object() - ref = weakref.ref(obj) - grefcount = obj.__grefcount__ - - value = GObject.Value() - value.init(GObject.TYPE_OBJECT) - - # TYPE_OBJECT will inc ref count as it should - value.set_object(obj) - self.assertEqual(obj.__grefcount__, grefcount + 1) - - # multiple set_object should not inc ref count - value.set_object(obj) - self.assertEqual(obj.__grefcount__, grefcount + 1) - - # get_object will re-use the same wrapper as obj - res = value.get_object() - self.assertEqual(obj, res) - self.assertEqual(obj.__grefcount__, grefcount + 1) - - # multiple get_object should not inc ref count - res = value.get_object() - self.assertEqual(obj.__grefcount__, grefcount + 1) - - # deletion of the result and value holder should bring the - # refcount back to where we started - del res - del value - gc.collect() - self.assertEqual(obj.__grefcount__, grefcount) - - del obj - gc.collect() - self.assertEqual(ref(), None) - - def test_gvalue_boxed_ref_counts(self): - # Tests a boxed type wrapping a python object pointer (TYPE_PYOBJECT) - # held by a GValue - class Obj(object): - pass - - obj = Obj() - ref = weakref.ref(obj) - refcount = sys.getrefcount(obj) - - value = GObject.Value() - value.init(GObject.TYPE_PYOBJECT) - - # boxed TYPE_PYOBJECT will inc ref count as it should - value.set_boxed(obj) - self.assertEqual(sys.getrefcount(obj), refcount + 1) - - # multiple set_boxed should not inc ref count - value.set_boxed(obj) - self.assertEqual(sys.getrefcount(obj), refcount + 1) - - res = value.get_boxed() - self.assertEqual(obj, res) - self.assertEqual(sys.getrefcount(obj), refcount + 2) - - # multiple get_boxed should not inc ref count - res = value.get_boxed() - self.assertEqual(sys.getrefcount(obj), refcount + 2) - - # deletion of the result and value holder should bring the - # refcount back to where we started - del res - del value - gc.collect() - self.assertEqual(sys.getrefcount(obj), refcount) - - del obj - gc.collect() - self.assertEqual(ref(), None) - - # FIXME: crashes - def disabled_test_gvalue_flat_array_round_trip(self): - self.assertEqual([42, '42', True], - GIMarshallingTests.gvalue_flat_array_round_trip(42, '42', True)) - class TestGClosure(unittest.TestCase): - def test_in(self): + def test_gclosure_in(self): GIMarshallingTests.gclosure_in(lambda: 42) - def test_pass(self): # test passing a closure between two C calls closure = GIMarshallingTests.gclosure_return() GIMarshallingTests.gclosure_in(closure) - def test_type_error(self): self.assertRaises(TypeError, GIMarshallingTests.gclosure_in, 42) self.assertRaises(TypeError, GIMarshallingTests.gclosure_in, None) -class TestCallbacks(unittest.TestCase): - def test_return_value_only(self): - def cb(): - return 5 - self.assertEqual(GIMarshallingTests.callback_return_value_only(cb), 5) - - def test_one_out_arg(self): - def cb(): - return 5.5 - self.assertAlmostEqual(GIMarshallingTests.callback_one_out_parameter(cb), 5.5) - - def test_multiple_out_args(self): - def cb(): - return (5.5, 42.0) - res = GIMarshallingTests.callback_multiple_out_parameters(cb) - self.assertAlmostEqual(res[0], 5.5) - self.assertAlmostEqual(res[1], 42.0) - - def test_return_and_one_out_arg(self): - def cb(): - return (5, 42.0) - res = GIMarshallingTests.callback_return_value_and_one_out_parameter(cb) - self.assertEqual(res[0], 5) - self.assertAlmostEqual(res[1], 42.0) - - def test_return_and_multiple_out_arg(self): - def cb(): - return (5, 42, -1000) - self.assertEqual(GIMarshallingTests.callback_return_value_and_multiple_out_parameters(cb), - (5, 42, -1000)) - - class TestPointer(unittest.TestCase): def test_pointer_in_return(self): self.assertEqual(GIMarshallingTests.pointer_in_return(42), 42) @@ -1628,19 +1081,15 @@ class TestEnum(unittest.TestCase): Run test under a locale which defines toupper('a') == 'a' ''' - if sys.platform == "darwin" or os.name == "nt": - return cls.locale_dir = tempfile.mkdtemp() - src = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'te_ST@nouppera') - dest = os.path.join(cls.locale_dir, 'te_ST.UTF-8@nouppera') - subprocess.check_call(['localedef', '-i', src, '-c', '-f', 'UTF-8', dest]) + subprocess.check_call(['localedef', '-i', + os.path.join(os.path.dirname(os.path.realpath(__file__)), 'te_ST@nouppera'), + '-c', '-f', 'UTF-8', os.path.join(cls.locale_dir, 'te_ST.UTF-8@nouppera')]) os.environ['LOCPATH'] = cls.locale_dir locale.setlocale(locale.LC_ALL, 'te_ST.UTF-8@nouppera') @classmethod def tearDownClass(cls): - if sys.platform == "darwin" or os.name == "nt": - return locale.setlocale(locale.LC_ALL, 'C') shutil.rmtree(cls.locale_dir) try: @@ -1671,11 +1120,6 @@ class TestEnum(unittest.TestCase): self.assertRaises(TypeError, GIMarshallingTests.enum_in, 43) self.assertRaises(TypeError, GIMarshallingTests.enum_in, 'GIMarshallingTests.Enum.VALUE3') - def test_enum_return(self): - enum = GIMarshallingTests.enum_returnv() - self.assertTrue(isinstance(enum, GIMarshallingTests.Enum)) - self.assertEqual(enum, GIMarshallingTests.Enum.VALUE3) - def test_enum_out(self): enum = GIMarshallingTests.enum_out() self.assertTrue(isinstance(enum, GIMarshallingTests.Enum)) @@ -1696,42 +1140,6 @@ class TestEnum(unittest.TestCase): self.assertTrue(hasattr(GIMarshallingTests.Enum, "VALUE1")) self.assertRaises(AttributeError, getattr, GIMarshallingTests.SecondEnum, "VALUE1") - def test_enum_gtype_name_is_namespaced(self): - self.assertEqual(GIMarshallingTests.Enum.__gtype__.name, - 'PyGIMarshallingTestsEnum') - - def test_enum_add_type_error(self): - self.assertRaises(TypeError, - gi._gi.enum_add, - GIMarshallingTests.NoTypeFlags.__gtype__) - - def test_type_module_name(self): - self.assertEqual(GIMarshallingTests.Enum.__name__, "Enum") - self.assertEqual(GIMarshallingTests.Enum.__module__, - "gi.repository.GIMarshallingTests") - - def test_repr(self): - self.assertEqual(repr(GIMarshallingTests.Enum.VALUE3), - "<enum GI_MARSHALLING_TESTS_ENUM_VALUE3 of type " - "GIMarshallingTests.Enum>") - - -class TestEnumVFuncResults(unittest.TestCase): - class EnumTester(GIMarshallingTests.Object): - def do_vfunc_return_enum(self): - return GIMarshallingTests.Enum.VALUE2 - - def do_vfunc_out_enum(self): - return GIMarshallingTests.Enum.VALUE3 - - def test_vfunc_return_enum(self): - tester = self.EnumTester() - self.assertEqual(tester.vfunc_return_enum(), GIMarshallingTests.Enum.VALUE2) - - def test_vfunc_out_enum(self): - tester = self.EnumTester() - self.assertEqual(tester.vfunc_out_enum(), GIMarshallingTests.Enum.VALUE3) - class TestGEnum(unittest.TestCase): @@ -1754,19 +1162,12 @@ class TestGEnum(unittest.TestCase): def test_genum_in(self): GIMarshallingTests.genum_in(GIMarshallingTests.GEnum.VALUE3) GIMarshallingTests.genum_in(42) - GIMarshallingTests.GEnum.in_(42) self.assertRaises(TypeError, GIMarshallingTests.genum_in, 43) self.assertRaises(TypeError, GIMarshallingTests.genum_in, 'GIMarshallingTests.GEnum.VALUE3') - def test_genum_return(self): - genum = GIMarshallingTests.genum_returnv() - self.assertTrue(isinstance(genum, GIMarshallingTests.GEnum)) - self.assertEqual(genum, GIMarshallingTests.GEnum.VALUE3) - def test_genum_out(self): genum = GIMarshallingTests.genum_out() - genum = GIMarshallingTests.GEnum.out() self.assertTrue(isinstance(genum, GIMarshallingTests.GEnum)) self.assertEqual(genum, GIMarshallingTests.GEnum.VALUE3) @@ -1775,16 +1176,6 @@ class TestGEnum(unittest.TestCase): self.assertTrue(isinstance(genum, GIMarshallingTests.GEnum)) self.assertEqual(genum, GIMarshallingTests.GEnum.VALUE1) - def test_type_module_name(self): - self.assertEqual(GIMarshallingTests.GEnum.__name__, "GEnum") - self.assertEqual(GIMarshallingTests.GEnum.__module__, - "gi.repository.GIMarshallingTests") - - def test_repr(self): - self.assertEqual(repr(GIMarshallingTests.GEnum.VALUE3), - "<enum GI_MARSHALLING_TESTS_GENUM_VALUE3 of type " - "GIMarshallingTests.GEnum>") - class TestGFlags(unittest.TestCase): @@ -1809,25 +1200,13 @@ class TestGFlags(unittest.TestCase): def test_flags_in(self): GIMarshallingTests.flags_in(GIMarshallingTests.Flags.VALUE2) - GIMarshallingTests.Flags.in_(GIMarshallingTests.Flags.VALUE2) # result of __or__() operation should still be valid instance, not an int. GIMarshallingTests.flags_in(GIMarshallingTests.Flags.VALUE2 | GIMarshallingTests.Flags.VALUE2) GIMarshallingTests.flags_in_zero(Number(0)) - GIMarshallingTests.Flags.in_zero(Number(0)) self.assertRaises(TypeError, GIMarshallingTests.flags_in, 1 << 1) self.assertRaises(TypeError, GIMarshallingTests.flags_in, 'GIMarshallingTests.Flags.VALUE2') - def test_flags_return(self): - flags = GIMarshallingTests.flags_returnv() - self.assertTrue(isinstance(flags, GIMarshallingTests.Flags)) - self.assertEqual(flags, GIMarshallingTests.Flags.VALUE2) - - def test_flags_return_method(self): - flags = GIMarshallingTests.Flags.returnv() - self.assertTrue(isinstance(flags, GIMarshallingTests.Flags)) - self.assertEqual(flags, GIMarshallingTests.Flags.VALUE2) - def test_flags_out(self): flags = GIMarshallingTests.flags_out() self.assertTrue(isinstance(flags, GIMarshallingTests.Flags)) @@ -1838,16 +1217,6 @@ class TestGFlags(unittest.TestCase): self.assertTrue(isinstance(flags, GIMarshallingTests.Flags)) self.assertEqual(flags, GIMarshallingTests.Flags.VALUE1) - def test_type_module_name(self): - self.assertEqual(GIMarshallingTests.Flags.__name__, "Flags") - self.assertEqual(GIMarshallingTests.Flags.__module__, - "gi.repository.GIMarshallingTests") - - def test_repr(self): - self.assertEqual(repr(GIMarshallingTests.Flags.VALUE2), - "<flags GI_MARSHALLING_TESTS_FLAGS_VALUE2 of type " - "GIMarshallingTests.Flags>") - class TestNoTypeFlags(unittest.TestCase): @@ -1878,11 +1247,6 @@ class TestNoTypeFlags(unittest.TestCase): self.assertRaises(TypeError, GIMarshallingTests.no_type_flags_in, 1 << 1) self.assertRaises(TypeError, GIMarshallingTests.no_type_flags_in, 'GIMarshallingTests.NoTypeFlags.VALUE2') - def test_flags_return(self): - flags = GIMarshallingTests.no_type_flags_returnv() - self.assertTrue(isinstance(flags, GIMarshallingTests.NoTypeFlags)) - self.assertEqual(flags, GIMarshallingTests.NoTypeFlags.VALUE2) - def test_flags_out(self): flags = GIMarshallingTests.no_type_flags_out() self.assertTrue(isinstance(flags, GIMarshallingTests.NoTypeFlags)) @@ -1893,21 +1257,6 @@ class TestNoTypeFlags(unittest.TestCase): self.assertTrue(isinstance(flags, GIMarshallingTests.NoTypeFlags)) self.assertEqual(flags, GIMarshallingTests.NoTypeFlags.VALUE1) - def test_flags_gtype_name_is_namespaced(self): - self.assertEqual(GIMarshallingTests.NoTypeFlags.__gtype__.name, - 'PyGIMarshallingTestsNoTypeFlags') - - def test_type_module_name(self): - self.assertEqual(GIMarshallingTests.NoTypeFlags.__name__, - "NoTypeFlags") - self.assertEqual(GIMarshallingTests.NoTypeFlags.__module__, - "gi.repository.GIMarshallingTests") - - def test_repr(self): - self.assertEqual(repr(GIMarshallingTests.NoTypeFlags.VALUE2), - "<flags GI_MARSHALLING_TESTS_NO_TYPE_FLAGS_VALUE2 of " - "type GIMarshallingTests.NoTypeFlags>") - class TestStructure(unittest.TestCase): @@ -2010,7 +1359,6 @@ class TestStructure(unittest.TestCase): self.assertTrue(isinstance(struct, GIMarshallingTests.BoxedStruct)) self.assertEqual(0, struct.long_) - self.assertEqual(None, struct.string_) self.assertEqual([], struct.g_strv) del struct @@ -2018,20 +1366,14 @@ class TestStructure(unittest.TestCase): def test_boxed_struct_new(self): struct = GIMarshallingTests.BoxedStruct.new() self.assertTrue(isinstance(struct, GIMarshallingTests.BoxedStruct)) - self.assertEqual(struct.long_, 0) - self.assertEqual(struct.string_, None) del struct def test_boxed_struct_copy(self): struct = GIMarshallingTests.BoxedStruct() - struct.long_ = 42 - struct.string_ = 'hello' new_struct = struct.copy() self.assertTrue(isinstance(new_struct, GIMarshallingTests.BoxedStruct)) - self.assertEqual(new_struct.long_, 42) - self.assertEqual(new_struct.string_, 'hello') del new_struct del struct @@ -2041,7 +1383,6 @@ class TestStructure(unittest.TestCase): self.assertTrue(isinstance(struct, GIMarshallingTests.BoxedStruct)) self.assertEqual(42, struct.long_) - self.assertEqual('hello', struct.string_) self.assertEqual(['0', '1', '2'], struct.g_strv) del struct @@ -2074,27 +1415,6 @@ class TestStructure(unittest.TestCase): del in_struct del out_struct - def test_struct_field_assignment(self): - struct = GIMarshallingTests.BoxedStruct() - - struct.long_ = 42 - struct.string_ = 'hello' - self.assertEqual(struct.long_, 42) - self.assertEqual(struct.string_, 'hello') - - def test_union_init(self): - with warnings.catch_warnings(record=True) as warn: - warnings.simplefilter('always') - GIMarshallingTests.Union(42) - - self.assertTrue(issubclass(warn[0].category, TypeError)) - - with warnings.catch_warnings(record=True) as warn: - warnings.simplefilter('always') - GIMarshallingTests.Union(f=42) - - self.assertTrue(issubclass(warn[0].category, TypeError)) - def test_union(self): union = GIMarshallingTests.Union() @@ -2132,27 +1452,6 @@ class TestStructure(unittest.TestCase): self.assertRaises(TypeError, GIMarshallingTests.Union.method) - def test_repr(self): - self.assertRegexpMatches( - repr(GIMarshallingTests.PointerStruct()), - r"<GIMarshallingTests.PointerStruct object at 0x[^\s]+ " - r"\(void at 0x[^\s]+\)>") - - self.assertRegexpMatches( - repr(GIMarshallingTests.SimpleStruct()), - r"<GIMarshallingTests.SimpleStruct object at 0x[^\s]+ " - r"\(void at 0x[^\s]+\)>") - - self.assertRegexpMatches( - repr(GIMarshallingTests.Union()), - r"<GIMarshallingTests.Union object at 0x[^\s]+ " - r"\(GIMarshallingTestsUnion at 0x[^\s]+\)>") - - self.assertRegexpMatches( - repr(GIMarshallingTests.BoxedStruct()), - r"<GIMarshallingTests.BoxedStruct object at 0x[^\s]+ " - r"\(GIMarshallingTestsBoxedStruct at 0x[^\s]+\)>") - class TestGObject(unittest.TestCase): @@ -2270,9 +1569,6 @@ class TestGObject(unittest.TestCase): GIMarshallingTests.Object.none_inout(GIMarshallingTests.SubObject(int=42)) def test_object_full_inout(self): - # Using gimarshallingtests.c from GI versions > 1.38.0 will show this - # test as an "unexpected success" due to reference leak fixes in that file. - # TODO: remove the expectedFailure once PyGI relies on GI > 1.38.0. object_ = GIMarshallingTests.Object(int=42) new_object = GIMarshallingTests.Object.full_inout(object_) @@ -2280,21 +1576,9 @@ class TestGObject(unittest.TestCase): self.assertFalse(object_ is new_object) - self.assertEqual(object_.__grefcount__, 1) + self.assertEqual(object_.__grefcount__, 2) self.assertEqual(new_object.__grefcount__, 1) - def test_repr(self): - self.assertRegexpMatches( - repr(GIMarshallingTests.Object(int=42)), - r"<GIMarshallingTests.Object object at 0x[^\s]+ " - r"\(GIMarshallingTestsObject at 0x[^\s]+\)>") - - def test_nongir_repr(self): - self.assertRegexpMatches( - repr(Gio.File.new_for_path("")), - r"<__gi__.GLocalFile object at 0x[^\s]+ " - r"\(GLocalFile at 0x[^\s]+\)>") - # FIXME: Doesn't actually return the same object. # def test_object_inout_same(self): # object_ = GIMarshallingTests.Object() @@ -2306,8 +1590,6 @@ class TestGObject(unittest.TestCase): class TestPythonGObject(unittest.TestCase): class Object(GIMarshallingTests.Object): - return_for_caller_allocated_out_parameter = 'test caller alloc return' - def __init__(self, int): GIMarshallingTests.Object.__init__(self) self.val = None @@ -2322,37 +1604,10 @@ class TestPythonGObject(unittest.TestCase): def do_method_int8_out(self): return 42 - def do_method_int8_arg_and_out_caller(self, arg): - return arg + 1 - - def do_method_int8_arg_and_out_callee(self, arg): - return arg + 1 - - def do_method_str_arg_out_ret(self, arg): - return (arg.upper(), len(arg)) - def do_method_with_default_implementation(self, int8): GIMarshallingTests.Object.do_method_with_default_implementation(self, int8) self.props.int += int8 - def do_vfunc_return_value_only(self): - return 4242 - - def do_vfunc_one_out_parameter(self): - return 42.42 - - def do_vfunc_multiple_out_parameters(self): - return (42.42, 3.14) - - def do_vfunc_return_value_and_one_out_parameter(self): - return (5, 42) - - def do_vfunc_return_value_and_multiple_out_parameters(self): - return (5, 42, 99) - - def do_vfunc_caller_allocated_out_parameter(self): - return self.return_for_caller_allocated_out_parameter - class SubObject(GIMarshallingTests.SubObject): def __init__(self, int): GIMarshallingTests.SubObject.__init__(self) @@ -2361,35 +1616,12 @@ class TestPythonGObject(unittest.TestCase): def do_method_with_default_implementation(self, int8): self.val = int8 - def do_vfunc_return_value_only(self): - return 2121 - - class Interface3Impl(GObject.Object, GIMarshallingTests.Interface3): - def __init__(self): - GObject.Object.__init__(self) - self.variants = None - self.n_variants = None - - def do_test_variant_array_in(self, variants, n_variants): - self.variants = variants - self.n_variants = n_variants - - class ErrorObject(GIMarshallingTests.Object): - def do_vfunc_return_value_only(self): - raise ValueError('Return value should be 0') - def test_object(self): self.assertTrue(issubclass(self.Object, GIMarshallingTests.Object)) object_ = self.Object(int=42) self.assertTrue(isinstance(object_, self.Object)) - @unittest.skipUnless(hasattr(GIMarshallingTests.Object, 'new_fail'), - 'Requires newer version of GI') - def test_object_fail(self): - with self.assertRaises(GLib.Error): - GIMarshallingTests.Object.new_fail(int_=42) - def test_object_method(self): self.Object(int=0).method() @@ -2399,28 +1631,9 @@ class TestPythonGObject(unittest.TestCase): self.assertEqual(object_.val, 84) self.assertEqual(object_.method_int8_out(), 42) - # can be dropped when bumping g-i dependencies to >= 1.35.2 - if hasattr(object_, 'method_int8_arg_and_out_caller'): - self.assertEqual(object_.method_int8_arg_and_out_caller(42), 43) - self.assertEqual(object_.method_int8_arg_and_out_callee(42), 43) - self.assertEqual(object_.method_str_arg_out_ret('hello'), ('HELLO', 5)) - object_.method_with_default_implementation(42) self.assertEqual(object_.props.int, 84) - self.assertEqual(object_.vfunc_return_value_only(), 4242) - self.assertAlmostEqual(object_.vfunc_one_out_parameter(), 42.42, places=5) - - (a, b) = object_.vfunc_multiple_out_parameters() - self.assertAlmostEqual(a, 42.42, places=5) - self.assertAlmostEqual(b, 3.14, places=5) - - self.assertEqual(object_.vfunc_return_value_and_one_out_parameter(), (5, 42)) - self.assertEqual(object_.vfunc_return_value_and_multiple_out_parameters(), (5, 42, 99)) - - self.assertEqual(object_.vfunc_caller_allocated_out_parameter(), - object_.return_for_caller_allocated_out_parameter) - class ObjectWithoutVFunc(GIMarshallingTests.Object): def __init__(self, int): GIMarshallingTests.Object.__init__(self) @@ -2429,30 +1642,22 @@ class TestPythonGObject(unittest.TestCase): object_.method_with_default_implementation(84) self.assertEqual(object_.props.int, 84) - def test_vfunc_return_ref_count(self): - obj = self.Object(int=42) - ref_count = sys.getrefcount(obj.return_for_caller_allocated_out_parameter) - ret = obj.vfunc_caller_allocated_out_parameter() - gc.collect() - - # Make sure the return and what the vfunc returned - # are equal but not the same object. - self.assertEqual(ret, obj.return_for_caller_allocated_out_parameter) - self.assertFalse(ret is obj.return_for_caller_allocated_out_parameter) - self.assertEqual(sys.getrefcount(obj.return_for_caller_allocated_out_parameter), - ref_count) - def test_subobject_parent_vfunc(self): object_ = self.SubObject(int=81) object_.method_with_default_implementation(87) self.assertEqual(object_.val, 87) - def test_subobject_child_vfunc(self): - object_ = self.SubObject(int=1) - self.assertEqual(object_.vfunc_return_value_only(), 2121) + def test_dynamic_module(self): + from gi.module import DynamicGObjectModule + self.assertTrue(isinstance(GObject, DynamicGObjectModule)) + # compare the same enum from both the pygobject attrs and gi GObject attrs + self.assertEqual(GObject.SIGNAL_ACTION, GObject.SignalFlags.ACTION) + # compare a static gobject attr with a dynamic GObject attr + import gi._gobject + self.assertEqual(GObject.GObject, gi._gobject.GObject) def test_subobject_non_vfunc_do_method(self): - class PythonObjectWithNonVFuncDoMethod(object): + class PythonObjectWithNonVFuncDoMethod: def do_not_a_vfunc(self): return 5 @@ -2488,41 +1693,6 @@ class TestPythonGObject(unittest.TestCase): GIMarshallingTests.SubSubObject.do_method_deep_hierarchy(sub_sub_sub_object, 5) self.assertEqual(sub_sub_sub_object.props.int, 5) - def test_interface3impl(self): - iface3 = self.Interface3Impl() - variants = [GLib.Variant('i', 27), GLib.Variant('s', 'Hello')] - iface3.test_variant_array_in(variants) - self.assertEqual(iface3.n_variants, 2) - self.assertEqual(iface3.variants[0].unpack(), 27) - self.assertEqual(iface3.variants[1].unpack(), 'Hello') - - def test_python_subsubobject_vfunc(self): - class PySubObject(GIMarshallingTests.Object): - def __init__(self): - GIMarshallingTests.Object.__init__(self) - self.sub_method_int8_called = 0 - - def do_method_int8_in(self, int8): - self.sub_method_int8_called += 1 - - class PySubSubObject(PySubObject): - def __init__(self): - PySubObject.__init__(self) - self.subsub_method_int8_called = 0 - - def do_method_int8_in(self, int8): - self.subsub_method_int8_called += 1 - - so = PySubObject() - so.method_int8_in(1) - self.assertEqual(so.sub_method_int8_called, 1) - - # it should call the method on the SubSub object only - sso = PySubSubObject() - sso.method_int8_in(1) - self.assertEqual(sso.subsub_method_int8_called, 1) - self.assertEqual(sso.sub_method_int8_called, 0) - def test_callback_in_vfunc(self): class SubObject(GIMarshallingTests.Object): def __init__(self): @@ -2534,30 +1704,10 @@ class TestPythonGObject(unittest.TestCase): _object = SubObject() _object.call_vfunc_with_callback() - self.assertTrue(_object.worked) + self.assertTrue(_object.worked == True) _object.worked = False _object.call_vfunc_with_callback() - self.assertTrue(_object.worked) - - def test_exception_in_vfunc_return_value(self): - obj = self.ErrorObject() - with capture_exceptions() as exc: - self.assertEqual(obj.vfunc_return_value_only(), 0) - self.assertEqual(len(exc), 1) - self.assertEqual(exc[0].type, ValueError) - - @unittest.skipUnless(hasattr(GIMarshallingTests, 'callback_owned_boxed'), - 'requires newer version of GI') - def test_callback_owned_box(self): - def callback(box, data): - self.box = box - - def nop_callback(box, data): - pass - - GIMarshallingTests.callback_owned_boxed(callback, None) - GIMarshallingTests.callback_owned_boxed(nop_callback, None) - self.assertEqual(self.box.long_, 1) + self.assertTrue(_object.worked == True) class TestMultiOutputArgs(unittest.TestCase): @@ -2569,8 +1719,21 @@ class TestMultiOutputArgs(unittest.TestCase): self.assertEqual((6, 7), GIMarshallingTests.int_return_out()) +class TestGErrorException(unittest.TestCase): + def test_gerror_exception(self): + self.assertRaises(GObject.GError, GIMarshallingTests.gerror) + try: + GIMarshallingTests.gerror() + except Exception: + etype, e = sys.exc_info()[:2] + self.assertEqual(e.domain, GIMarshallingTests.CONSTANT_GERROR_DOMAIN) + self.assertEqual(e.code, GIMarshallingTests.CONSTANT_GERROR_CODE) + self.assertEqual(e.message, GIMarshallingTests.CONSTANT_GERROR_MESSAGE) + + # Interface + class TestInterfaces(unittest.TestCase): class TestInterfaceImpl(GObject.GObject, GIMarshallingTests.Interface): @@ -2608,102 +1771,7 @@ class TestInterfaces(unittest.TestCase): GIMarshallingTests.test_interface_test_int8_in(instance, 42) self.assertEqual(instance.val, 42) - def test_subclass_override(self): - class TestInterfaceImplD(TestInterfaces.TestInterfaceImpl): - val2 = None - - def do_test_int8_in(self, int8): - self.val2 = int8 - - instance = TestInterfaceImplD() - self.assertEqual(instance.val, None) - self.assertEqual(instance.val2, None) - - GIMarshallingTests.test_interface_test_int8_in(instance, 42) - self.assertEqual(instance.val, None) - self.assertEqual(instance.val2, 42) - - def test_type_mismatch(self): - obj = GIMarshallingTests.Object() - - # wrong type for first argument: interface - enum = Gio.File.new_for_path('.').enumerate_children( - '', Gio.FileQueryInfoFlags.NONE, None) - try: - enum.next_file(obj) - self.fail('call with wrong type argument unexpectedly succeeded') - except TypeError as e: - # should have argument name - self.assertTrue('cancellable' in str(e), e) - # should have expected type - self.assertTrue('xpected Gio.Cancellable' in str(e), e) - # should have actual type - self.assertTrue('GIMarshallingTests.Object' in str(e), e) - - # wrong type for self argument: interface - try: - Gio.FileEnumerator.next_file(obj, None) - self.fail('call with wrong type argument unexpectedly succeeded') - except TypeError as e: - # should have argument name - self.assertTrue('self' in str(e), e) - # should have expected type - self.assertTrue('xpected Gio.FileEnumerator' in str(e), e) - # should have actual type - self.assertTrue('GIMarshallingTests.Object' in str(e), e) - - # wrong type for first argument: GObject - var = GLib.Variant('s', 'mystring') - action = Gio.SimpleAction.new('foo', var.get_type()) - try: - action.activate(obj) - self.fail('call with wrong type argument unexpectedly succeeded') - except TypeError as e: - # should have argument name - self.assertTrue('parameter' in str(e), e) - # should have expected type - self.assertTrue('xpected GLib.Variant' in str(e), e) - # should have actual type - self.assertTrue('GIMarshallingTests.Object' in str(e), e) - - # wrong type for self argument: GObject - try: - Gio.SimpleAction.activate(obj, obj) - self.fail('call with wrong type argument unexpectedly succeeded') - except TypeError as e: - # should have argument name - self.assertTrue('self' in str(e), e) - # should have expected type - self.assertTrue('xpected Gio.Action' in str(e), e) - # should have actual type - self.assertTrue('GIMarshallingTests.Object' in str(e), e) - - -class TestMRO(unittest.TestCase): def test_mro(self): - # check that our own MRO calculation matches what we would expect - # from Python's own C3 calculations - class A(object): - pass - - class B(A): - pass - - class C(A): - pass - - class D(B, C): - pass - - class E(D, GIMarshallingTests.Object): - pass - - expected = (E, D, B, C, A, GIMarshallingTests.Object, - GObject.Object, GObject.Object.__base__, gi._gi.GObject, - object) - self.assertEqual(expected, E.__mro__) - - def test_interface_collision(self): # there was a problem with Python bailing out because of # http://en.wikipedia.org/wiki/Diamond_problem with interfaces, # which shouldn't really be a problem. @@ -2715,27 +1783,10 @@ class TestMRO(unittest.TestCase): TestInterfaceImpl): pass - class TestInterfaceImpl3(TestInterfaceImpl, + class TestInterfaceImpl3(self.TestInterfaceImpl, GIMarshallingTests.Interface2): pass - def test_old_style_mixin(self): - # Note: Old style classes don't exist in Python 3 - class Mixin: - pass - - with warnings.catch_warnings(record=True) as warn: - warnings.simplefilter('always') - - # Dynamically create a new gi based class with an old - # style mixin. - type('GIWithOldStyleMixin', (GIMarshallingTests.Object, Mixin), {}) - - if sys.version_info < (3, 0): - self.assertTrue(issubclass(warn[0].category, RuntimeWarning)) - else: - self.assertEqual(len(warn), 0) - class TestInterfaceClash(unittest.TestCase): @@ -2792,13 +1843,7 @@ class TestOverrides(unittest.TestCase): self.assertTrue(isinstance(object_, GIMarshallingTests.OverridesObject)) def test_module_name(self): - # overridden types self.assertEqual(GIMarshallingTests.OverridesStruct.__module__, 'gi.overrides.GIMarshallingTests') - self.assertEqual(GIMarshallingTests.OverridesObject.__module__, 'gi.overrides.GIMarshallingTests') - self.assertEqual(GObject.Object.__module__, 'gi.overrides.GObject') - - # not overridden - self.assertEqual(GIMarshallingTests.SubObject.__module__, 'gi.repository.GIMarshallingTests') self.assertEqual(GObject.InitiallyUnowned.__module__, 'gi.repository.GObject') @@ -2827,25 +1872,49 @@ class TestDir(unittest.TestCase): # self.assertTrue('DoNotImportDummyTests' in list) -class TestParamSpec(unittest.TestCase): - # https://bugzilla.gnome.org/show_bug.cgi?id=682355 - @unittest.expectedFailure - def test_param_spec_in_bool(self): - ps = GObject.param_spec_boolean('mybool', 'test-bool', 'boolblurb', - True, GObject.ParamFlags.READABLE) - GIMarshallingTests.param_spec_in_bool(ps) +class TestGErrorArrayInCrash(unittest.TestCase): + # Previously there was a bug in invoke, in which C arrays were unwrapped + # from inside GArrays to be passed to the C function. But when a GError was + # set, invoke would attempt to free the C array as if it were a GArray. + # This crash is only for C arrays. It does not happen for C functions which + # take in GArrays. See https://bugzilla.gnome.org/show_bug.cgi?id=642708 + def test_gerror_array_in_crash(self): + self.assertRaises(GObject.GError, GIMarshallingTests.gerror_array_in, [1, 2, 3]) + - def test_param_spec_return(self): - obj = GIMarshallingTests.param_spec_return() - self.assertEqual(obj.name, 'test-param') - self.assertEqual(obj.nick, 'test') - self.assertEqual(obj.value_type, GObject.TYPE_STRING) +class TestGErrorOut(unittest.TestCase): + # See https://bugzilla.gnome.org/show_bug.cgi?id=666098 + def test_gerror_out(self): + error, debug = GIMarshallingTests.gerror_out() - def test_param_spec_out(self): - obj = GIMarshallingTests.param_spec_out() - self.assertEqual(obj.name, 'test-param') - self.assertEqual(obj.nick, 'test') - self.assertEqual(obj.value_type, GObject.TYPE_STRING) + self.assertIsInstance(error, GObject.GError) + self.assertEqual(error.domain, GIMarshallingTests.CONSTANT_GERROR_DOMAIN) + self.assertEqual(error.code, GIMarshallingTests.CONSTANT_GERROR_CODE) + self.assertEqual(error.message, GIMarshallingTests.CONSTANT_GERROR_MESSAGE) + self.assertEqual(debug, GIMarshallingTests.CONSTANT_GERROR_DEBUG_MESSAGE) + + +class TestGErrorOutTransferNone(unittest.TestCase): + # See https://bugzilla.gnome.org/show_bug.cgi?id=666098 + def test_gerror_out_transfer_none(self): + error, debug = GIMarshallingTests.gerror_out_transfer_none() + + self.assertIsInstance(error, GObject.GError) + self.assertEqual(error.domain, GIMarshallingTests.CONSTANT_GERROR_DOMAIN) + self.assertEqual(error.code, GIMarshallingTests.CONSTANT_GERROR_CODE) + self.assertEqual(error.message, GIMarshallingTests.CONSTANT_GERROR_MESSAGE) + self.assertEqual(GIMarshallingTests.CONSTANT_GERROR_DEBUG_MESSAGE, debug) + + +class TestGErrorReturn(unittest.TestCase): + # See https://bugzilla.gnome.org/show_bug.cgi?id=666098 + def test_return_gerror(self): + error = GIMarshallingTests.gerror_return() + + self.assertIsInstance(error, GObject.GError) + self.assertEqual(error.domain, GIMarshallingTests.CONSTANT_GERROR_DOMAIN) + self.assertEqual(error.code, GIMarshallingTests.CONSTANT_GERROR_CODE) + self.assertEqual(error.message, GIMarshallingTests.CONSTANT_GERROR_MESSAGE) class TestKeywordArgs(unittest.TestCase): @@ -2876,29 +1945,29 @@ class TestKeywordArgs(unittest.TestCase): def test_type_errors(self): # test too few args - self.assertRaisesMessage(TypeError, "GIMarshallingTests.int_three_in_three_out() takes exactly 3 arguments (0 given)", + self.assertRaisesMessage(TypeError, "int_three_in_three_out() takes exactly 3 arguments (0 given)", GIMarshallingTests.int_three_in_three_out) - self.assertRaisesMessage(TypeError, "GIMarshallingTests.int_three_in_three_out() takes exactly 3 arguments (1 given)", + self.assertRaisesMessage(TypeError, "int_three_in_three_out() takes exactly 3 arguments (1 given)", GIMarshallingTests.int_three_in_three_out, 1) - self.assertRaisesMessage(TypeError, "GIMarshallingTests.int_three_in_three_out() takes exactly 3 arguments (0 given)", + self.assertRaisesMessage(TypeError, "int_three_in_three_out() takes exactly 3 arguments (0 given)", GIMarshallingTests.int_three_in_three_out, *()) - self.assertRaisesMessage(TypeError, "GIMarshallingTests.int_three_in_three_out() takes exactly 3 arguments (0 given)", + self.assertRaisesMessage(TypeError, "int_three_in_three_out() takes exactly 3 arguments (0 given)", GIMarshallingTests.int_three_in_three_out, *(), **{}) - self.assertRaisesMessage(TypeError, "GIMarshallingTests.int_three_in_three_out() takes exactly 3 non-keyword arguments (0 given)", + self.assertRaisesMessage(TypeError, "int_three_in_three_out() takes exactly 3 non-keyword arguments (0 given)", GIMarshallingTests.int_three_in_three_out, *(), **{'c': 4}) # test too many args - self.assertRaisesMessage(TypeError, "GIMarshallingTests.int_three_in_three_out() takes exactly 3 arguments (4 given)", + self.assertRaisesMessage(TypeError, "int_three_in_three_out() takes exactly 3 arguments (4 given)", GIMarshallingTests.int_three_in_three_out, *(1, 2, 3, 4)) - self.assertRaisesMessage(TypeError, "GIMarshallingTests.int_three_in_three_out() takes exactly 3 non-keyword arguments (4 given)", + self.assertRaisesMessage(TypeError, "int_three_in_three_out() takes exactly 3 non-keyword arguments (4 given)", GIMarshallingTests.int_three_in_three_out, *(1, 2, 3, 4), c=6) # test too many keyword args - self.assertRaisesMessage(TypeError, "GIMarshallingTests.int_three_in_three_out() got multiple values for keyword argument 'a'", + self.assertRaisesMessage(TypeError, "int_three_in_three_out() got multiple values for keyword argument 'a'", GIMarshallingTests.int_three_in_three_out, 1, 2, 3, **{'a': 4, 'b': 5}) - self.assertRaisesMessage(TypeError, "GIMarshallingTests.int_three_in_three_out() got an unexpected keyword argument 'd'", + self.assertRaisesMessage(TypeError, "int_three_in_three_out() got an unexpected keyword argument 'd'", GIMarshallingTests.int_three_in_three_out, d=4) - self.assertRaisesMessage(TypeError, "GIMarshallingTests.int_three_in_three_out() got an unexpected keyword argument 'e'", + self.assertRaisesMessage(TypeError, "int_three_in_three_out() got an unexpected keyword argument 'e'", GIMarshallingTests.int_three_in_three_out, **{'e': 2}) def test_kwargs_are_not_modified(self): @@ -2907,283 +1976,70 @@ class TestKeywordArgs(unittest.TestCase): GIMarshallingTests.int_three_in_three_out(1, c=4, **d) self.assertEqual(d, d2) - @unittest.skipUnless(hasattr(GIMarshallingTests, 'int_one_in_utf8_two_in_one_allows_none'), - 'Requires newer GIMarshallingTests') - def test_allow_none_as_default(self): - GIMarshallingTests.int_two_in_utf8_two_in_with_allow_none(1, 2, '3', '4') - GIMarshallingTests.int_two_in_utf8_two_in_with_allow_none(1, 2, '3') - GIMarshallingTests.int_two_in_utf8_two_in_with_allow_none(1, 2) - GIMarshallingTests.int_two_in_utf8_two_in_with_allow_none(1, 2, d='4') - - GIMarshallingTests.array_in_utf8_two_in_out_of_order('1', [-1, 0, 1, 2]) - GIMarshallingTests.array_in_utf8_two_in_out_of_order('1', [-1, 0, 1, 2], '2') - self.assertRaises(TypeError, - GIMarshallingTests.array_in_utf8_two_in_out_of_order, - [-1, 0, 1, 2], a='1') - self.assertRaises(TypeError, - GIMarshallingTests.array_in_utf8_two_in_out_of_order, - [-1, 0, 1, 2]) - - GIMarshallingTests.array_in_utf8_two_in([-1, 0, 1, 2], '1', '2') - GIMarshallingTests.array_in_utf8_two_in([-1, 0, 1, 2], '1') - GIMarshallingTests.array_in_utf8_two_in([-1, 0, 1, 2]) - GIMarshallingTests.array_in_utf8_two_in([-1, 0, 1, 2], b='2') - - GIMarshallingTests.int_one_in_utf8_two_in_one_allows_none(1, '2', '3') - self.assertRaises(TypeError, - GIMarshallingTests.int_one_in_utf8_two_in_one_allows_none, - 1, '3') - self.assertRaises(TypeError, - GIMarshallingTests.int_one_in_utf8_two_in_one_allows_none, - 1, c='3') - - -class TestKeywords(unittest.TestCase): - def test_method(self): - # g_variant_print() - v = GLib.Variant('i', 1) - self.assertEqual(v.print_(False), '1') - - def test_function(self): - # g_thread_yield() - self.assertEqual(GLib.Thread.yield_(), None) - - def test_struct_method(self): - # g_timer_continue() - # we cannot currently instantiate GLib.Timer objects, so just ensure - # the method exists - self.assertTrue(callable(GLib.Timer.continue_)) - - def test_uppercase(self): - self.assertEqual(GLib.IOCondition.IN.value_nicks, ['in']) - - -class TestModule(unittest.TestCase): - def test_path(self): - self.assertTrue(GIMarshallingTests.__path__.endswith('GIMarshallingTests-1.0.typelib'), - GIMarshallingTests.__path__) - - def test_str(self): - self.assertTrue("'GIMarshallingTests' from '" in str(GIMarshallingTests), - str(GIMarshallingTests)) - - def test_dir(self): - _dir = dir(GIMarshallingTests) - self.assertGreater(len(_dir), 10) - - self.assertTrue('SimpleStruct' in _dir) - self.assertTrue('Interface2' in _dir) - self.assertTrue('CONSTANT_GERROR_CODE' in _dir) - self.assertTrue('array_zero_terminated_inout' in _dir) - - # assert that dir() does not contain garbage - for item_name in _dir: - item = getattr(GIMarshallingTests, item_name) - self.assertTrue(hasattr(item, '__class__')) - - def test_help(self): - orig_stdout = sys.stdout - try: - if sys.version_info < (3, 0): - sys.stdout = BytesIO() - else: - sys.stdout = StringIO() - help(GIMarshallingTests) - output = sys.stdout.getvalue() - finally: - sys.stdout = orig_stdout - - self.assertTrue('SimpleStruct' in output, output) - self.assertTrue('Interface2' in output, output) - self.assertTrue('method_array_inout' in output, output) - - -class TestProjectVersion(unittest.TestCase): - def test_version_str(self): - self.assertGreater(gi.__version__, "3.") - - def test_version_info(self): - self.assertEqual(len(gi.version_info), 3) - self.assertGreaterEqual(gi.version_info, (3, 3, 5)) - - def test_check_version(self): - self.assertRaises(ValueError, gi.check_version, (99, 0, 0)) - self.assertRaises(ValueError, gi.check_version, "99.0.0") - gi.check_version((3, 3, 5)) - gi.check_version("3.3.5") - - -class TestGIWarning(unittest.TestCase): - - def test_warning(self): - ignored_by_default = (DeprecationWarning, PendingDeprecationWarning, - ImportWarning) - - with warnings.catch_warnings(record=True) as warn: - warnings.simplefilter('always') - warnings.warn("test", PyGIWarning) - self.assertTrue(issubclass(warn[0].category, Warning)) - # We don't want PyGIWarning get ignored by default - self.assertFalse(issubclass(warn[0].category, ignored_by_default)) - - -class TestDeprecation(unittest.TestCase): - def test_method(self): - d = GLib.Date.new() - with warnings.catch_warnings(record=True) as warn: - warnings.simplefilter('always') - d.set_time(1) - self.assertTrue(issubclass(warn[0].category, DeprecationWarning)) - self.assertEqual(str(warn[0].message), "GLib.Date.set_time is deprecated") - - def test_function(self): - with warnings.catch_warnings(record=True) as warn: - warnings.simplefilter('always') - GLib.strcasecmp("foo", "bar") - self.assertTrue(issubclass(warn[0].category, DeprecationWarning)) - self.assertEqual(str(warn[0].message), "GLib.strcasecmp is deprecated") - - def test_deprecated_attribute_compat(self): - # test if the deprecation descriptor behaves like an instance attribute - - # save the descriptor - desc = type(GLib).__dict__["IO_STATUS_ERROR"] - - # the descriptor raises AttributeError for itself - self.assertFalse(hasattr(type(GLib), "IO_STATUS_ERROR")) - - with warnings.catch_warnings(): - warnings.simplefilter('ignore', PyGIDeprecationWarning) - self.assertTrue(hasattr(GLib, "IO_STATUS_ERROR")) - try: - # check if replacing works - GLib.IO_STATUS_ERROR = "foo" - self.assertEqual(GLib.IO_STATUS_ERROR, "foo") - finally: - # restore descriptor - try: - del GLib.IO_STATUS_ERROR - except AttributeError: - pass - setattr(type(GLib), "IO_STATUS_ERROR", desc) +class TestPropertiesObject(unittest.TestCase): - try: - # check if deleting works - del GLib.IO_STATUS_ERROR - self.assertFalse(hasattr(GLib, "IO_STATUS_ERROR")) - finally: - # restore descriptor - try: - del GLib.IO_STATUS_ERROR - except AttributeError: - pass - setattr(type(GLib), "IO_STATUS_ERROR", desc) - - def test_deprecated_attribute_warning(self): - with warnings.catch_warnings(record=True) as warn: - warnings.simplefilter('always') - self.assertEqual(GLib.IO_STATUS_ERROR, GLib.IOStatus.ERROR) - GLib.IO_STATUS_ERROR - GLib.IO_STATUS_ERROR - self.assertEqual(len(warn), 3) - self.assertTrue( - issubclass(warn[0].category, PyGIDeprecationWarning)) - self.assertRegexpMatches( - str(warn[0].message), - ".*GLib.IO_STATUS_ERROR.*GLib.IOStatus.ERROR.*") - - def test_deprecated_attribute_warning_coverage(self): - with warnings.catch_warnings(record=True) as warn: - warnings.simplefilter('always') - GObject.markup_escape_text - GObject.PRIORITY_DEFAULT - GObject.GError - GObject.PARAM_CONSTRUCT - GObject.SIGNAL_ACTION - GObject.property - GObject.IO_STATUS_ERROR - GObject.G_MAXUINT64 - GLib.IO_STATUS_ERROR - GLib.SPAWN_SEARCH_PATH - GLib.OPTION_FLAG_HIDDEN - GLib.IO_FLAG_IS_WRITEABLE - GLib.IO_FLAG_NONBLOCK - GLib.USER_DIRECTORY_DESKTOP - GLib.OPTION_ERROR_BAD_VALUE - GLib.glib_version - GLib.pyglib_version - self.assertEqual(len(warn), 17) - - def test_deprecated_init_no_keywords(self): - def init(self, **kwargs): - self.assertDictEqual(kwargs, {'a': 1, 'b': 2, 'c': 3}) - - fn = gi.overrides.deprecated_init(init, arg_names=('a', 'b', 'c')) - with warnings.catch_warnings(record=True) as warn: - warnings.simplefilter('always') - fn(self, 1, 2, 3) - self.assertEqual(len(warn), 1) - self.assertTrue(issubclass(warn[0].category, PyGIDeprecationWarning)) - self.assertRegexpMatches(str(warn[0].message), - '.*keyword.*a, b, c.*') - - def test_deprecated_init_no_keywords_out_of_order(self): - def init(self, **kwargs): - self.assertDictEqual(kwargs, {'a': 1, 'b': 2, 'c': 3}) - - fn = gi.overrides.deprecated_init(init, arg_names=('b', 'a', 'c')) - with warnings.catch_warnings(record=True) as warn: - warnings.simplefilter('always') - fn(self, 2, 1, 3) - self.assertEqual(len(warn), 1) - self.assertTrue(issubclass(warn[0].category, PyGIDeprecationWarning)) - self.assertRegexpMatches(str(warn[0].message), - '.*keyword.*b, a, c.*') - - def test_deprecated_init_ignored_keyword(self): - def init(self, **kwargs): - self.assertDictEqual(kwargs, {'a': 1, 'c': 3}) - - fn = gi.overrides.deprecated_init(init, - arg_names=('a', 'b', 'c'), - ignore=('b',)) - with warnings.catch_warnings(record=True) as warn: - warnings.simplefilter('always') - fn(self, 1, 2, 3) - self.assertEqual(len(warn), 1) - self.assertTrue(issubclass(warn[0].category, PyGIDeprecationWarning)) - self.assertRegexpMatches(str(warn[0].message), - '.*keyword.*a, b, c.*') - - def test_deprecated_init_with_aliases(self): - def init(self, **kwargs): - self.assertDictEqual(kwargs, {'a': 1, 'b': 2, 'c': 3}) - - fn = gi.overrides.deprecated_init(init, - arg_names=('a', 'b', 'c'), - deprecated_aliases={'b': 'bb', 'c': 'cc'}) - with warnings.catch_warnings(record=True) as warn: - warnings.simplefilter('always') - - fn(self, a=1, bb=2, cc=3) - self.assertEqual(len(warn), 1) - self.assertTrue(issubclass(warn[0].category, PyGIDeprecationWarning)) - self.assertRegexpMatches(str(warn[0].message), - '.*keyword.*"bb, cc".*deprecated.*"b, c" respectively') - - def test_deprecated_init_with_defaults(self): - def init(self, **kwargs): - self.assertDictEqual(kwargs, {'a': 1, 'b': 2, 'c': 3}) - - fn = gi.overrides.deprecated_init(init, - arg_names=('a', 'b', 'c'), - deprecated_defaults={'b': 2, 'c': 3}) - with warnings.catch_warnings(record=True) as warn: - warnings.simplefilter('always') - fn(self, a=1) - self.assertEqual(len(warn), 1) - self.assertTrue(issubclass(warn[0].category, PyGIDeprecationWarning)) - self.assertRegexpMatches(str(warn[0].message), - '.*relying on deprecated non-standard defaults.*' - 'explicitly use: b=2, c=3') + def setUp(self): + self.obj = GIMarshallingTests.PropertiesObject() + + def test_boolean(self): + self.assertEqual(self.obj.props.some_boolean, False) + self.obj.props.some_boolean = True + self.assertEqual(self.obj.props.some_boolean, True) + + @unittest.expectedFailure + def test_char(self): + # gobject-introspection thinks it has a guint8 type tag, which is + # wrong; this will raise an assertion critical which we need to ignore + old_mask = GLib.log_set_always_fatal( + GLib.LogLevelFlags.LEVEL_WARNING | GLib.LogLevelFlags.LEVEL_ERROR) + self.assertEqual(self.obj.props.some_char, 0) + self.obj.props.some_char = GObject.G_MAXINT8 + self.assertEqual(self.obj.props.some_char, GObject.G_MAXINT8) + + GLib.log_set_always_fatal(old_mask) + + def test_uchar(self): + self.assertEqual(self.obj.props.some_uchar, 0) + self.obj.props.some_uchar = GObject.G_MAXUINT8 + self.assertEqual(self.obj.props.some_uchar, GObject.G_MAXUINT8) + + def test_int(self): + self.assertEqual(self.obj.props.some_int, 0) + self.obj.props.some_int = GObject.G_MAXINT + self.assertEqual(self.obj.props.some_int, GObject.G_MAXINT) + + def test_uint(self): + self.assertEqual(self.obj.props.some_uint, 0) + self.obj.props.some_uint = GObject.G_MAXUINT + self.assertEqual(self.obj.props.some_uint, GObject.G_MAXUINT) + + def test_long(self): + self.assertEqual(self.obj.props.some_long, 0) + self.obj.props.some_long = GObject.G_MAXLONG + self.assertEqual(self.obj.props.some_long, GObject.G_MAXLONG) + + def test_ulong(self): + self.assertEqual(self.obj.props.some_ulong, 0) + self.obj.props.some_ulong = GObject.G_MAXULONG + self.assertEqual(self.obj.props.some_ulong, GObject.G_MAXULONG) + + def test_int64(self): + self.assertEqual(self.obj.props.some_int64, 0) + self.obj.props.some_int64 = GObject.G_MAXINT64 + self.assertEqual(self.obj.props.some_int64, GObject.G_MAXINT64) + + def test_uint64(self): + self.assertEqual(self.obj.props.some_uint64, 0) + self.obj.props.some_uint64 = GObject.G_MAXUINT64 + self.assertEqual(self.obj.props.some_uint64, GObject.G_MAXUINT64) + + def test_float(self): + self.assertEqual(self.obj.props.some_float, 0) + self.obj.props.some_float = GObject.G_MAXFLOAT + self.assertEqual(self.obj.props.some_float, GObject.G_MAXFLOAT) + + def test_double(self): + self.assertEqual(self.obj.props.some_double, 0) + self.obj.props.some_double = GObject.G_MAXDOUBLE + self.assertEqual(self.obj.props.some_double, GObject.G_MAXDOUBLE) diff --git a/tests/test_gio.py b/tests/test_gio.py deleted file mode 100644 index c7239ce..0000000 --- a/tests/test_gio.py +++ /dev/null @@ -1,314 +0,0 @@ -# -*- Mode: Python; py-indent-offset: 4 -*- -# vim: tabstop=4 shiftwidth=4 expandtab - -import os -import unittest -import warnings - -import gi.overrides -from gi import PyGIWarning -from gi.repository import GLib, Gio - -from helper import ignore_gi_deprecation_warnings - - -class TestGio(unittest.TestCase): - def test_file_enumerator(self): - self.assertEqual(Gio.FileEnumerator, gi.overrides.Gio.FileEnumerator) - f = Gio.file_new_for_path("./") - - iter_info = [] - for info in f.enumerate_children("standard::*", 0, None): - iter_info.append(info.get_name()) - - next_info = [] - enumerator = f.enumerate_children("standard::*", 0, None) - while True: - info = enumerator.next_file(None) - if info is None: - break - next_info.append(info.get_name()) - - self.assertEqual(iter_info, next_info) - - def test_menu_item(self): - menu = Gio.Menu() - item = Gio.MenuItem() - item.set_attribute([("label", "s", "Test"), - ("action", "s", "app.test")]) - menu.append_item(item) - value = menu.get_item_attribute_value(0, "label", GLib.VariantType.new("s")) - self.assertEqual("Test", value.unpack()) - value = menu.get_item_attribute_value(0, "action", GLib.VariantType.new("s")) - self.assertEqual("app.test", value.unpack()) - - def test_volume_monitor_warning(self): - with warnings.catch_warnings(record=True) as warn: - warnings.simplefilter('always') - Gio.VolumeMonitor() - self.assertEqual(len(warn), 1) - self.assertTrue(issubclass(warn[0].category, PyGIWarning)) - self.assertRegexpMatches(str(warn[0].message), - '.*Gio\\.VolumeMonitor\\.get\\(\\).*') - - -class TestGSettings(unittest.TestCase): - def setUp(self): - self.settings = Gio.Settings.new('org.gnome.test') - # we change the values in the tests, so set them to predictable start - # value - self.settings.reset('test-string') - self.settings.reset('test-array') - self.settings.reset('test-boolean') - self.settings.reset('test-enum') - - def test_native(self): - self.assertTrue('test-array' in self.settings.list_keys()) - - # get various types - v = self.settings.get_value('test-boolean') - self.assertEqual(v.get_boolean(), True) - self.assertEqual(self.settings.get_boolean('test-boolean'), True) - - v = self.settings.get_value('test-string') - self.assertEqual(v.get_string(), 'Hello') - self.assertEqual(self.settings.get_string('test-string'), 'Hello') - - v = self.settings.get_value('test-array') - self.assertEqual(v.unpack(), [1, 2]) - - v = self.settings.get_value('test-tuple') - self.assertEqual(v.unpack(), (1, 2)) - - # set a value - self.settings.set_string('test-string', 'World') - self.assertEqual(self.settings.get_string('test-string'), 'World') - - self.settings.set_value('test-string', GLib.Variant('s', 'Goodbye')) - self.assertEqual(self.settings.get_string('test-string'), 'Goodbye') - - def test_constructor(self): - # default constructor uses path from schema - self.assertEqual(self.settings.get_property('path'), '/tests/') - - # optional constructor arguments - with_path = Gio.Settings.new_with_path('org.gnome.nopathtest', '/mypath/') - self.assertEqual(with_path.get_property('path'), '/mypath/') - self.assertEqual(with_path['np-int'], 42) - - def test_dictionary_api(self): - self.assertEqual(len(self.settings), 5) - self.assertTrue('test-array' in self.settings) - self.assertTrue('test-array' in self.settings.keys()) - self.assertFalse('nonexisting' in self.settings) - self.assertFalse(4 in self.settings) - self.assertEqual(bool(self.settings), True) - - def test_get(self): - self.assertEqual(self.settings['test-boolean'], True) - self.assertEqual(self.settings['test-string'], 'Hello') - self.assertEqual(self.settings['test-enum'], 'banana') - self.assertEqual(self.settings['test-array'], [1, 2]) - self.assertEqual(self.settings['test-tuple'], (1, 2)) - - self.assertRaises(KeyError, self.settings.__getitem__, 'unknown') - self.assertRaises(KeyError, self.settings.__getitem__, 2) - - def test_set(self): - self.settings['test-boolean'] = False - self.assertEqual(self.settings['test-boolean'], False) - self.settings['test-string'] = 'Goodbye' - self.assertEqual(self.settings['test-string'], 'Goodbye') - self.settings['test-array'] = [3, 4, 5] - self.assertEqual(self.settings['test-array'], [3, 4, 5]) - self.settings['test-enum'] = 'pear' - self.assertEqual(self.settings['test-enum'], 'pear') - - self.assertRaises(TypeError, self.settings.__setitem__, 'test-string', 1) - self.assertRaises(ValueError, self.settings.__setitem__, 'test-enum', 'plum') - self.assertRaises(KeyError, self.settings.__setitem__, 'unknown', 'moo') - - def test_empty(self): - empty = Gio.Settings.new_with_path('org.gnome.empty', '/tests/') - self.assertEqual(len(empty), 0) - self.assertEqual(bool(empty), True) - self.assertEqual(empty.keys(), []) - - @ignore_gi_deprecation_warnings - def test_change_event(self): - changed_log = [] - change_event_log = [] - - def on_changed(settings, key): - changed_log.append((settings, key)) - - def on_change_event(settings, keys, n_keys): - change_event_log.append((settings, keys, n_keys)) - - self.settings.connect('changed', on_changed) - self.settings.connect('change-event', on_change_event) - self.settings['test-string'] = 'Moo' - self.assertEqual(changed_log, [(self.settings, 'test-string')]) - self.assertEqual(change_event_log, [(self.settings, - [GLib.quark_from_static_string('test-string')], - 1)]) - - -@unittest.skipIf(os.name == "nt", "FIXME") -class TestGFile(unittest.TestCase): - def setUp(self): - self.file, self.io_stream = Gio.File.new_tmp('TestGFile.XXXXXX') - - def tearDown(self): - try: - self.file.delete(None) - # test_delete and test_delete_async already remove it - except GLib.GError: - pass - - def test_replace_contents(self): - content = b'hello\0world\x7F!' - succ, etag = self.file.replace_contents(content, None, False, - Gio.FileCreateFlags.NONE, None) - new_succ, new_content, new_etag = self.file.load_contents(None) - - self.assertTrue(succ) - self.assertTrue(new_succ) - self.assertEqual(etag, new_etag) - self.assertEqual(content, new_content) - - # https://bugzilla.gnome.org/show_bug.cgi?id=690525 - def disabled_test_replace_contents_async(self): - content = b''.join(bytes(chr(i), 'utf-8') for i in range(128)) - - def callback(f, result, d): - # Quit so in case of failed assertations loop doesn't keep running. - main_loop.quit() - succ, etag = self.file.replace_contents_finish(result) - new_succ, new_content, new_etag = self.file.load_contents(None) - d['succ'], d['etag'] = self.file.replace_contents_finish(result) - load = self.file.load_contents(None) - d['new_succ'], d['new_content'], d['new_etag'] = load - - data = {} - self.file.replace_contents_async(content, None, False, - Gio.FileCreateFlags.NONE, None, - callback, data) - main_loop = GLib.MainLoop() - main_loop.run() - self.assertTrue(data['succ']) - self.assertTrue(data['new_succ']) - self.assertEqual(data['etag'], data['new_etag']) - self.assertEqual(content, data['new_content']) - - def test_tmp_exists(self): - # A simple test to check if Gio.File.new_tmp is working correctly. - self.assertTrue(self.file.query_exists(None)) - - def test_delete(self): - self.file.delete(None) - self.assertFalse(self.file.query_exists(None)) - - def test_delete_async(self): - def callback(f, result, data): - main_loop.quit() - - self.file.delete_async(0, None, callback, None) - main_loop = GLib.MainLoop() - main_loop.run() - self.assertFalse(self.file.query_exists(None)) - - -@unittest.skipIf(os.name == "nt", "crashes on Windows") -class TestGApplication(unittest.TestCase): - def test_command_line(self): - class App(Gio.Application): - args = None - - def __init__(self): - super(App, self).__init__(flags=Gio.ApplicationFlags.HANDLES_COMMAND_LINE) - - def do_command_line(self, cmdline): - self.args = cmdline.get_arguments() - return 42 - - app = App() - res = app.run(['spam', 'eggs']) - - self.assertEqual(res, 42) - self.assertSequenceEqual(app.args, ['spam', 'eggs']) - - def test_local_command_line(self): - class App(Gio.Application): - local_args = None - - def __init__(self): - super(App, self).__init__(flags=Gio.ApplicationFlags.HANDLES_COMMAND_LINE) - - def do_local_command_line(self, args): - self.local_args = args[:] # copy - args.remove('eggs') - - # True skips do_command_line being called. - return True, args, 42 - - app = App() - res = app.run(['spam', 'eggs']) - - self.assertEqual(res, 42) - self.assertSequenceEqual(app.local_args, ['spam', 'eggs']) - - def test_local_and_remote_command_line(self): - class App(Gio.Application): - args = None - local_args = None - - def __init__(self): - super(App, self).__init__(flags=Gio.ApplicationFlags.HANDLES_COMMAND_LINE) - - def do_command_line(self, cmdline): - self.args = cmdline.get_arguments() - return 42 - - def do_local_command_line(self, args): - self.local_args = args[:] # copy - args.remove('eggs') - - # False causes do_command_line to be called with args. - return False, args, 0 - - app = App() - res = app.run(['spam', 'eggs']) - - self.assertEqual(res, 42) - self.assertSequenceEqual(app.args, ['spam']) - self.assertSequenceEqual(app.local_args, ['spam', 'eggs']) - - @unittest.skipUnless(hasattr(Gio.Application, 'add_main_option'), - 'Requires newer version of GLib') - def test_add_main_option(self): - stored_options = [] - - def on_handle_local_options(app, options): - stored_options.append(options) - return 0 # Return 0 if options have been handled - - def on_activate(app): - pass - - app = Gio.Application() - app.add_main_option(long_name='string', - short_name=b's', - flags=0, - arg=GLib.OptionArg.STRING, - description='some string') - - app.connect('activate', on_activate) - app.connect('handle-local-options', on_handle_local_options) - app.run(['app', '-s', 'test string']) - - self.assertEqual(len(stored_options), 1) - options = stored_options[0] - self.assertTrue(options.contains('string')) - self.assertEqual(options.lookup_value('string').unpack(), - 'test string') diff --git a/tests/test_glib.py b/tests/test_glib.py deleted file mode 100644 index 78366a9..0000000 --- a/tests/test_glib.py +++ /dev/null @@ -1,267 +0,0 @@ -# -*- Mode: Python -*- -# encoding: UTF-8 - -import os -import sys -import unittest -import os.path -import warnings -import subprocess - -from gi.repository import GLib -from gi import PyGIDeprecationWarning - - -class TestGLib(unittest.TestCase): - - @unittest.skipIf(os.name == "nt", "no bash on Windows") - def test_find_program_in_path(self): - bash_path = GLib.find_program_in_path('bash') - self.assertTrue(bash_path.endswith(os.path.sep + 'bash')) - self.assertTrue(os.path.exists(bash_path)) - - self.assertEqual(GLib.find_program_in_path('non existing'), None) - - def test_markup_escape_text(self): - self.assertEqual(GLib.markup_escape_text(u'a&bä'), 'a&bä') - self.assertEqual(GLib.markup_escape_text(b'a&b\x05'), 'a&b') - - # with explicit length argument - self.assertEqual(GLib.markup_escape_text(b'a\x05\x01\x02', 2), 'a') - - def test_progname(self): - GLib.set_prgname('moo') - self.assertEqual(GLib.get_prgname(), 'moo') - - def test_appname(self): - GLib.set_application_name('moo') - self.assertEqual(GLib.get_application_name(), 'moo') - - def test_xdg_dirs(self): - d = GLib.get_user_data_dir() - self.assertTrue(os.path.sep in d, d) - d = GLib.get_user_special_dir(GLib.UserDirectory.DIRECTORY_DESKTOP) - self.assertTrue(os.path.sep in d, d) - with warnings.catch_warnings(): - warnings.simplefilter('ignore', PyGIDeprecationWarning) - - # also works with backwards compatible enum names - self.assertEqual(GLib.get_user_special_dir(GLib.UserDirectory.DIRECTORY_MUSIC), - GLib.get_user_special_dir(GLib.USER_DIRECTORY_MUSIC)) - - for d in GLib.get_system_config_dirs(): - self.assertTrue(os.path.sep in d, d) - for d in GLib.get_system_data_dirs(): - self.assertTrue(isinstance(d, str), d) - - def test_main_depth(self): - self.assertEqual(GLib.main_depth(), 0) - - def test_filenames(self): - self.assertEqual(GLib.filename_display_name('foo'), 'foo') - self.assertEqual(GLib.filename_display_basename('bar/foo'), 'foo') - - # this is locale dependent, so we cannot completely verify the result - res = GLib.filename_from_utf8(u'aäb') - self.assertTrue(isinstance(res, bytes)) - self.assertGreaterEqual(len(res), 3) - - # with explicit length argument - self.assertEqual(GLib.filename_from_utf8(u'aäb', 1), b'a') - - def test_uri_extract(self): - res = GLib.uri_list_extract_uris('''# some comment -http://example.com -https://my.org/q?x=1&y=2 - http://gnome.org/new''') - self.assertEqual(res, ['http://example.com', - 'https://my.org/q?x=1&y=2', - 'http://gnome.org/new']) - - def test_current_time(self): - with warnings.catch_warnings(record=True) as warn: - warnings.simplefilter('always') - tm = GLib.get_current_time() - self.assertTrue(issubclass(warn[0].category, PyGIDeprecationWarning)) - - self.assertTrue(isinstance(tm, float)) - self.assertGreater(tm, 1350000000.0) - - @unittest.skipIf(sys.platform == "darwin", "fails on OSX") - def test_main_loop(self): - # note we do not test run() here, as we use this in countless other - # tests - ml = GLib.MainLoop() - self.assertFalse(ml.is_running()) - - context = ml.get_context() - self.assertEqual(context, GLib.MainContext.default()) - self.assertTrue(context.is_owner() in [True, False]) - self.assertTrue(context.pending() in [True, False]) - self.assertFalse(context.iteration(False)) - - def test_main_loop_with_context(self): - context = GLib.MainContext() - ml = GLib.MainLoop(context) - self.assertFalse(ml.is_running()) - self.assertEqual(ml.get_context(), context) - - def test_main_context(self): - # constructor - context = GLib.MainContext() - self.assertTrue(context.is_owner() in [True, False]) - self.assertFalse(context.pending()) - self.assertFalse(context.iteration(False)) - - # GLib API - context = GLib.MainContext.default() - self.assertTrue(context.is_owner() in [True, False]) - self.assertTrue(context.pending() in [True, False]) - self.assertTrue(context.iteration(False) in [True, False]) - - # backwards compatible API - context = GLib.main_context_default() - self.assertTrue(context.is_owner() in [True, False]) - self.assertTrue(context.pending() in [True, False]) - self.assertTrue(context.iteration(False) in [True, False]) - - @unittest.skipIf(os.name == "nt", "hangs") - def test_io_add_watch_no_data(self): - (r, w) = os.pipe() - call_data = [] - - def cb(fd, condition): - call_data.append((fd, condition, os.read(fd, 1))) - if len(call_data) == 2: - ml.quit() - return True - - # io_add_watch() takes an IOChannel, calling with an fd is deprecated - with warnings.catch_warnings(record=True) as warn: - warnings.simplefilter('always') - GLib.io_add_watch(r, GLib.IOCondition.IN, cb, - priority=GLib.PRIORITY_HIGH) - self.assertTrue(issubclass(warn[0].category, PyGIDeprecationWarning)) - - def write(): - os.write(w, b'a') - GLib.idle_add(lambda: os.write(w, b'b') and False) - - ml = GLib.MainLoop() - GLib.idle_add(write) - GLib.timeout_add(2000, ml.quit) - ml.run() - - self.assertEqual(call_data, [(r, GLib.IOCondition.IN, b'a'), - (r, GLib.IOCondition.IN, b'b')]) - - @unittest.skipIf(os.name == "nt", "hangs") - def test_io_add_watch_with_data(self): - (r, w) = os.pipe() - call_data = [] - - def cb(fd, condition, data): - call_data.append((fd, condition, os.read(fd, 1), data)) - if len(call_data) == 2: - ml.quit() - return True - - # io_add_watch() takes an IOChannel, calling with an fd is deprecated - with warnings.catch_warnings(record=True) as warn: - warnings.simplefilter('always') - GLib.io_add_watch(r, GLib.IOCondition.IN, cb, 'moo', - priority=GLib.PRIORITY_HIGH) - self.assertTrue(issubclass(warn[0].category, PyGIDeprecationWarning)) - - def write(): - os.write(w, b'a') - GLib.idle_add(lambda: os.write(w, b'b') and False) - - ml = GLib.MainLoop() - GLib.idle_add(write) - GLib.timeout_add(2000, ml.quit) - ml.run() - - self.assertEqual(call_data, [(r, GLib.IOCondition.IN, b'a', 'moo'), - (r, GLib.IOCondition.IN, b'b', 'moo')]) - - @unittest.skipIf(os.name == "nt", "hangs") - def test_io_add_watch_with_multiple_data(self): - (r, w) = os.pipe() - call_data = [] - - def cb(fd, condition, *user_data): - call_data.append((fd, condition, os.read(fd, 1), user_data)) - ml.quit() - return True - - # io_add_watch() takes an IOChannel, calling with an fd is deprecated - with warnings.catch_warnings(record=True) as warn: - warnings.simplefilter('always') - GLib.io_add_watch(r, GLib.IOCondition.IN, cb, 'moo', 'foo') - self.assertTrue(issubclass(warn[0].category, PyGIDeprecationWarning)) - - ml = GLib.MainLoop() - GLib.idle_add(lambda: os.write(w, b'a') and False) - GLib.timeout_add(2000, ml.quit) - ml.run() - - self.assertEqual(call_data, [(r, GLib.IOCondition.IN, b'a', ('moo', 'foo'))]) - - @unittest.skipIf(os.name == "nt", "no shell on Windows") - def test_io_add_watch_pyfile(self): - call_data = [] - - cmd = subprocess.Popen('echo hello; echo world', - shell=True, bufsize=0, stdout=subprocess.PIPE) - - def cb(file, condition): - call_data.append((file, condition, file.readline())) - if len(call_data) == 2: - # avoid having to wait for the full timeout - ml.quit() - return True - - # io_add_watch() takes an IOChannel, calling with a Python file is deprecated - with warnings.catch_warnings(record=True) as warn: - warnings.simplefilter('always') - GLib.io_add_watch(cmd.stdout, GLib.IOCondition.IN, cb) - self.assertTrue(issubclass(warn[0].category, PyGIDeprecationWarning)) - - ml = GLib.MainLoop() - GLib.timeout_add(2000, ml.quit) - ml.run() - - cmd.wait() - - self.assertEqual(call_data, [(cmd.stdout, GLib.IOCondition.IN, b'hello\n'), - (cmd.stdout, GLib.IOCondition.IN, b'world\n')]) - - def test_glib_version(self): - with warnings.catch_warnings(): - warnings.simplefilter('ignore', PyGIDeprecationWarning) - - (major, minor, micro) = GLib.glib_version - self.assertGreaterEqual(major, 2) - self.assertGreaterEqual(minor, 0) - self.assertGreaterEqual(micro, 0) - - def test_pyglib_version(self): - with warnings.catch_warnings(): - warnings.simplefilter('ignore', PyGIDeprecationWarning) - - (major, minor, micro) = GLib.pyglib_version - self.assertGreaterEqual(major, 3) - self.assertGreaterEqual(minor, 0) - self.assertGreaterEqual(micro, 0) - - def test_timezone_constructor(self): - timezone = GLib.TimeZone("+05:21") - self.assertEqual(timezone.get_offset(0), ((5 * 60) + 21) * 60) - - def test_source_attach_implicit_context(self): - context = GLib.MainContext.default() - source = GLib.Idle() - source_id = source.attach() - self.assertEqual(context, source.get_context()) - self.assertTrue(GLib.Source.remove(source_id)) diff --git a/tests/test_gobject.py b/tests/test_gobject.py index c380d72..5a4284e 100644 --- a/tests/test_gobject.py +++ b/tests/test_gobject.py @@ -1,101 +1,36 @@ # -*- Mode: Python -*- -import sys -import gc import unittest -import warnings - -from gi.repository import GObject, GLib -from gi import PyGIDeprecationWarning -from gi.module import get_introspection_module -from gi import _gi +from gi.repository import GObject +import sys import testhelper class TestGObjectAPI(unittest.TestCase): + def testGObjectModule(self): + obj = GObject.GObject() - def test_call_method_uninitialized_instance(self): - obj = GObject.Object.__new__(GObject.Object) - with self.assertRaisesRegex(RuntimeError, '.*is not initialized'): - obj.notify("foo") - - def test_gobject_inheritance(self): - # GObject.Object is a class hierarchy as follows: - # overrides.Object -> introspection.Object -> static.GObject - GIObjectModule = get_introspection_module('GObject') - self.assertTrue(issubclass(GObject.Object, GIObjectModule.Object)) - self.assertTrue(issubclass(GIObjectModule.Object, _gi.GObject)) - - self.assertEqual(_gi.GObject.__gtype__, GObject.TYPE_OBJECT) - self.assertEqual(GIObjectModule.Object.__gtype__, GObject.TYPE_OBJECT) - self.assertEqual(GObject.Object.__gtype__, GObject.TYPE_OBJECT) - - # The pytype wrapper should hold the outer most Object class from overrides. - self.assertEqual(GObject.TYPE_OBJECT.pytype, GObject.Object) - - def test_gobject_unsupported_overrides(self): - obj = GObject.Object() - - with self.assertRaisesRegex(RuntimeError, 'Data access methods are unsupported.*'): - obj.get_data() - - with self.assertRaisesRegex(RuntimeError, 'This method is currently unsupported.*'): - obj.force_floating() - - def test_compat_api(self): - with warnings.catch_warnings(record=True) as w: - warnings.simplefilter('always') - # GObject formerly exposed a lot of GLib's functions - self.assertEqual(GObject.markup_escape_text('foo'), 'foo') - - ml = GObject.MainLoop() - self.assertFalse(ml.is_running()) - - context = GObject.main_context_default() - self.assertTrue(context.pending() in [False, True]) - - context = GObject.MainContext() - self.assertFalse(context.pending()) - - self.assertTrue(issubclass(w[0].category, PyGIDeprecationWarning)) - self.assertTrue('GLib.markup_escape_text' in str(w[0]), str(w[0])) - - self.assertLess(GObject.PRIORITY_HIGH, GObject.PRIORITY_DEFAULT) - - def test_min_max_int(self): - with warnings.catch_warnings(): - warnings.simplefilter('ignore', PyGIDeprecationWarning) - - self.assertEqual(GObject.G_MAXINT16, 2 ** 15 - 1) - self.assertEqual(GObject.G_MININT16, -2 ** 15) - self.assertEqual(GObject.G_MAXUINT16, 2 ** 16 - 1) - - self.assertEqual(GObject.G_MAXINT32, 2 ** 31 - 1) - self.assertEqual(GObject.G_MININT32, -2 ** 31) - self.assertEqual(GObject.G_MAXUINT32, 2 ** 32 - 1) - - self.assertEqual(GObject.G_MAXINT64, 2 ** 63 - 1) - self.assertEqual(GObject.G_MININT64, -2 ** 63) - self.assertEqual(GObject.G_MAXUINT64, 2 ** 64 - 1) + self.assertEqual(obj.__module__, + 'gi._gobject._gobject') class TestReferenceCounting(unittest.TestCase): - def test_regular_object(self): + def testRegularObject(self): obj = GObject.GObject() self.assertEqual(obj.__grefcount__, 1) obj = GObject.new(GObject.GObject) self.assertEqual(obj.__grefcount__, 1) - def test_floating(self): + def testFloating(self): obj = testhelper.Floating() self.assertEqual(obj.__grefcount__, 1) obj = GObject.new(testhelper.Floating) self.assertEqual(obj.__grefcount__, 1) - def test_owned_by_library(self): + def testOwnedByLibrary(self): # Upon creation, the refcount of the object should be 2: # - someone already has a reference on the new object. # - the python wrapper should hold its own reference. @@ -108,7 +43,7 @@ class TestReferenceCounting(unittest.TestCase): obj.release() self.assertEqual(obj.__grefcount__, 1) - def test_owned_by_library_out_of_scope(self): + def testOwnedByLibraryOutOfScope(self): obj = testhelper.OwnedByLibrary() self.assertEqual(obj.__grefcount__, 2) @@ -126,7 +61,7 @@ class TestReferenceCounting(unittest.TestCase): obj.release() self.assertEqual(obj.__grefcount__, 1) - def test_owned_by_library_using_gobject_new(self): + def testOwnedByLibraryUsingGObjectNew(self): # Upon creation, the refcount of the object should be 2: # - someone already has a reference on the new object. # - the python wrapper should hold its own reference. @@ -139,7 +74,7 @@ class TestReferenceCounting(unittest.TestCase): obj.release() self.assertEqual(obj.__grefcount__, 1) - def test_owned_by_library_out_of_scope_using_gobject_new(self): + def testOwnedByLibraryOutOfScopeUsingGobjectNew(self): obj = GObject.new(testhelper.OwnedByLibrary) self.assertEqual(obj.__grefcount__, 2) @@ -157,7 +92,7 @@ class TestReferenceCounting(unittest.TestCase): obj.release() self.assertEqual(obj.__grefcount__, 1) - def test_floating_and_sunk(self): + def testFloatingAndSunk(self): # Upon creation, the refcount of the object should be 2: # - someone already has a reference on the new object. # - the python wrapper should hold its own reference. @@ -170,7 +105,7 @@ class TestReferenceCounting(unittest.TestCase): obj.release() self.assertEqual(obj.__grefcount__, 1) - def test_floating_and_sunk_out_of_scope(self): + def testFloatingAndSunkOutOfScope(self): obj = testhelper.FloatingAndSunk() self.assertEqual(obj.__grefcount__, 2) @@ -188,7 +123,7 @@ class TestReferenceCounting(unittest.TestCase): obj.release() self.assertEqual(obj.__grefcount__, 1) - def test_floating_and_sunk_using_gobject_new(self): + def testFloatingAndSunkUsingGObjectNew(self): # Upon creation, the refcount of the object should be 2: # - someone already has a reference on the new object. # - the python wrapper should hold its own reference. @@ -201,7 +136,7 @@ class TestReferenceCounting(unittest.TestCase): obj.release() self.assertEqual(obj.__grefcount__, 1) - def test_floating_and_sunk_out_of_scope_using_gobject_new(self): + def testFloatingAndSunkOutOfScopeUsingGObjectNew(self): obj = GObject.new(testhelper.FloatingAndSunk) self.assertEqual(obj.__grefcount__, 2) @@ -219,7 +154,7 @@ class TestReferenceCounting(unittest.TestCase): obj.release() self.assertEqual(obj.__grefcount__, 1) - def test_uninitialized_object(self): + def testUninitializedObject(self): class Obj(GObject.GObject): def __init__(self): x = self.__grefcount__ @@ -240,19 +175,19 @@ class TestPythonReferenceCounting(unittest.TestCase): # Newly created instances should alwayshave two references: one for # the GC, and one for the bound variable in the local scope. - def test_new_instance_has_two_refs(self): + def testNewInstanceHasTwoRefs(self): obj = GObject.GObject() self.assertEqual(sys.getrefcount(obj), 2) - def test_new_instance_has_two_refs_using_gobject_new(self): + def testNewInstanceHasTwoRefsUsingGObjectNew(self): obj = GObject.new(GObject.GObject) self.assertEqual(sys.getrefcount(obj), 2) - def test_new_subclass_instance_has_two_refs(self): + def testNewSubclassInstanceHasTwoRefs(self): obj = A() self.assertEqual(sys.getrefcount(obj), 2) - def test_new_subclass_instance_has_two_refs_using_gobject_new(self): + def testNewSubclassInstanceHasTwoRefsUsingGObjectNew(self): obj = GObject.new(A) self.assertEqual(sys.getrefcount(obj), 2) @@ -270,7 +205,7 @@ class TestContextManagers(unittest.TestCase): self.obj = self.ContextTestObject() self.handler = self.obj.connect('notify::prop', self.on_prop_set) - def test_freeze_notify_context(self): + def testFreezeNotifyContext(self): # Verify prop tracking list self.assertEqual(self.tracking, []) self.obj.props.prop = 1 @@ -279,28 +214,22 @@ class TestContextManagers(unittest.TestCase): self.assertEqual(self.tracking, [1, 2]) self.assertEqual(self.obj.__grefcount__, 1) - pyref_count = sys.getrefcount(self.obj) - - # Using the context manager the tracking list should not be affected. - # The GObject reference count should stay the same and the python - # object ref-count should go up. + # Using the context manager the tracking list should not be affected + # and the GObject reference count should go up. with self.obj.freeze_notify(): - self.assertEqual(self.obj.__grefcount__, 1) - self.assertEqual(sys.getrefcount(self.obj), pyref_count + 1) + self.assertEqual(self.obj.__grefcount__, 2) self.obj.props.prop = 3 self.assertEqual(self.obj.props.prop, 3) self.assertEqual(self.tracking, [1, 2]) # After the context manager, the prop should have been modified, - # the tracking list will be modified, and the python object ref + # the tracking list will be modified, and the GObject ref # count goes back down. - gc.collect() self.assertEqual(self.obj.props.prop, 3) self.assertEqual(self.tracking, [1, 2, 3]) self.assertEqual(self.obj.__grefcount__, 1) - self.assertEqual(sys.getrefcount(self.obj), pyref_count) - def test_handler_block_context(self): + def testHandlerBlockContext(self): # Verify prop tracking list self.assertEqual(self.tracking, []) self.obj.props.prop = 1 @@ -309,14 +238,10 @@ class TestContextManagers(unittest.TestCase): self.assertEqual(self.tracking, [1, 2]) self.assertEqual(self.obj.__grefcount__, 1) - pyref_count = sys.getrefcount(self.obj) - - # Using the context manager the tracking list should not be affected. - # The GObject reference count should stay the same and the python - # object ref-count should go up. + # Using the context manager the tracking list should not be affected + # and the GObject reference count should go up. with self.obj.handler_block(self.handler): - self.assertEqual(self.obj.__grefcount__, 1) - self.assertEqual(sys.getrefcount(self.obj), pyref_count + 1) + self.assertEqual(self.obj.__grefcount__, 2) self.obj.props.prop = 3 self.assertEqual(self.obj.props.prop, 3) self.assertEqual(self.tracking, [1, 2]) @@ -324,13 +249,11 @@ class TestContextManagers(unittest.TestCase): # After the context manager, the prop should have been modified # the tracking list should have stayed the same and the GObject ref # count goes back down. - gc.collect() self.assertEqual(self.obj.props.prop, 3) self.assertEqual(self.tracking, [1, 2]) self.assertEqual(self.obj.__grefcount__, 1) - self.assertEqual(sys.getrefcount(self.obj), pyref_count) - def test_freeze_notify_context_nested(self): + def testFreezeNotifyContextNested(self): self.assertEqual(self.tracking, []) with self.obj.freeze_notify(): self.obj.props.prop = 1 @@ -350,7 +273,7 @@ class TestContextManagers(unittest.TestCase): # and the last one sent. self.assertEqual(self.tracking, [3]) - def test_handler_block_context_nested(self): + def testHandlerBlockContextNested(self): self.assertEqual(self.tracking, []) with self.obj.handler_block(self.handler): self.obj.props.prop = 1 @@ -371,7 +294,7 @@ class TestContextManagers(unittest.TestCase): self.assertEqual(self.obj.props.prop, 3) self.assertEqual(self.tracking, []) - def test_freeze_notify_normal_usage_ref_counts(self): + def testFreezeNotifyNormalUsageRefCounts(self): # Ensure ref counts without using methods as context managers # maintain the same count. self.assertEqual(self.obj.__grefcount__, 1) @@ -380,14 +303,14 @@ class TestContextManagers(unittest.TestCase): self.obj.thaw_notify() self.assertEqual(self.obj.__grefcount__, 1) - def test_handler_block_normal_usage_ref_counts(self): + def testHandlerBlockNormalUsageRefCounts(self): self.assertEqual(self.obj.__grefcount__, 1) self.obj.handler_block(self.handler) self.assertEqual(self.obj.__grefcount__, 1) self.obj.handler_unblock(self.handler) self.assertEqual(self.obj.__grefcount__, 1) - def test_freeze_notify_context_error(self): + def testFreezeNotifyContextError(self): # Test an exception occurring within a freeze context exits the context try: with self.obj.freeze_notify(): @@ -405,7 +328,7 @@ class TestContextManagers(unittest.TestCase): self.obj.props.prop = 2 self.assertEqual(self.tracking, [1, 2]) - def test_handler_block_context_error(self): + def testHandlerBlockContextError(self): # Test an exception occurring within a handler block exits the context try: with self.obj.handler_block(self.handler): @@ -423,278 +346,5 @@ class TestContextManagers(unittest.TestCase): self.obj.props.prop = 2 self.assertEqual(self.tracking, [2]) - -@unittest.skipUnless(hasattr(GObject.Binding, 'unbind'), - 'Requires newer GLib which has g_binding_unbind') -class TestPropertyBindings(unittest.TestCase): - class TestObject(GObject.GObject): - int_prop = GObject.Property(default=0, type=int) - - def setUp(self): - self.source = self.TestObject() - self.target = self.TestObject() - - def test_default_binding(self): - binding = self.source.bind_property('int_prop', self.target, 'int_prop', - GObject.BindingFlags.DEFAULT) - binding = binding # PyFlakes - - # Test setting value on source gets pushed to target - self.source.int_prop = 1 - self.assertEqual(self.source.int_prop, 1) - self.assertEqual(self.target.int_prop, 1) - - # Test setting value on target does not change source - self.target.props.int_prop = 2 - self.assertEqual(self.source.int_prop, 1) - self.assertEqual(self.target.int_prop, 2) - - def test_bidirectional_binding(self): - binding = self.source.bind_property('int_prop', self.target, 'int_prop', - GObject.BindingFlags.BIDIRECTIONAL) - binding = binding # PyFlakes - - # Test setting value on source gets pushed to target - self.source.int_prop = 1 - self.assertEqual(self.source.int_prop, 1) - self.assertEqual(self.target.int_prop, 1) - - # Test setting value on target also changes source - self.target.props.int_prop = 2 - self.assertEqual(self.source.int_prop, 2) - self.assertEqual(self.target.int_prop, 2) - - def test_transform_to_only(self): - def transform_to(binding, value, user_data=None): - self.assertEqual(user_data, 'test-data') - return value * 2 - - binding = self.source.bind_property('int_prop', self.target, 'int_prop', - GObject.BindingFlags.DEFAULT, - transform_to, None, 'test-data') - binding = binding # PyFlakes - - self.source.int_prop = 1 - self.assertEqual(self.source.int_prop, 1) - self.assertEqual(self.target.int_prop, 2) - - self.target.props.int_prop = 1 - self.assertEqual(self.source.int_prop, 1) - self.assertEqual(self.target.int_prop, 1) - - def test_transform_from_only(self): - def transform_from(binding, value, user_data=None): - self.assertEqual(user_data, None) - return value * 2 - - binding = self.source.bind_property('int_prop', self.target, 'int_prop', - GObject.BindingFlags.BIDIRECTIONAL, - None, transform_from) - binding = binding # PyFlakes - - self.source.int_prop = 1 - self.assertEqual(self.source.int_prop, 1) - self.assertEqual(self.target.int_prop, 1) - - self.target.props.int_prop = 1 - self.assertEqual(self.source.int_prop, 2) - self.assertEqual(self.target.int_prop, 1) - - def test_transform_bidirectional(self): - test_data = object() - - def transform_to(binding, value, user_data=None): - self.assertEqual(user_data, test_data) - return value * 2 - - def transform_from(binding, value, user_data=None): - self.assertEqual(user_data, test_data) - return value // 2 - - test_data_ref_count = sys.getrefcount(test_data) - transform_to_ref_count = sys.getrefcount(transform_to) - transform_from_ref_count = sys.getrefcount(transform_from) - - # bidirectional bindings - binding = self.source.bind_property('int_prop', self.target, 'int_prop', - GObject.BindingFlags.BIDIRECTIONAL, - transform_to, transform_from, test_data) - binding = binding # PyFlakes - binding_ref_count = sys.getrefcount(binding) - binding_gref_count = binding.__grefcount__ - - self.source.int_prop = 1 - self.assertEqual(self.source.int_prop, 1) - self.assertEqual(self.target.int_prop, 2) - - self.target.props.int_prop = 4 - self.assertEqual(self.source.int_prop, 2) - self.assertEqual(self.target.int_prop, 4) - - self.assertEqual(sys.getrefcount(binding), binding_ref_count) - self.assertEqual(binding.__grefcount__, binding_gref_count) - - # test_data ref count increases by 2, once for each callback. - self.assertEqual(sys.getrefcount(test_data), test_data_ref_count + 2) - self.assertEqual(sys.getrefcount(transform_to), transform_to_ref_count + 1) - self.assertEqual(sys.getrefcount(transform_from), transform_from_ref_count + 1) - - # Unbind should clear out the binding and its transforms - binding.unbind() - - # Setting source or target should not change the other. - self.target.int_prop = 3 - self.source.int_prop = 5 - self.assertEqual(self.target.int_prop, 3) - self.assertEqual(self.source.int_prop, 5) - - self.assertEqual(sys.getrefcount(test_data), test_data_ref_count) - self.assertEqual(sys.getrefcount(transform_to), transform_to_ref_count) - self.assertEqual(sys.getrefcount(transform_from), transform_from_ref_count) - - def test_explicit_unbind_clears_connection(self): - self.assertEqual(self.source.int_prop, 0) - self.assertEqual(self.target.int_prop, 0) - - # Test deleting binding reference removes binding. - binding = self.source.bind_property('int_prop', self.target, 'int_prop') - self.source.int_prop = 1 - self.assertEqual(self.source.int_prop, 1) - self.assertEqual(self.target.int_prop, 1) - - # unbind should clear out the bindings self reference - binding.unbind() - self.assertEqual(binding.__grefcount__, 1) - - self.source.int_prop = 10 - self.assertEqual(self.source.int_prop, 10) - self.assertEqual(self.target.int_prop, 1) - - # An already unbound BindingWeakRef will raise if unbind is attempted a second time. - self.assertRaises(ValueError, binding.unbind) - - def test_reference_counts(self): - self.assertEqual(self.source.__grefcount__, 1) - self.assertEqual(self.target.__grefcount__, 1) - - # Binding ref count will be 2 do to the initial ref implicitly held by - # the act of binding and the ref incurred by using __call__ to generate - # a wrapper from the weak binding ref within python. - binding = self.source.bind_property('int_prop', self.target, 'int_prop') - self.assertEqual(binding.__grefcount__, 2) - - # Creating a binding does not inc refs on source and target (they are weak - # on the binding object itself) - self.assertEqual(self.source.__grefcount__, 1) - self.assertEqual(self.target.__grefcount__, 1) - - # Use GObject.get_property because the "props" accessor leaks. - # Note property names are canonicalized. - self.assertEqual(binding.get_property('source'), self.source) - self.assertEqual(binding.get_property('source_property'), 'int-prop') - self.assertEqual(binding.get_property('target'), self.target) - self.assertEqual(binding.get_property('target_property'), 'int-prop') - self.assertEqual(binding.get_property('flags'), GObject.BindingFlags.DEFAULT) - - # Delete reference to source or target and the binding will remove its own - # "self reference". - ref = self.source.weak_ref() - del self.source - gc.collect() - self.assertEqual(ref(), None) - self.assertEqual(binding.__grefcount__, 1) - - # Finally clear out the last ref held by the python wrapper - ref = binding.weak_ref() - del binding - gc.collect() - self.assertEqual(ref(), None) - - -class TestGValue(unittest.TestCase): - def test_type_constant(self): - self.assertEqual(GObject.TYPE_VALUE, GObject.Value.__gtype__) - self.assertEqual(GObject.type_name(GObject.TYPE_VALUE), 'GValue') - - def test_no_type(self): - value = GObject.Value() - self.assertEqual(value.g_type, GObject.TYPE_INVALID) - self.assertRaises(TypeError, value.set_value, 23) - self.assertEqual(value.get_value(), None) - - def test_int(self): - value = GObject.Value(GObject.TYPE_UINT) - self.assertEqual(value.g_type, GObject.TYPE_UINT) - value.set_value(23) - self.assertEqual(value.get_value(), 23) - value.set_value(42.0) - self.assertEqual(value.get_value(), 42) - - def test_string(self): - value = GObject.Value(str, 'foo_bar') - self.assertEqual(value.g_type, GObject.TYPE_STRING) - self.assertEqual(value.get_value(), 'foo_bar') - - def test_float(self): - # python float is G_TYPE_DOUBLE - value = GObject.Value(float, 23.4) - self.assertEqual(value.g_type, GObject.TYPE_DOUBLE) - value.set_value(1e50) - self.assertAlmostEqual(value.get_value(), 1e50) - - value = GObject.Value(GObject.TYPE_FLOAT, 23.4) - self.assertEqual(value.g_type, GObject.TYPE_FLOAT) - self.assertRaises(TypeError, value.set_value, 'string') - self.assertRaises(OverflowError, value.set_value, 1e50) - - def test_float_inf_nan(self): - nan = float('nan') - for type_ in [GObject.TYPE_FLOAT, GObject.TYPE_DOUBLE]: - for x in [float('inf'), float('-inf'), nan]: - value = GObject.Value(type_, x) - # assertEqual() is False for (nan, nan) - if x is nan: - self.assertEqual(str(value.get_value()), 'nan') - else: - self.assertEqual(value.get_value(), x) - - def test_enum(self): - value = GObject.Value(GLib.FileError, GLib.FileError.FAILED) - self.assertEqual(value.get_value(), GLib.FileError.FAILED) - - def test_flags(self): - value = GObject.Value(GLib.IOFlags, GLib.IOFlags.IS_READABLE) - self.assertEqual(value.get_value(), GLib.IOFlags.IS_READABLE) - - def test_object(self): - class TestObject(GObject.Object): - pass - obj = TestObject() - value = GObject.Value(GObject.TYPE_OBJECT, obj) - self.assertEqual(value.get_value(), obj) - - def test_value_array(self): - value = GObject.Value(GObject.ValueArray) - self.assertEqual(value.g_type, GObject.type_from_name('GValueArray')) - value.set_value([32, 'foo_bar', 0.3]) - self.assertEqual(value.get_value(), [32, 'foo_bar', 0.3]) - - def test_gerror_boxing(self): - error = GLib.Error('test message', domain='mydomain', code=42) - value = GObject.Value(GLib.Error, error) - self.assertEqual(value.g_type, GObject.type_from_name('GError')) - - unboxed = value.get_value() - self.assertEqual(unboxed.message, error.message) - self.assertEqual(unboxed.domain, error.domain) - self.assertEqual(unboxed.code, error.code) - - def test_gerror_novalue(self): - GLib.Error('test message', domain='mydomain', code=42) - value = GObject.Value(GLib.Error) - self.assertEqual(value.g_type, GObject.type_from_name('GError')) - self.assertEqual(value.get_value(), None) - - if __name__ == '__main__': unittest.main() diff --git a/tests/test_gtype.py b/tests/test_gtype.py deleted file mode 100644 index 8099101..0000000 --- a/tests/test_gtype.py +++ /dev/null @@ -1,51 +0,0 @@ -import unittest - -from gi.repository import GObject -from gi.repository import GIMarshallingTests - - -class CustomBase(GObject.GObject): - pass - - -class CustomChild(CustomBase, GIMarshallingTests.Interface): - pass - - -class TestTypeModuleLevelFunctions(unittest.TestCase): - def test_type_name(self): - self.assertEqual(GObject.type_name(GObject.TYPE_NONE), 'void') - self.assertEqual(GObject.type_name(GObject.TYPE_OBJECT), 'GObject') - self.assertEqual(GObject.type_name(GObject.TYPE_PYOBJECT), 'PyObject') - - def test_type_from_name(self): - # A complete test is not needed here since the TYPE_* defines are created - # using this method. - self.assertRaises(RuntimeError, GObject.type_from_name, '!NOT_A_REAL_TYPE!') - self.assertEqual(GObject.type_from_name('GObject'), GObject.TYPE_OBJECT) - self.assertEqual(GObject.type_from_name('GObject'), GObject.GObject.__gtype__) - - def test_type_is_a(self): - self.assertTrue(GObject.type_is_a(CustomBase, GObject.TYPE_OBJECT)) - self.assertTrue(GObject.type_is_a(CustomChild, CustomBase)) - self.assertTrue(GObject.type_is_a(CustomBase, GObject.GObject)) - self.assertTrue(GObject.type_is_a(CustomBase.__gtype__, GObject.TYPE_OBJECT)) - self.assertFalse(GObject.type_is_a(GObject.TYPE_OBJECT, CustomBase)) - self.assertFalse(GObject.type_is_a(CustomBase, int)) # invalid type - self.assertRaises(TypeError, GObject.type_is_a, CustomBase, 1) - self.assertRaises(TypeError, GObject.type_is_a, 2, GObject.TYPE_OBJECT) - self.assertRaises(TypeError, GObject.type_is_a, 1, 2) - - def test_type_children(self): - self.assertEqual(GObject.type_children(CustomBase), [CustomChild.__gtype__]) - self.assertEqual(len(GObject.type_children(CustomChild)), 0) - - def test_type_interfaces(self): - self.assertEqual(len(GObject.type_interfaces(CustomBase)), 0) - self.assertEqual(len(GObject.type_interfaces(CustomChild)), 1) - self.assertEqual(GObject.type_interfaces(CustomChild), [GIMarshallingTests.Interface.__gtype__]) - - def test_type_parent(self): - self.assertEqual(GObject.type_parent(CustomChild), CustomBase.__gtype__) - self.assertEqual(GObject.type_parent(CustomBase), GObject.TYPE_OBJECT) - self.assertRaises(RuntimeError, GObject.type_parent, GObject.GObject) diff --git a/tests/test_import_machinery.py b/tests/test_import_machinery.py deleted file mode 100644 index 044117d..0000000 --- a/tests/test_import_machinery.py +++ /dev/null @@ -1,151 +0,0 @@ -# -*- Mode: Python; py-indent-offset: 4 -*- -# vim: tabstop=4 shiftwidth=4 expandtab - -import sys -import unittest - -import gi.overrides -import gi.module -import gi.importer - -from gi.repository import Regress - - -class TestOverrides(unittest.TestCase): - - def test_non_gi(self): - class MyClass: - pass - - try: - gi.overrides.override(MyClass) - self.fail('unexpected success of overriding non-GI class') - except TypeError as e: - self.assertTrue('Can not override a type MyClass' in str(e)) - - def test_separate_path(self): - # Regress override is in tests/gi/overrides, separate from gi/overrides - # https://bugzilla.gnome.org/show_bug.cgi?id=680913 - self.assertEqual(Regress.REGRESS_OVERRIDE, 42) - - def test_load_overrides(self): - mod = gi.module.get_introspection_module('GIMarshallingTests') - mod_override = gi.overrides.load_overrides(mod) - self.assertTrue(mod_override is not mod) - self.assertTrue(mod_override._introspection_module is mod) - self.assertEqual(mod_override.OVERRIDES_CONSTANT, 7) - self.assertEqual(mod.OVERRIDES_CONSTANT, 42) - - def test_load_no_overrides(self): - mod_key = "gi.overrides.GIMarshallingTests" - had_mod = mod_key in sys.modules - old_mod = sys.modules.get(mod_key) - try: - # this makes override import fail - sys.modules[mod_key] = None - mod = gi.module.get_introspection_module('GIMarshallingTests') - mod_override = gi.overrides.load_overrides(mod) - self.assertTrue(mod_override is mod) - finally: - del sys.modules[mod_key] - if had_mod: - sys.modules[mod_key] = old_mod - - -class TestModule(unittest.TestCase): - # Tests for gi.module - - def test_get_introspection_module_caching(self): - # This test attempts to minimize side effects by - # using a DynamicModule directly instead of going though: - # from gi.repository import Foo - - # Clear out introspection module cache before running this test. - old_modules = gi.module._introspection_modules - gi.module._introspection_modules = {} - - mod_name = 'GIMarshallingTests' - mod1 = gi.module.get_introspection_module(mod_name) - mod2 = gi.module.get_introspection_module(mod_name) - self.assertTrue(mod1 is mod2) - - # Restore the previous cache - gi.module._introspection_modules = old_modules - - def test_module_dependency_loading(self): - # Difficult to because this generally need to run in isolation to make - # sure GIMarshallingTests has not yet been loaded. But we can do this with: - # make check TEST_NAMES=test_import_machinery.TestModule.test_module_dependency_loading - if 'gi.repository.Gio' in sys.modules: - return - - from gi.repository import GIMarshallingTests - GIMarshallingTests # PyFlakes - - self.assertIn('gi.repository.Gio', sys.modules) - self.assertIn('gi.repository.GIMarshallingTests', sys.modules) - - def test_static_binding_protection(self): - # Importing old static bindings once gi has been imported should not - # crash but instead give back a dummy module which produces RuntimeErrors - # on access. - with self.assertRaises(AttributeError): - import gobject - gobject.anything - - with self.assertRaises(AttributeError): - import glib - glib.anything - - with self.assertRaises(AttributeError): - import gio - gio.anything - - with self.assertRaises(AttributeError): - import gtk - gtk.anything - - with self.assertRaises(AttributeError): - import gtk.gdk - gtk.gdk.anything - - -class TestImporter(unittest.TestCase): - def test_invalid_repository_module_name(self): - with self.assertRaises(ImportError) as context: - from gi.repository import InvalidGObjectRepositoryModuleName - InvalidGObjectRepositoryModuleName # pyflakes - - exception_string = str(context.exception) - - self.assertTrue('InvalidGObjectRepositoryModuleName' in exception_string) - - # The message of the custom exception in gi/importer.py is eaten in Python <3.3 - if sys.version_info < (3, 3): - self.assertTrue('introspection typelib' not in exception_string) - else: - self.assertTrue('introspection typelib' in exception_string) - - def test_require_version_warning(self): - check = gi.importer._check_require_version - - # make sure it doesn't fail at least - with check("GLib", 1): - from gi.repository import GLib - GLib - - # make sure the exception propagates - with self.assertRaises(ImportError): - with check("InvalidGObjectRepositoryModuleName", 1): - from gi.repository import InvalidGObjectRepositoryModuleName - InvalidGObjectRepositoryModuleName - - def test_require_versions(self): - import gi - gi.require_versions({'GLib': '2.0', 'Gio': '2.0', 'GObject': '2.0'}) - from gi.repository import GLib - GLib - - def test_get_import_stacklevel(self): - gi.importer.get_import_stacklevel(import_hook=True) - gi.importer.get_import_stacklevel(import_hook=False) diff --git a/tests/test_interface.py b/tests/test_interface.py index ba20cb4..2df61b1 100644 --- a/tests/test_interface.py +++ b/tests/test_interface.py @@ -20,8 +20,6 @@ class MyUnknown(Unknown, testhelper.Interface): def do_iface_method(self): self.called = True Unknown.do_iface_method(self) - - GObject.type_register(MyUnknown) @@ -34,19 +32,17 @@ class MyObject(GObject.GObject, testhelper.Interface): def do_iface_method(self): self.called = True - - GObject.type_register(MyObject) class TestIfaceImpl(unittest.TestCase): - def test_reimplement_interface(self): + def testReImplementInterface(self): m = MyUnknown() m.iface_method() self.assertEqual(m.called, True) - def test_implement_interface(self): + def testImplementInterface(self): m = MyObject() m.iface_method() self.assertEqual(m.called, True) diff --git a/tests/test_internal_api.py b/tests/test_internal_api.py deleted file mode 100644 index eb66fdd..0000000 --- a/tests/test_internal_api.py +++ /dev/null @@ -1,73 +0,0 @@ -# -*- Mode: Python -*- - -import unittest - -from gi.repository import GLib, GObject - -import testhelper -import testmodule - - -class TestObject(unittest.TestCase): - def test_create_ctor(self): - o = testmodule.PyGObject() - self.assertTrue(isinstance(o, GObject.Object)) - self.assertTrue(isinstance(o, testmodule.PyGObject)) - - # has expected property - self.assertEqual(o.props.label, 'hello') - o.props.label = 'goodbye' - self.assertEqual(o.props.label, 'goodbye') - self.assertRaises(AttributeError, getattr, o.props, 'nosuchprop') - - def test_pyobject_new_test_type(self): - o = testhelper.create_test_type() - self.assertTrue(isinstance(o, testmodule.PyGObject)) - - # has expected property - self.assertEqual(o.props.label, 'hello') - o.props.label = 'goodbye' - self.assertEqual(o.props.label, 'goodbye') - self.assertRaises(AttributeError, getattr, o.props, 'nosuchprop') - - def test_new_refcount(self): - # TODO: justify why this should be 2 - self.assertEqual(testhelper.test_g_object_new(), 2) - - -class TestGValueConversion(unittest.TestCase): - def test_int(self): - self.assertEqual(testhelper.test_value(0), 0) - self.assertEqual(testhelper.test_value(5), 5) - self.assertEqual(testhelper.test_value(-5), -5) - self.assertEqual(testhelper.test_value(GLib.MAXINT32), GLib.MAXINT32) - self.assertEqual(testhelper.test_value(GLib.MININT32), GLib.MININT32) - - def test_str(self): - self.assertEqual(testhelper.test_value('hello'), 'hello') - - def test_int_array(self): - self.assertEqual(testhelper.test_value_array([]), []) - self.assertEqual(testhelper.test_value_array([0]), [0]) - ar = list(range(100)) - self.assertEqual(testhelper.test_value_array(ar), ar) - - def test_str_array(self): - self.assertEqual(testhelper.test_value_array([]), []) - self.assertEqual(testhelper.test_value_array(['a']), ['a']) - ar = ('aa ' * 1000).split() - self.assertEqual(testhelper.test_value_array(ar), ar) - - -class TestErrors(unittest.TestCase): - def test_gerror(self): - callable_ = lambda: GLib.file_get_contents('/nonexisting ') - self.assertRaises(GLib.GError, testhelper.test_gerror_exception, callable_) - - def test_no_gerror(self): - callable_ = lambda: GLib.file_get_contents(__file__) - self.assertEqual(testhelper.test_gerror_exception(callable_), None) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/test_iochannel.py b/tests/test_iochannel.py deleted file mode 100644 index 95b8d1f..0000000 --- a/tests/test_iochannel.py +++ /dev/null @@ -1,480 +0,0 @@ -# -*- Mode: Python -*- -# encoding: UTF-8 - -import os -import unittest -import tempfile -import os.path -import shutil -import warnings - -try: - import fcntl -except ImportError: - fcntl = None - -from gi.repository import GLib -from gi import PyGIDeprecationWarning - - -class IOChannel(unittest.TestCase): - def setUp(self): - self.workdir = tempfile.mkdtemp() - - self.testutf8 = os.path.join(self.workdir, 'testutf8.txt') - with open(self.testutf8, 'wb') as f: - f.write(u'''hello ♥ world -second line - -À demain!'''.encode('UTF-8')) - - self.testlatin1 = os.path.join(self.workdir, 'testlatin1.txt') - with open(self.testlatin1, 'wb') as f: - f.write(b'''hell\xf8 world -second line - -\xc0 demain!''') - - self.testout = os.path.join(self.workdir, 'testout.txt') - - def tearDown(self): - shutil.rmtree(self.workdir) - - def test_file_readline_utf8(self): - ch = GLib.IOChannel(filename=self.testutf8) - self.assertEqual(ch.get_encoding(), 'UTF-8') - self.assertTrue(ch.get_close_on_unref()) - self.assertEqual(ch.readline(), 'hello ♥ world\n') - self.assertEqual(ch.get_buffer_condition(), GLib.IOCondition.IN) - self.assertEqual(ch.readline(), 'second line\n') - self.assertEqual(ch.readline(), '\n') - self.assertEqual(ch.readline(), 'À demain!') - self.assertEqual(ch.get_buffer_condition(), 0) - self.assertEqual(ch.readline(), '') - ch.shutdown(True) - - def test_file_readline_latin1(self): - ch = GLib.IOChannel(filename=self.testlatin1, mode='r') - ch.set_encoding('latin1') - self.assertEqual(ch.get_encoding(), 'latin1') - self.assertEqual(ch.readline(), 'hellø world\n') - self.assertEqual(ch.readline(), 'second line\n') - self.assertEqual(ch.readline(), '\n') - self.assertEqual(ch.readline(), 'À demain!') - ch.shutdown(True) - - def test_file_iter(self): - items = [] - ch = GLib.IOChannel(filename=self.testutf8) - for item in ch: - items.append(item) - self.assertEqual(len(items), 4) - self.assertEqual(items[0], 'hello ♥ world\n') - ch.shutdown(True) - - def test_file_readlines(self): - ch = GLib.IOChannel(filename=self.testutf8) - lines = ch.readlines() - # Note, this really ought to be 4, but the static bindings add an extra - # empty one - self.assertGreaterEqual(len(lines), 4) - self.assertLessEqual(len(lines), 5) - self.assertEqual(lines[0], 'hello ♥ world\n') - self.assertEqual(lines[3], 'À demain!') - if len(lines) == 4: - self.assertEqual(lines[4], '') - - def test_file_read(self): - ch = GLib.IOChannel(filename=self.testutf8) - with open(self.testutf8, 'rb') as f: - self.assertEqual(ch.read(), f.read()) - - ch = GLib.IOChannel(filename=self.testutf8) - with open(self.testutf8, 'rb') as f: - self.assertEqual(ch.read(10), f.read(10)) - - ch = GLib.IOChannel(filename=self.testutf8) - with open(self.testutf8, 'rb') as f: - self.assertEqual(ch.read(max_count=15), f.read(15)) - - def test_seek(self): - ch = GLib.IOChannel(filename=self.testutf8) - ch.seek(2) - self.assertEqual(ch.read(3), b'llo') - - ch.seek(2, 0) # SEEK_SET - self.assertEqual(ch.read(3), b'llo') - - ch.seek(1, 1) # SEEK_CUR, skip the space - self.assertEqual(ch.read(3), b'\xe2\x99\xa5') - - ch.seek(2, 2) # SEEK_END - # FIXME: does not work currently - # self.assertEqual(ch.read(2), b'n!') - - # invalid whence value - self.assertRaises(ValueError, ch.seek, 0, 3) - ch.shutdown(True) - - def test_file_write(self): - ch = GLib.IOChannel(filename=self.testout, mode='w') - ch.set_encoding('latin1') - ch.write('hellø world\n') - ch.shutdown(True) - ch = GLib.IOChannel(filename=self.testout, mode='a') - ch.set_encoding('latin1') - ch.write('À demain!') - ch.shutdown(True) - - with open(self.testout, 'rb') as f: - self.assertEqual(f.read().decode('latin1'), u'hellø world\nÀ demain!') - - def test_file_writelines(self): - ch = GLib.IOChannel(filename=self.testout, mode='w') - ch.writelines(['foo', 'bar\n', 'baz\n', 'end']) - ch.shutdown(True) - - with open(self.testout, 'r') as f: - self.assertEqual(f.read(), 'foobar\nbaz\nend') - - def test_buffering(self): - writer = GLib.IOChannel(filename=self.testout, mode='w') - writer.set_encoding(None) - self.assertTrue(writer.get_buffered()) - self.assertGreater(writer.get_buffer_size(), 10) - - reader = GLib.IOChannel(filename=self.testout, mode='r') - - # does not get written immediately on buffering - writer.write('abc') - self.assertEqual(reader.read(), b'') - writer.flush() - self.assertEqual(reader.read(), b'abc') - - # does get written immediately without buffering - writer.set_buffered(False) - writer.write('def') - self.assertEqual(reader.read(), b'def') - - # writes after buffer overflow - writer.set_buffer_size(10) - writer.write('0123456789012') - self.assertTrue(reader.read().startswith(b'012')) - writer.flush() - reader.read() # ignore bits written after flushing - - # closing flushes - writer.set_buffered(True) - writer.write('ghi') - writer.shutdown(True) - self.assertEqual(reader.read(), b'ghi') - reader.shutdown(True) - - @unittest.skipIf(os.name == "nt", "NONBLOCK not implemented on Windows") - def test_fd_read(self): - (r, w) = os.pipe() - - ch = GLib.IOChannel(filedes=r) - ch.set_encoding(None) - ch.set_flags(ch.get_flags() | GLib.IOFlags.NONBLOCK) - self.assertNotEqual(ch.get_flags() | GLib.IOFlags.NONBLOCK, 0) - self.assertEqual(ch.read(), b'') - os.write(w, b'\x01\x02') - self.assertEqual(ch.read(), b'\x01\x02') - - # now test blocking case, after closing the write end - ch.set_flags(GLib.IOFlags(ch.get_flags() & ~GLib.IOFlags.NONBLOCK)) - os.write(w, b'\x03\x04') - os.close(w) - self.assertEqual(ch.read(), b'\x03\x04') - - ch.shutdown(True) - - @unittest.skipUnless(fcntl, "no fcntl") - def test_fd_write(self): - (r, w) = os.pipe() - fcntl.fcntl(r, fcntl.F_SETFL, fcntl.fcntl(r, fcntl.F_GETFL) | os.O_NONBLOCK) - - ch = GLib.IOChannel(filedes=w, mode='w') - ch.set_encoding(None) - ch.set_buffered(False) - ch.write(b'\x01\x02') - self.assertEqual(os.read(r, 10), b'\x01\x02') - - # now test blocking case, after closing the write end - fcntl.fcntl(r, fcntl.F_SETFL, fcntl.fcntl(r, fcntl.F_GETFL) & ~os.O_NONBLOCK) - ch.write(b'\x03\x04') - ch.shutdown(True) - self.assertEqual(os.read(r, 10), b'\x03\x04') - os.close(r) - - @unittest.skipIf(os.name == "nt", "NONBLOCK not implemented on Windows") - def test_deprecated_method_add_watch_no_data(self): - (r, w) = os.pipe() - - ch = GLib.IOChannel(filedes=r) - ch.set_encoding(None) - ch.set_flags(ch.get_flags() | GLib.IOFlags.NONBLOCK) - - cb_reads = [] - - def cb(channel, condition): - self.assertEqual(channel, ch) - self.assertEqual(condition, GLib.IOCondition.IN) - cb_reads.append(channel.read()) - if len(cb_reads) == 2: - ml.quit() - return True - - # io_add_watch() method is deprecated, use GLib.io_add_watch - with warnings.catch_warnings(record=True) as warn: - warnings.simplefilter('always') - ch.add_watch(GLib.IOCondition.IN, cb, priority=GLib.PRIORITY_HIGH) - self.assertTrue(issubclass(warn[0].category, PyGIDeprecationWarning)) - - def write(): - os.write(w, b'a') - GLib.idle_add(lambda: os.write(w, b'b') and False) - - ml = GLib.MainLoop() - GLib.idle_add(write) - GLib.timeout_add(2000, ml.quit) - ml.run() - - self.assertEqual(cb_reads, [b'a', b'b']) - - @unittest.skipIf(os.name == "nt", "NONBLOCK not implemented on Windows") - def test_deprecated_method_add_watch_data_priority(self): - (r, w) = os.pipe() - - ch = GLib.IOChannel(filedes=r) - ch.set_encoding(None) - ch.set_flags(ch.get_flags() | GLib.IOFlags.NONBLOCK) - - cb_reads = [] - - def cb(channel, condition, data): - self.assertEqual(channel, ch) - self.assertEqual(condition, GLib.IOCondition.IN) - self.assertEqual(data, 'hello') - cb_reads.append(channel.read()) - if len(cb_reads) == 2: - ml.quit() - return True - - ml = GLib.MainLoop() - # io_add_watch() method is deprecated, use GLib.io_add_watch - with warnings.catch_warnings(record=True) as warn: - warnings.simplefilter('always') - id = ch.add_watch(GLib.IOCondition.IN, cb, 'hello', priority=GLib.PRIORITY_HIGH) - self.assertTrue(issubclass(warn[0].category, PyGIDeprecationWarning)) - - self.assertEqual(ml.get_context().find_source_by_id(id).priority, - GLib.PRIORITY_HIGH) - - def write(): - os.write(w, b'a') - GLib.idle_add(lambda: os.write(w, b'b') and False) - - GLib.idle_add(write) - GLib.timeout_add(2000, ml.quit) - ml.run() - - self.assertEqual(cb_reads, [b'a', b'b']) - - @unittest.skipIf(os.name == "nt", "NONBLOCK not implemented on Windows") - def test_add_watch_no_data(self): - (r, w) = os.pipe() - - ch = GLib.IOChannel(filedes=r) - ch.set_encoding(None) - ch.set_flags(ch.get_flags() | GLib.IOFlags.NONBLOCK) - - cb_reads = [] - - def cb(channel, condition): - self.assertEqual(channel, ch) - self.assertEqual(condition, GLib.IOCondition.IN) - cb_reads.append(channel.read()) - if len(cb_reads) == 2: - ml.quit() - return True - - id = GLib.io_add_watch(ch, GLib.PRIORITY_HIGH, GLib.IOCondition.IN, cb) - - ml = GLib.MainLoop() - self.assertEqual(ml.get_context().find_source_by_id(id).priority, - GLib.PRIORITY_HIGH) - - def write(): - os.write(w, b'a') - GLib.idle_add(lambda: os.write(w, b'b') and False) - - GLib.idle_add(write) - GLib.timeout_add(2000, ml.quit) - ml.run() - - self.assertEqual(cb_reads, [b'a', b'b']) - - @unittest.skipIf(os.name == "nt", "NONBLOCK not implemented on Windows") - def test_add_watch_with_data(self): - (r, w) = os.pipe() - - ch = GLib.IOChannel(filedes=r) - ch.set_encoding(None) - ch.set_flags(ch.get_flags() | GLib.IOFlags.NONBLOCK) - - cb_reads = [] - - def cb(channel, condition, data): - self.assertEqual(channel, ch) - self.assertEqual(condition, GLib.IOCondition.IN) - self.assertEqual(data, 'hello') - cb_reads.append(channel.read()) - if len(cb_reads) == 2: - ml.quit() - return True - - id = GLib.io_add_watch(ch, GLib.PRIORITY_HIGH, GLib.IOCondition.IN, cb, 'hello') - - ml = GLib.MainLoop() - self.assertEqual(ml.get_context().find_source_by_id(id).priority, - GLib.PRIORITY_HIGH) - - def write(): - os.write(w, b'a') - GLib.idle_add(lambda: os.write(w, b'b') and False) - - GLib.idle_add(write) - GLib.timeout_add(2000, ml.quit) - ml.run() - - self.assertEqual(cb_reads, [b'a', b'b']) - - @unittest.skipIf(os.name == "nt", "NONBLOCK not implemented on Windows") - def test_add_watch_with_multi_data(self): - (r, w) = os.pipe() - - ch = GLib.IOChannel(filedes=r) - ch.set_encoding(None) - ch.set_flags(ch.get_flags() | GLib.IOFlags.NONBLOCK) - - cb_reads = [] - - def cb(channel, condition, data1, data2, data3): - self.assertEqual(channel, ch) - self.assertEqual(condition, GLib.IOCondition.IN) - self.assertEqual(data1, 'a') - self.assertEqual(data2, 'b') - self.assertEqual(data3, 'c') - cb_reads.append(channel.read()) - if len(cb_reads) == 2: - ml.quit() - return True - - id = GLib.io_add_watch(ch, GLib.PRIORITY_HIGH, GLib.IOCondition.IN, cb, - 'a', 'b', 'c') - - ml = GLib.MainLoop() - self.assertEqual(ml.get_context().find_source_by_id(id).priority, - GLib.PRIORITY_HIGH) - - def write(): - os.write(w, b'a') - GLib.idle_add(lambda: os.write(w, b'b') and False) - - GLib.idle_add(write) - GLib.timeout_add(2000, ml.quit) - ml.run() - - self.assertEqual(cb_reads, [b'a', b'b']) - - @unittest.skipIf(os.name == "nt", "NONBLOCK not implemented on Windows") - def test_deprecated_add_watch_no_data(self): - (r, w) = os.pipe() - - ch = GLib.IOChannel(filedes=r) - ch.set_encoding(None) - ch.set_flags(ch.get_flags() | GLib.IOFlags.NONBLOCK) - - cb_reads = [] - - def cb(channel, condition): - self.assertEqual(channel, ch) - self.assertEqual(condition, GLib.IOCondition.IN) - cb_reads.append(channel.read()) - if len(cb_reads) == 2: - ml.quit() - return True - - with warnings.catch_warnings(record=True) as warn: - warnings.simplefilter('always') - id = GLib.io_add_watch(ch, GLib.IOCondition.IN, cb, priority=GLib.PRIORITY_HIGH) - self.assertTrue(issubclass(warn[0].category, PyGIDeprecationWarning)) - - ml = GLib.MainLoop() - self.assertEqual(ml.get_context().find_source_by_id(id).priority, - GLib.PRIORITY_HIGH) - - def write(): - os.write(w, b'a') - GLib.idle_add(lambda: os.write(w, b'b') and False) - - GLib.idle_add(write) - GLib.timeout_add(2000, ml.quit) - ml.run() - - self.assertEqual(cb_reads, [b'a', b'b']) - - @unittest.skipIf(os.name == "nt", "NONBLOCK not implemented on Windows") - def test_deprecated_add_watch_with_data(self): - (r, w) = os.pipe() - - ch = GLib.IOChannel(filedes=r) - ch.set_encoding(None) - ch.set_flags(ch.get_flags() | GLib.IOFlags.NONBLOCK) - - cb_reads = [] - - def cb(channel, condition, data): - self.assertEqual(channel, ch) - self.assertEqual(condition, GLib.IOCondition.IN) - self.assertEqual(data, 'hello') - cb_reads.append(channel.read()) - if len(cb_reads) == 2: - ml.quit() - return True - - with warnings.catch_warnings(record=True) as warn: - warnings.simplefilter('always') - id = GLib.io_add_watch(ch, GLib.IOCondition.IN, cb, 'hello', - priority=GLib.PRIORITY_HIGH) - self.assertTrue(issubclass(warn[0].category, PyGIDeprecationWarning)) - - ml = GLib.MainLoop() - self.assertEqual(ml.get_context().find_source_by_id(id).priority, - GLib.PRIORITY_HIGH) - - def write(): - os.write(w, b'a') - GLib.idle_add(lambda: os.write(w, b'b') and False) - - GLib.idle_add(write) - - GLib.timeout_add(2000, ml.quit) - ml.run() - - self.assertEqual(cb_reads, [b'a', b'b']) - - def test_backwards_compat_flags(self): - with warnings.catch_warnings(): - warnings.simplefilter('ignore', PyGIDeprecationWarning) - - self.assertEqual(GLib.IOCondition.IN, GLib.IO_IN) - self.assertEqual(GLib.IOFlags.NONBLOCK, GLib.IO_FLAG_NONBLOCK) - self.assertEqual(GLib.IOFlags.IS_SEEKABLE, GLib.IO_FLAG_IS_SEEKABLE) - self.assertEqual(GLib.IOStatus.NORMAL, GLib.IO_STATUS_NORMAL) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/test_mainloop.py b/tests/test_mainloop.py index fda6787..4c7794a 100644 --- a/tests/test_mainloop.py +++ b/tests/test_mainloop.py @@ -4,14 +4,21 @@ import os import sys import select import signal +import time import unittest +try: + from _thread import start_new_thread + start_new_thread # pyflakes +except ImportError: + # Python 2 + from thread import start_new_thread from gi.repository import GLib +from compathelper import _bytes -class TestMainLoop(unittest.TestCase): - @unittest.skipUnless(hasattr(os, "fork"), "no os.fork available") +class TestMainLoop(unittest.TestCase): def test_exception_handling(self): pipe_r, pipe_w = os.pipe() @@ -27,55 +34,47 @@ class TestMainLoop(unittest.TestCase): raise Exception("deadbabe") loop = GLib.MainLoop() - GLib.child_watch_add(GLib.PRIORITY_DEFAULT, pid, child_died, loop) + GLib.child_watch_add(pid, child_died, loop) os.close(pipe_r) - os.write(pipe_w, b"Y") + os.write(pipe_w, _bytes("Y")) os.close(pipe_w) def excepthook(type, value, traceback): - self.assertTrue(type is Exception) - self.assertEqual(value.args[0], "deadbabe") + assert type is Exception + assert value.args[0] == "deadbabe" sys.excepthook = excepthook + + got_exception = False try: - got_exception = False - try: - loop.run() - except: - got_exception = True - finally: - sys.excepthook = sys.__excepthook__ + loop.run() + except: + got_exception = True # # The exception should be handled (by printing it) # immediately on return from child_died() rather # than here. See bug #303573 # - self.assertFalse(got_exception) - - @unittest.skipUnless(hasattr(os, "fork"), "no os.fork available") - def test_sigint(self): - r, w = os.pipe() - pid = os.fork() - if pid == 0: - # wait for the parent process loop to start - os.read(r, 1) - os.close(r) + sys.excepthook = sys.__excepthook__ + assert not got_exception - os.kill(os.getppid(), signal.SIGINT) - os._exit(0) - - def notify_child(): - # tell the child that it can kill the parent - os.write(w, b"X") - os.close(w) + def test_concurrency(self): + def on_usr1(signum, frame): + pass - GLib.idle_add(notify_child) - loop = GLib.MainLoop() try: - loop.run() - self.fail('expected KeyboardInterrupt exception') - except KeyboardInterrupt: - pass - self.assertFalse(loop.is_running()) - os.waitpid(pid, 0) + # create a thread which will terminate upon SIGUSR1 by way of + # interrupting sleep() + orig_handler = signal.signal(signal.SIGUSR1, on_usr1) + start_new_thread(time.sleep, (10,)) + + # now create two main loops + loop1 = GLib.MainLoop() + loop2 = GLib.MainLoop() + GLib.timeout_add(100, lambda: os.kill(os.getpid(), signal.SIGUSR1)) + GLib.timeout_add(500, loop1.quit) + loop1.run() + loop2.quit() + finally: + signal.signal(signal.SIGUSR1, orig_handler) diff --git a/tests/test_object_marshaling.py b/tests/test_object_marshaling.py deleted file mode 100644 index c881a9a..0000000 --- a/tests/test_object_marshaling.py +++ /dev/null @@ -1,570 +0,0 @@ -# -*- Mode: Python; py-indent-offset: 4 -*- -# vim: tabstop=4 shiftwidth=4 expandtab - -import unittest -import weakref -import gc -import sys -import warnings - -from gi.repository import GObject -from gi.repository import GIMarshallingTests - -try: - from gi.repository import Regress -except ImportError: - Regress = None - - -class StrongRef(object): - # A class that behaves like weakref.ref but holds a strong reference. - # This allows re-use of the VFuncsBase by swapping out the ObjectRef - # class var with either weakref.ref or StrongRef. - - def __init__(self, obj): - self.obj = obj - - def __call__(self): - return self.obj - - -class VFuncsBase(GIMarshallingTests.Object): - # Class which generically implements the vfuncs used for reference counting tests - # in a way that can be easily sub-classed and modified. - - #: Object type used by this class for testing - #: This can be GObject.Object or GObject.InitiallyUnowned - Object = GObject.Object - - #: Reference type used by this class for holding refs to in/out objects. - #: This can be set to weakref.ref or StrongRef - ObjectRef = weakref.ref - - def __init__(self): - super(VFuncsBase, self).__init__() - - #: Hold ref of input or output python wrappers - self.object_ref = None - - #: store grefcount of input object - self.in_object_grefcount = None - self.in_object_is_floating = None - - def do_vfunc_return_object_transfer_none(self): - # Return an object but keep a python reference to it. - obj = self.Object() - self.object_ref = self.ObjectRef(obj) - return obj - - def do_vfunc_return_object_transfer_full(self): - # Return an object and hand off the reference to the caller. - obj = self.Object() - self.object_ref = self.ObjectRef(obj) - return obj - - def do_vfunc_out_object_transfer_none(self): - # Same as do_vfunc_return_object_transfer_none but the pygi - # internals convert the return here into an out arg. - obj = self.Object() - self.object_ref = self.ObjectRef(obj) - return obj - - def do_vfunc_out_object_transfer_full(self): - # Same as do_vfunc_return_object_transfer_full but the pygi - # internals convert the return here into an out arg. - obj = self.Object() - self.object_ref = self.ObjectRef(obj) - return obj - - def do_vfunc_in_object_transfer_none(self, obj): - # 'obj' will have a python wrapper as well as still held - # by the caller. - self.object_ref = self.ObjectRef(obj) - self.in_object_grefcount = obj.__grefcount__ - self.in_object_is_floating = obj.is_floating() - - def do_vfunc_in_object_transfer_full(self, obj): - # 'obj' will now be owned by the Python GObject wrapper. - # When obj goes out of scope and is collected, the GObject - # should also be fully released. - self.object_ref = self.ObjectRef(obj) - self.in_object_grefcount = obj.__grefcount__ - self.in_object_is_floating = obj.is_floating() - - -class TestVFuncsWithObjectArg(unittest.TestCase): - # Basic set of tests which work on non-floating objects which python does - # not keep an additional reference of. - - class VFuncs(VFuncsBase): - # Object for testing non-floating objects without holding any refs. - Object = GObject.Object - ObjectRef = weakref.ref - - def test_vfunc_self_arg_ref_count(self): - # Check to make sure vfunc "self" arguments don't leak. - vfuncs = self.VFuncs() - vfuncs_ref = weakref.ref(vfuncs) - vfuncs.get_ref_info_for_vfunc_return_object_transfer_full() # Use any vfunc to test this. - - gc.collect() - self.assertEqual(sys.getrefcount(vfuncs), 2) - self.assertEqual(vfuncs.__grefcount__, 1) - - del vfuncs - gc.collect() - self.assertTrue(vfuncs_ref() is None) - - def test_vfunc_return_object_transfer_none(self): - # This tests a problem case where the vfunc returns a GObject owned solely by Python - # but the argument is marked as transfer-none. - # In this case pygobject marshaling adds an additional ref and gives a warning - # of a potential leak. If this occures it is really a bug in the underlying library - # but pygobject tries to react to this in a reasonable way. - vfuncs = self.VFuncs() - with warnings.catch_warnings(record=True) as warn: - warnings.simplefilter('always') - ref_count, is_floating = vfuncs.get_ref_info_for_vfunc_out_object_transfer_none() - self.assertTrue(issubclass(warn[0].category, RuntimeWarning)) - - # The ref count of the GObject returned to the caller (get_ref_info_for_vfunc_return_object_transfer_none) - # should be a single floating ref - self.assertEqual(ref_count, 1) - self.assertFalse(is_floating) - - gc.collect() - self.assertTrue(vfuncs.object_ref() is None) - - def test_vfunc_out_object_transfer_none(self): - # Same as above except uses out arg instead of return - vfuncs = self.VFuncs() - with warnings.catch_warnings(record=True) as warn: - warnings.simplefilter('always') - ref_count, is_floating = vfuncs.get_ref_info_for_vfunc_out_object_transfer_none() - self.assertTrue(issubclass(warn[0].category, RuntimeWarning)) - - self.assertEqual(ref_count, 1) - self.assertFalse(is_floating) - - gc.collect() - self.assertTrue(vfuncs.object_ref() is None) - - def test_vfunc_return_object_transfer_full(self): - vfuncs = self.VFuncs() - ref_count, is_floating = vfuncs.get_ref_info_for_vfunc_return_object_transfer_full() - - # The vfunc caller receives full ownership of a single ref which should not - # be floating. - self.assertEqual(ref_count, 1) - self.assertFalse(is_floating) - - gc.collect() - self.assertTrue(vfuncs.object_ref() is None) - - def test_vfunc_out_object_transfer_full(self): - # Same as above except uses out arg instead of return - vfuncs = self.VFuncs() - ref_count, is_floating = vfuncs.get_ref_info_for_vfunc_out_object_transfer_full() - - self.assertEqual(ref_count, 1) - self.assertFalse(is_floating) - - gc.collect() - self.assertTrue(vfuncs.object_ref() is None) - - def test_vfunc_in_object_transfer_none(self): - vfuncs = self.VFuncs() - ref_count, is_floating = vfuncs.get_ref_info_for_vfunc_in_object_transfer_none(self.VFuncs.Object) - - gc.collect() - self.assertEqual(vfuncs.in_object_grefcount, 2) # initial + python wrapper - self.assertFalse(vfuncs.in_object_is_floating) - - self.assertEqual(ref_count, 1) # ensure python wrapper released - self.assertFalse(is_floating) - - self.assertTrue(vfuncs.object_ref() is None) - - def test_vfunc_in_object_transfer_full(self): - vfuncs = self.VFuncs() - ref_count, is_floating = vfuncs.get_ref_info_for_vfunc_in_object_transfer_full(self.VFuncs.Object) - - gc.collect() - - # python wrapper should take sole ownership of the gobject - self.assertEqual(vfuncs.in_object_grefcount, 1) - self.assertFalse(vfuncs.in_object_is_floating) - - # ensure python wrapper took ownership and released, after vfunc was complete - self.assertEqual(ref_count, 0) - self.assertFalse(is_floating) - - self.assertTrue(vfuncs.object_ref() is None) - - -class TestVFuncsWithFloatingArg(unittest.TestCase): - # All tests here work with a floating object by using InitiallyUnowned as the argument - - class VFuncs(VFuncsBase): - # Object for testing non-floating objects without holding any refs. - Object = GObject.InitiallyUnowned - ObjectRef = weakref.ref - - def test_vfunc_return_object_transfer_none_with_floating(self): - # Python is expected to return a single floating reference without warning. - vfuncs = self.VFuncs() - ref_count, is_floating = vfuncs.get_ref_info_for_vfunc_return_object_transfer_none() - - # The ref count of the GObject returned to the caller (get_ref_info_for_vfunc_return_object_transfer_none) - # should be a single floating ref - self.assertEqual(ref_count, 1) - self.assertTrue(is_floating) - - gc.collect() - self.assertTrue(vfuncs.object_ref() is None) - - def test_vfunc_out_object_transfer_none_with_floating(self): - # Same as above except uses out arg instead of return - vfuncs = self.VFuncs() - ref_count, is_floating = vfuncs.get_ref_info_for_vfunc_out_object_transfer_none() - - self.assertEqual(ref_count, 1) - self.assertTrue(is_floating) - - gc.collect() - self.assertTrue(vfuncs.object_ref() is None) - - def test_vfunc_return_object_transfer_full_with_floating(self): - vfuncs = self.VFuncs() - ref_count, is_floating = vfuncs.get_ref_info_for_vfunc_return_object_transfer_full() - - # The vfunc caller receives full ownership of a single ref. - self.assertEqual(ref_count, 1) - self.assertFalse(is_floating) - - gc.collect() - self.assertTrue(vfuncs.object_ref() is None) - - def test_vfunc_out_object_transfer_full_with_floating(self): - # Same as above except uses out arg instead of return - vfuncs = self.VFuncs() - ref_count, is_floating = vfuncs.get_ref_info_for_vfunc_out_object_transfer_full() - - self.assertEqual(ref_count, 1) - self.assertFalse(is_floating) - - gc.collect() - self.assertTrue(vfuncs.object_ref() is None) - - def test_vfunc_in_object_transfer_none_with_floating(self): - vfuncs = self.VFuncs() - ref_count, is_floating = vfuncs.get_ref_info_for_vfunc_in_object_transfer_none(self.VFuncs.Object) - - gc.collect() - - # python wrapper should maintain the object as floating and add an additional ref - self.assertEqual(vfuncs.in_object_grefcount, 2) - self.assertTrue(vfuncs.in_object_is_floating) - - # vfunc caller should only have a single floating ref after the vfunc finishes - self.assertEqual(ref_count, 1) - self.assertTrue(is_floating) - - self.assertTrue(vfuncs.object_ref() is None) - - def test_vfunc_in_object_transfer_full_with_floating(self): - vfuncs = self.VFuncs() - ref_count, is_floating = vfuncs.get_ref_info_for_vfunc_in_object_transfer_full(self.VFuncs.Object) - - gc.collect() - - # python wrapper sinks and owns the gobject - self.assertEqual(vfuncs.in_object_grefcount, 1) - self.assertFalse(vfuncs.in_object_is_floating) - - # ensure python wrapper took ownership and released - self.assertEqual(ref_count, 0) - self.assertFalse(is_floating) - - self.assertTrue(vfuncs.object_ref() is None) - - -class TestVFuncsWithHeldObjectArg(unittest.TestCase): - # Same tests as TestVFuncsWithObjectArg except we hold - # onto the python object reference in all cases. - - class VFuncs(VFuncsBase): - # Object for testing non-floating objects with a held ref. - Object = GObject.Object - ObjectRef = StrongRef - - def test_vfunc_return_object_transfer_none_with_held_object(self): - vfuncs = self.VFuncs() - ref_count, is_floating = vfuncs.get_ref_info_for_vfunc_return_object_transfer_none() - - # Python holds the single gobject ref in 'vfuncs.object_ref' - # Because of this, we do not expect a floating ref or a ref increase. - self.assertEqual(ref_count, 1) - self.assertFalse(is_floating) - - # The actual grefcount should stay at 1 even after the vfunc return. - self.assertEqual(vfuncs.object_ref().__grefcount__, 1) - self.assertFalse(vfuncs.in_object_is_floating) - - held_object_ref = weakref.ref(vfuncs.object_ref) - del vfuncs.object_ref - gc.collect() - self.assertTrue(held_object_ref() is None) - - def test_vfunc_out_object_transfer_none_with_held_object(self): - vfuncs = self.VFuncs() - ref_count, is_floating = vfuncs.get_ref_info_for_vfunc_out_object_transfer_none() - - self.assertEqual(ref_count, 1) - self.assertFalse(is_floating) - - self.assertEqual(vfuncs.object_ref().__grefcount__, 1) - self.assertFalse(vfuncs.in_object_is_floating) - - held_object_ref = weakref.ref(vfuncs.object_ref) - del vfuncs.object_ref - gc.collect() - self.assertTrue(held_object_ref() is None) - - def test_vfunc_return_object_transfer_full_with_held_object(self): - # The vfunc caller receives full ownership which should not - # be floating. However, the held python wrapper also has a ref. - - vfuncs = self.VFuncs() - ref_count, is_floating = vfuncs.get_ref_info_for_vfunc_return_object_transfer_full() - - # Ref count from the perspective of C after the vfunc is called - # The vfunc caller receives a new reference which should not - # be floating. However, the held python wrapper also has a ref. - self.assertEqual(ref_count, 2) - self.assertFalse(is_floating) - - # Current ref count - # The vfunc caller should have decremented its reference. - self.assertEqual(vfuncs.object_ref().__grefcount__, 1) - - held_object_ref = weakref.ref(vfuncs.object_ref) - del vfuncs.object_ref - gc.collect() - self.assertTrue(held_object_ref() is None) - - def test_vfunc_out_object_transfer_full_with_held_object(self): - # Same test as above except uses out arg instead of return - vfuncs = self.VFuncs() - ref_count, is_floating = vfuncs.get_ref_info_for_vfunc_out_object_transfer_full() - - # Ref count from the perspective of C after the vfunc is called - # The vfunc caller receives a new reference which should not - # be floating. However, the held python wrapper also has a ref. - self.assertEqual(ref_count, 2) - self.assertFalse(is_floating) - - # Current ref count - # The vfunc caller should have decremented its reference. - self.assertEqual(vfuncs.object_ref().__grefcount__, 1) - - held_object_ref = weakref.ref(vfuncs.object_ref()) - del vfuncs.object_ref - gc.collect() - self.assertTrue(held_object_ref() is None) - - def test_vfunc_in_object_transfer_none_with_held_object(self): - vfuncs = self.VFuncs() - ref_count, is_floating = vfuncs.get_ref_info_for_vfunc_in_object_transfer_none(self.VFuncs.Object) - - gc.collect() - - # Ref count inside vfunc from the perspective of Python - self.assertEqual(vfuncs.in_object_grefcount, 2) # initial + python wrapper - self.assertFalse(vfuncs.in_object_is_floating) - - # Ref count from the perspective of C after the vfunc is called - self.assertEqual(ref_count, 2) # kept after vfunc + held python wrapper - self.assertFalse(is_floating) - - # Current ref count after C cleans up its reference - self.assertEqual(vfuncs.object_ref().__grefcount__, 1) - - held_object_ref = weakref.ref(vfuncs.object_ref()) - del vfuncs.object_ref - gc.collect() - self.assertTrue(held_object_ref() is None) - - def test_vfunc_in_object_transfer_full_with_held_object(self): - vfuncs = self.VFuncs() - ref_count, is_floating = vfuncs.get_ref_info_for_vfunc_in_object_transfer_full(self.VFuncs.Object) - - gc.collect() - - # Ref count inside vfunc from the perspective of Python - self.assertEqual(vfuncs.in_object_grefcount, 1) # python wrapper takes ownership of the gobject - self.assertFalse(vfuncs.in_object_is_floating) - - # Ref count from the perspective of C after the vfunc is called - self.assertEqual(ref_count, 1) - self.assertFalse(is_floating) - - # Current ref count - self.assertEqual(vfuncs.object_ref().__grefcount__, 1) - - held_object_ref = weakref.ref(vfuncs.object_ref()) - del vfuncs.object_ref - gc.collect() - self.assertTrue(held_object_ref() is None) - - -class TestVFuncsWithHeldFloatingArg(unittest.TestCase): - # Tests for a floating object which we hold a reference to the python wrapper - # on the VFuncs test class. - - class VFuncs(VFuncsBase): - # Object for testing floating objects with a held ref. - Object = GObject.InitiallyUnowned - ObjectRef = StrongRef - - def test_vfunc_return_object_transfer_none_with_held_floating(self): - # Python holds onto the wrapper which basically means the floating ref - # should also be owned by python. - - vfuncs = self.VFuncs() - ref_count, is_floating = vfuncs.get_ref_info_for_vfunc_return_object_transfer_none() - - # This is a borrowed ref from what is held in python. - self.assertEqual(ref_count, 1) - self.assertFalse(is_floating) - - # The actual grefcount should stay at 1 even after the vfunc return. - self.assertEqual(vfuncs.object_ref().__grefcount__, 1) - - held_object_ref = weakref.ref(vfuncs.object_ref) - del vfuncs.object_ref - gc.collect() - self.assertTrue(held_object_ref() is None) - - def test_vfunc_out_object_transfer_none_with_held_floating(self): - # Same as above - - vfuncs = self.VFuncs() - ref_count, is_floating = vfuncs.get_ref_info_for_vfunc_out_object_transfer_none() - - self.assertEqual(ref_count, 1) - self.assertFalse(is_floating) - - self.assertEqual(vfuncs.object_ref().__grefcount__, 1) - - held_object_ref = weakref.ref(vfuncs.object_ref) - del vfuncs.object_ref - gc.collect() - self.assertTrue(held_object_ref() is None) - - def test_vfunc_return_object_transfer_full_with_held_floating(self): - vfuncs = self.VFuncs() - ref_count, is_floating = vfuncs.get_ref_info_for_vfunc_return_object_transfer_full() - - # Ref count from the perspective of C after the vfunc is called - self.assertEqual(ref_count, 2) - self.assertFalse(is_floating) - - # Current ref count - # vfunc wrapper destroyes ref it was given - self.assertEqual(vfuncs.object_ref().__grefcount__, 1) - - held_object_ref = weakref.ref(vfuncs.object_ref) - del vfuncs.object_ref - gc.collect() - self.assertTrue(held_object_ref() is None) - - def test_vfunc_out_object_transfer_full_with_held_floating(self): - # Same test as above except uses out arg instead of return - vfuncs = self.VFuncs() - ref_count, is_floating = vfuncs.get_ref_info_for_vfunc_out_object_transfer_full() - - # Ref count from the perspective of C after the vfunc is called - self.assertEqual(ref_count, 2) - self.assertFalse(is_floating) - - # Current ref count - # vfunc wrapper destroyes ref it was given - self.assertEqual(vfuncs.object_ref().__grefcount__, 1) - - held_object_ref = weakref.ref(vfuncs.object_ref()) - del vfuncs.object_ref - gc.collect() - self.assertTrue(held_object_ref() is None) - - def test_vfunc_in_floating_transfer_none_with_held_floating(self): - vfuncs = self.VFuncs() - ref_count, is_floating = vfuncs.get_ref_info_for_vfunc_in_object_transfer_none(self.VFuncs.Object) - gc.collect() - - # Ref count inside vfunc from the perspective of Python - self.assertTrue(vfuncs.in_object_is_floating) - self.assertEqual(vfuncs.in_object_grefcount, 2) # python wrapper sinks and owns the gobject - - # Ref count from the perspective of C after the vfunc is called - self.assertTrue(is_floating) - self.assertEqual(ref_count, 2) # floating + held by wrapper - - # Current ref count after C cleans up its reference - self.assertEqual(vfuncs.object_ref().__grefcount__, 1) - - held_object_ref = weakref.ref(vfuncs.object_ref()) - del vfuncs.object_ref - gc.collect() - self.assertTrue(held_object_ref() is None) - - def test_vfunc_in_floating_transfer_full_with_held_floating(self): - vfuncs = self.VFuncs() - ref_count, is_floating = vfuncs.get_ref_info_for_vfunc_in_object_transfer_full(self.VFuncs.Object) - gc.collect() - - # Ref count from the perspective of C after the vfunc is called - self.assertEqual(vfuncs.in_object_grefcount, 1) # python wrapper sinks and owns the gobject - self.assertFalse(vfuncs.in_object_is_floating) - - # Ref count from the perspective of C after the vfunc is called - self.assertEqual(ref_count, 1) # held by wrapper - self.assertFalse(is_floating) - - # Current ref count - self.assertEqual(vfuncs.object_ref().__grefcount__, 1) - - held_object_ref = weakref.ref(vfuncs.object_ref()) - del vfuncs.object_ref - gc.collect() - self.assertTrue(held_object_ref() is None) - - -@unittest.skipIf(Regress is None, 'Regress is required') -class TestArgumentTypeErrors(unittest.TestCase): - def test_object_argument_type_error(self): - # ensure TypeError is raised for things which are not GObjects - obj = Regress.TestObj() - obj.set_bare(GObject.Object()) - obj.set_bare(None) - - self.assertRaises(TypeError, obj.set_bare, object()) - self.assertRaises(TypeError, obj.set_bare, 42) - self.assertRaises(TypeError, obj.set_bare, 'not an object') - - def test_instance_argument_error(self): - # ensure TypeError is raised for non Regress.TestObj instances. - obj = Regress.TestObj() - self.assertEqual(Regress.TestObj.instance_method(obj), -1) - self.assertRaises(TypeError, Regress.TestObj.instance_method, object()) - self.assertRaises(TypeError, Regress.TestObj.instance_method, GObject.Object()) - self.assertRaises(TypeError, Regress.TestObj.instance_method, 42) - self.assertRaises(TypeError, Regress.TestObj.instance_method, 'not an object') - - def test_instance_argument_base_type_error(self): - # ensure TypeError is raised when a base type is passed to something - # expecting a derived type - obj = Regress.TestSubObj() - self.assertEqual(Regress.TestSubObj.instance_method(obj), 0) - self.assertRaises(TypeError, Regress.TestSubObj.instance_method, GObject.Object()) - self.assertRaises(TypeError, Regress.TestSubObj.instance_method, Regress.TestObj()) diff --git a/tests/test_option.py b/tests/test_option.py index fe25746..7f63173 100644 --- a/tests/test_option.py +++ b/tests/test_option.py @@ -10,17 +10,19 @@ try: except ImportError: from io import StringIO -from gi.repository import GLib +# FIXME: we need a way to import the options module from a public module +from gi._glib.option import OptionParser, OptionGroup, OptionValueError, \ + make_option, BadOptionError class TestOption(unittest.TestCase): EXCEPTION_MESSAGE = "This callback fails" def setUp(self): - self.parser = GLib.option.OptionParser("NAMES...", - description="Option unit test") + self.parser = OptionParser("NAMES...", + description="Option unit test") self.parser.add_option("-t", "--test", help="Unit test option", - action="store_false", dest="test", default=True) + action="store_false", dest="test", default=True) self.parser.add_option("--g-fatal-warnings", action="store_true", dest="fatal_warnings", @@ -30,22 +32,22 @@ class TestOption(unittest.TestCase): def option_callback(option, opt, value, parser): raise Exception(self.EXCEPTION_MESSAGE) - group = GLib.option.OptionGroup( + group = OptionGroup( "unittest", "Unit test options", "Show all unittest options", option_list=[ - GLib.option.make_option("-f", "-u", "--file", "--unit-file", - type="filename", - dest="unit_file", - help="Unit test option"), - GLib.option.make_option("--test-integer", - type="int", - dest="test_integer", - help="Unit integer option"), - GLib.option.make_option("--callback-failure-test", - action="callback", - callback=option_callback, - dest="test_integer", - help="Unit integer option"), + make_option("-f", "-u", "--file", "--unit-file", + type="filename", + dest="unit_file", + help="Unit test option"), + make_option("--test-integer", + type="int", + dest="test_integer", + help="Unit integer option"), + make_option("--callback-failure-test", + action="callback", + callback=option_callback, + dest="test_integer", + help="Unit integer option"), ]) group.add_option("-t", "--test", action="store_false", @@ -55,7 +57,7 @@ class TestOption(unittest.TestCase): self.parser.add_option_group(group) return group - def test_parse_args(self): + def testParseArgs(self): options, args = self.parser.parse_args( ["test_option.py"]) self.assertFalse(args) @@ -68,12 +70,12 @@ class TestOption(unittest.TestCase): ["test_option.py", "foo", "bar"]) self.assertEqual(args, []) - def test_parse_args_double_dash(self): + def testParseArgsDoubleDash(self): options, args = self.parser.parse_args( ["test_option.py", "--", "-xxx"]) - # self.assertEqual(args, ["-xxx"]) + #self.assertEqual(args, ["-xxx"]) - def test_parse_args_group(self): + def testParseArgsGroup(self): group = self._create_group() options, args = self.parser.parse_args( @@ -87,20 +89,20 @@ class TestOption(unittest.TestCase): self.assertEqual(group.values.unit_file, "test") self.assertFalse(args) - def test_option_value_error(self): + def testOptionValueError(self): self._create_group() - self.assertRaises(GLib.option.OptionValueError, self.parser.parse_args, + self.assertRaises(OptionValueError, self.parser.parse_args, ["test_option.py", "--test-integer=text"]) - def test_bad_option_error(self): - self.assertRaises(GLib.option.BadOptionError, + def testBadOptionError(self): + self.assertRaises(BadOptionError, self.parser.parse_args, ["test_option.py", "--unknwon-option"]) - def test_option_group_constructor(self): - self.assertRaises(TypeError, GLib.option.OptionGroup) + def testOptionGroupConstructor(self): + self.assertRaises(TypeError, OptionGroup) - def test_standard_error(self): + def testStandardError(self): self._create_group() sio = StringIO() old_stderr = sys.stderr diff --git a/tests/test_overrides_gtk.py b/tests/test_overrides.py index 61b7dc0..aef20e8 100644 --- a/tests/test_overrides_gtk.py +++ b/tests/test_overrides.py @@ -1,64 +1,580 @@ # -*- Mode: Python; py-indent-offset: 4 -*- -# coding: UTF-8 # vim: tabstop=4 shiftwidth=4 expandtab -import contextlib import unittest -import time -import sys -import warnings - -from helper import ignore_gi_deprecation_warnings, capture_glib_warnings -import gi.overrides +import sys +sys.path.insert(0, "../") + +from compathelper import _long, _unicode, _bytes + +from gi.repository import GLib +from gi.repository import GObject +from gi.repository import Gdk +from gi.repository import Gtk +from gi.repository import Gio +from gi.repository import Pango +from gi.repository import GdkPixbuf +import gi.overrides as overrides import gi.types -from gi.repository import GLib, GObject - -try: - from gi.repository import Gtk, GdkPixbuf, Gdk - PyGTKDeprecationWarning = Gtk.PyGTKDeprecationWarning -except ImportError: - Gtk = None - PyGTKDeprecationWarning = None - GdkPixbuf = None - Gdk = None - -@contextlib.contextmanager -def realized(widget): - """Makes sure the widget is realized. - view = Gtk.TreeView() - with realized(view): - do_something(view) - """ +class TestRegistry(unittest.TestCase): - if isinstance(widget, Gtk.Window): - toplevel = widget - else: - toplevel = widget.get_parent_window() - - if toplevel is None: - window = Gtk.Window() - window.add(widget) - - widget.realize() - while Gtk.events_pending(): - Gtk.main_iteration() - assert widget.get_realized() - yield widget + def test_non_gi(self): + class MyClass: + pass - if toplevel is None: - window.remove(widget) - window.destroy() + try: + overrides.override(MyClass) + self.fail('unexpected success of overriding non-GI class') + except TypeError as e: + self.assertTrue('Can not override a type MyClass' in str(e)) + + +class TestGLib(unittest.TestCase): + + def test_gvariant_create(self): + # simple values + + variant = GLib.Variant('i', 42) + self.assertTrue(isinstance(variant, GLib.Variant)) + self.assertEqual(variant.get_int32(), 42) + + variant = GLib.Variant('s', '') + self.assertTrue(isinstance(variant, GLib.Variant)) + self.assertEqual(variant.get_string(), '') + + variant = GLib.Variant('s', 'hello') + self.assertTrue(isinstance(variant, GLib.Variant)) + self.assertEqual(variant.get_string(), 'hello') + + # boxed variant + variant = GLib.Variant('v', GLib.Variant('i', 42)) + self.assertTrue(isinstance(variant, GLib.Variant)) + self.assertTrue(isinstance(variant.get_variant(), GLib.Variant)) + self.assertEqual(variant.get_type_string(), 'v') + self.assertEqual(variant.get_variant().get_type_string(), 'i') + self.assertEqual(variant.get_variant().get_int32(), 42) + + variant = GLib.Variant('v', GLib.Variant('v', GLib.Variant('i', 42))) + self.assertEqual(variant.get_type_string(), 'v') + self.assertEqual(variant.get_variant().get_type_string(), 'v') + self.assertEqual(variant.get_variant().get_variant().get_type_string(), 'i') + self.assertEqual(variant.get_variant().get_variant().get_int32(), 42) + + # tuples + + variant = GLib.Variant('()', ()) + self.assertEqual(variant.get_type_string(), '()') + self.assertEqual(variant.n_children(), 0) + + variant = GLib.Variant('(i)', (3,)) + self.assertEqual(variant.get_type_string(), '(i)') + self.assertTrue(isinstance(variant, GLib.Variant)) + self.assertEqual(variant.n_children(), 1) + self.assertTrue(isinstance(variant.get_child_value(0), GLib.Variant)) + self.assertEqual(variant.get_child_value(0).get_int32(), 3) + + variant = GLib.Variant('(ss)', ('mec', 'mac')) + self.assertEqual(variant.get_type_string(), '(ss)') + self.assertTrue(isinstance(variant, GLib.Variant)) + self.assertTrue(isinstance(variant.get_child_value(0), GLib.Variant)) + self.assertTrue(isinstance(variant.get_child_value(1), GLib.Variant)) + self.assertEqual(variant.get_child_value(0).get_string(), 'mec') + self.assertEqual(variant.get_child_value(1).get_string(), 'mac') + + # nested tuples + variant = GLib.Variant('((si)(ub))', (('hello', -1), (42, True))) + self.assertEqual(variant.get_type_string(), '((si)(ub))') + self.assertEqual(variant.unpack(), (('hello', -1), (_long(42), True))) + + # dictionaries + + variant = GLib.Variant('a{si}', {}) + self.assertTrue(isinstance(variant, GLib.Variant)) + self.assertEqual(variant.get_type_string(), 'a{si}') + self.assertEqual(variant.n_children(), 0) + + variant = GLib.Variant('a{si}', {'': 1, 'key1': 2, 'key2': 3}) + self.assertEqual(variant.get_type_string(), 'a{si}') + self.assertTrue(isinstance(variant, GLib.Variant)) + self.assertTrue(isinstance(variant.get_child_value(0), GLib.Variant)) + self.assertTrue(isinstance(variant.get_child_value(1), GLib.Variant)) + self.assertTrue(isinstance(variant.get_child_value(2), GLib.Variant)) + self.assertEqual(variant.unpack(), {'': 1, 'key1': 2, 'key2': 3}) + + # nested dictionaries + variant = GLib.Variant('a{sa{si}}', {}) + self.assertTrue(isinstance(variant, GLib.Variant)) + self.assertEqual(variant.get_type_string(), 'a{sa{si}}') + self.assertEqual(variant.n_children(), 0) + + d = {'': {'': 1, 'keyn1': 2}, + 'key1': {'key11': 11, 'key12': 12}} + variant = GLib.Variant('a{sa{si}}', d) + self.assertEqual(variant.get_type_string(), 'a{sa{si}}') + self.assertTrue(isinstance(variant, GLib.Variant)) + self.assertEqual(variant.unpack(), d) + + # arrays + + variant = GLib.Variant('ai', []) + self.assertEqual(variant.get_type_string(), 'ai') + self.assertEqual(variant.n_children(), 0) + + variant = GLib.Variant('ai', [1, 2]) + self.assertEqual(variant.get_type_string(), 'ai') + self.assertTrue(isinstance(variant, GLib.Variant)) + self.assertTrue(isinstance(variant.get_child_value(0), GLib.Variant)) + self.assertTrue(isinstance(variant.get_child_value(1), GLib.Variant)) + self.assertEqual(variant.get_child_value(0).get_int32(), 1) + self.assertEqual(variant.get_child_value(1).get_int32(), 2) + + variant = GLib.Variant('as', []) + self.assertEqual(variant.get_type_string(), 'as') + self.assertEqual(variant.n_children(), 0) + + variant = GLib.Variant('as', ['']) + self.assertEqual(variant.get_type_string(), 'as') + self.assertTrue(isinstance(variant, GLib.Variant)) + self.assertTrue(isinstance(variant.get_child_value(0), GLib.Variant)) + self.assertEqual(variant.get_child_value(0).get_string(), '') + + variant = GLib.Variant('as', ['hello', 'world']) + self.assertEqual(variant.get_type_string(), 'as') + self.assertTrue(isinstance(variant, GLib.Variant)) + self.assertTrue(isinstance(variant.get_child_value(0), GLib.Variant)) + self.assertTrue(isinstance(variant.get_child_value(1), GLib.Variant)) + self.assertEqual(variant.get_child_value(0).get_string(), 'hello') + self.assertEqual(variant.get_child_value(1).get_string(), 'world') + + # nested arrays + variant = GLib.Variant('aai', []) + self.assertEqual(variant.get_type_string(), 'aai') + self.assertEqual(variant.n_children(), 0) + + variant = GLib.Variant('aai', [[]]) + self.assertEqual(variant.get_type_string(), 'aai') + self.assertEqual(variant.n_children(), 1) + self.assertEqual(variant.get_child_value(0).n_children(), 0) + + variant = GLib.Variant('aai', [[1, 2], [3, 4, 5]]) + self.assertEqual(variant.get_type_string(), 'aai') + self.assertEqual(variant.unpack(), [[1, 2], [3, 4, 5]]) + + # + # complex types + # + + variant = GLib.Variant('(as)', ([],)) + self.assertEqual(variant.get_type_string(), '(as)') + self.assertEqual(variant.n_children(), 1) + self.assertEqual(variant.get_child_value(0).n_children(), 0) + + variant = GLib.Variant('(as)', ([''],)) + self.assertEqual(variant.get_type_string(), '(as)') + self.assertEqual(variant.n_children(), 1) + self.assertEqual(variant.get_child_value(0).n_children(), 1) + self.assertEqual(variant.get_child_value(0).get_child_value(0).get_string(), '') + + variant = GLib.Variant('(as)', (['hello'],)) + self.assertEqual(variant.get_type_string(), '(as)') + self.assertEqual(variant.n_children(), 1) + self.assertEqual(variant.get_child_value(0).n_children(), 1) + self.assertEqual(variant.get_child_value(0).get_child_value(0).get_string(), 'hello') + + obj = {'a1': (1, True), 'a2': (2, False)} + variant = GLib.Variant('a{s(ib)}', obj) + self.assertEqual(variant.get_type_string(), 'a{s(ib)}') + self.assertEqual(variant.unpack(), obj) + + obj = {'a1': (1, GLib.Variant('b', True)), 'a2': (2, GLib.Variant('y', 255))} + variant = GLib.Variant('a{s(iv)}', obj) + self.assertEqual(variant.get_type_string(), 'a{s(iv)}') + self.assertEqual(variant.unpack(), {'a1': (1, True), 'a2': (2, 255)}) + + obj = (1, {'a': {'a1': True, 'a2': False}, + 'b': {'b1': False}, + 'c': {} + }, + 'foo') + variant = GLib.Variant('(ia{sa{sb}}s)', obj) + self.assertEqual(variant.get_type_string(), '(ia{sa{sb}}s)') + self.assertEqual(variant.unpack(), obj) + + obj = {"frequency": GLib.Variant('t', 738000000), + "hierarchy": GLib.Variant('i', 0), + "bandwidth": GLib.Variant('x', 8), + "code-rate-hp": GLib.Variant('d', 2.0 / 3.0), + "constellation": GLib.Variant('s', "QAM16"), + "guard-interval": GLib.Variant('u', 4)} + variant = GLib.Variant('a{sv}', obj) + self.assertEqual(variant.get_type_string(), 'a{sv}') + self.assertEqual(variant.unpack(), {"frequency": 738000000, + "hierarchy": 0, + "bandwidth": 8, + "code-rate-hp": 2.0 / 3.0, + "constellation": "QAM16", + "guard-interval": 4}) + + def test_gvariant_create_errors(self): + # excess arguments + self.assertRaises(TypeError, GLib.Variant, 'i', 42, 3) + self.assertRaises(TypeError, GLib.Variant, '(i)', (42, 3)) + + # not enough arguments + self.assertRaises(TypeError, GLib.Variant, '(ii)', (42,)) + + # data type mismatch + self.assertRaises(TypeError, GLib.Variant, 'i', 'hello') + self.assertRaises(TypeError, GLib.Variant, 's', 42) + self.assertRaises(TypeError, GLib.Variant, '(ss)', 'mec', 'mac') + + # unimplemented data type + self.assertRaises(NotImplementedError, GLib.Variant, 'Q', 1) + + def test_gvariant_unpack(self): + # simple values + res = GLib.Variant.new_int32(-42).unpack() + self.assertEqual(res, -42) + + res = GLib.Variant.new_uint64(34359738368).unpack() + self.assertEqual(res, 34359738368) + + res = GLib.Variant.new_boolean(True).unpack() + self.assertEqual(res, True) + + res = GLib.Variant.new_object_path('/foo/Bar').unpack() + self.assertEqual(res, '/foo/Bar') + + # variant + res = GLib.Variant('v', GLib.Variant.new_int32(-42)).unpack() + self.assertEqual(res, -42) + + GLib.Variant('v', GLib.Variant('v', GLib.Variant('i', 42))) + self.assertEqual(res, -42) + + # tuple + res = GLib.Variant.new_tuple(GLib.Variant.new_int32(-1), + GLib.Variant.new_string('hello')).unpack() + self.assertEqual(res, (-1, 'hello')) + + # array + vb = GLib.VariantBuilder.new(gi._gi.variant_type_from_string('ai')) + vb.add_value(GLib.Variant.new_int32(-1)) + vb.add_value(GLib.Variant.new_int32(3)) + res = vb.end().unpack() + self.assertEqual(res, [-1, 3]) + + # dictionary + res = GLib.Variant('a{si}', {'key1': 1, 'key2': 2}).unpack() + self.assertEqual(res, {'key1': 1, 'key2': 2}) + + def test_gvariant_iteration(self): + # array index access + vb = GLib.VariantBuilder.new(gi._gi.variant_type_from_string('ai')) + vb.add_value(GLib.Variant.new_int32(-1)) + vb.add_value(GLib.Variant.new_int32(3)) + v = vb.end() + + self.assertEqual(len(v), 2) + self.assertEqual(v[0], -1) + self.assertEqual(v[1], 3) + self.assertEqual(v[-1], 3) + self.assertEqual(v[-2], -1) + self.assertRaises(IndexError, v.__getitem__, 2) + self.assertRaises(IndexError, v.__getitem__, -3) + self.assertRaises(ValueError, v.__getitem__, 'a') + + # array iteration + self.assertEqual([x for x in v], [-1, 3]) + self.assertEqual(list(v), [-1, 3]) + + # tuple index access + v = GLib.Variant.new_tuple(GLib.Variant.new_int32(-1), + GLib.Variant.new_string('hello')) + self.assertEqual(len(v), 2) + self.assertEqual(v[0], -1) + self.assertEqual(v[1], 'hello') + self.assertEqual(v[-1], 'hello') + self.assertEqual(v[-2], -1) + self.assertRaises(IndexError, v.__getitem__, 2) + self.assertRaises(IndexError, v.__getitem__, -3) + self.assertRaises(ValueError, v.__getitem__, 'a') + + # tuple iteration + self.assertEqual([x for x in v], [-1, 'hello']) + self.assertEqual(tuple(v), (-1, 'hello')) + + # dictionary index access + vsi = GLib.Variant('a{si}', {'key1': 1, 'key2': 2}) + vis = GLib.Variant('a{is}', {1: 'val1', 5: 'val2'}) + + self.assertEqual(len(vsi), 2) + self.assertEqual(vsi['key1'], 1) + self.assertEqual(vsi['key2'], 2) + self.assertRaises(KeyError, vsi.__getitem__, 'unknown') + + self.assertEqual(len(vis), 2) + self.assertEqual(vis[1], 'val1') + self.assertEqual(vis[5], 'val2') + self.assertRaises(KeyError, vsi.__getitem__, 3) + + # dictionary iteration + self.assertEqual(set(vsi.keys()), set(['key1', 'key2'])) + self.assertEqual(set(vis.keys()), set([1, 5])) + + # string index access + v = GLib.Variant('s', 'hello') + self.assertEqual(len(v), 5) + self.assertEqual(v[0], 'h') + self.assertEqual(v[4], 'o') + self.assertEqual(v[-1], 'o') + self.assertEqual(v[-5], 'h') + self.assertRaises(IndexError, v.__getitem__, 5) + self.assertRaises(IndexError, v.__getitem__, -6) + + # string iteration + self.assertEqual([x for x in v], ['h', 'e', 'l', 'l', 'o']) + + def test_variant_split_signature(self): + self.assertEqual(GLib.Variant.split_signature('()'), []) + + self.assertEqual(GLib.Variant.split_signature('s'), ['s']) + + self.assertEqual(GLib.Variant.split_signature('as'), ['as']) + + self.assertEqual(GLib.Variant.split_signature('(s)'), ['s']) + + self.assertEqual(GLib.Variant.split_signature('(iso)'), ['i', 's', 'o']) + + self.assertEqual(GLib.Variant.split_signature('(s(ss)i(ii))'), + ['s', '(ss)', 'i', '(ii)']) + + self.assertEqual(GLib.Variant.split_signature('(as)'), ['as']) + + self.assertEqual(GLib.Variant.split_signature('(s(ss)iaiaasa(ii))'), + ['s', '(ss)', 'i', 'ai', 'aas', 'a(ii)']) + + self.assertEqual(GLib.Variant.split_signature('(a{iv}(ii)((ss)a{s(ss)}))'), + ['a{iv}', '(ii)', '((ss)a{s(ss)})']) + + def test_variant_hash(self): + v1 = GLib.Variant('s', 'somestring') + v2 = GLib.Variant('s', 'somestring') + v3 = GLib.Variant('s', 'somestring2') + + self.assertTrue(v2 in set([v1, v3])) + self.assertTrue(v2 in frozenset([v1, v3])) + self.assertTrue(v2 in {v1: '1', v3: '2'}) + + def test_variant_compare(self): + # Check if identical GVariant are equal + + def assert_equal(vtype, value): + self.assertEqual(GLib.Variant(vtype, value), GLib.Variant(vtype, value)) + + def assert_not_equal(vtype1, value1, vtype2, value2): + self.assertNotEqual(GLib.Variant(vtype1, value1), GLib.Variant(vtype2, value2)) + + numbers = ['y', 'n', 'q', 'i', 'u', 'x', 't', 'h', 'd'] + for num in numbers: + assert_equal(num, 42) + assert_not_equal(num, 42, num, 41) + assert_not_equal(num, 42, 's', '42') + + assert_equal('s', 'something') + assert_not_equal('s', 'something', 's', 'somethingelse') + assert_not_equal('s', 'something', 'i', 1234) + + assert_equal('g', 'dustybinqhogx') + assert_not_equal('g', 'dustybinqhogx', 'g', 'dustybin') + assert_not_equal('g', 'dustybinqhogx', 'i', 1234) + + assert_equal('o', '/dev/null') + assert_not_equal('o', '/dev/null', 'o', '/dev/zero') + assert_not_equal('o', '/dev/null', 'i', 1234) + + assert_equal('(s)', ('strtuple',)) + assert_not_equal('(s)', ('strtuple',), '(s)', ('strtuple2',)) + + assert_equal('a{si}', {'str': 42}) + assert_not_equal('a{si}', {'str': 42}, 'a{si}', {'str': 43}) + + assert_equal('v', GLib.Variant('i', 42)) + assert_not_equal('v', GLib.Variant('i', 42), 'v', GLib.Variant('i', 43)) + + def test_variant_bool(self): + # Check if the GVariant bool matches the unpacked Pythonic bool + + def assert_equals_bool(vtype, value): + self.assertEqual(bool(GLib.Variant(vtype, value)), bool(value)) + + # simple values + assert_equals_bool('b', True) + assert_equals_bool('b', False) + + numbers = ['y', 'n', 'q', 'i', 'u', 'x', 't', 'h', 'd'] + for number in numbers: + assert_equals_bool(number, 0) + assert_equals_bool(number, 1) + + assert_equals_bool('s', '') + assert_equals_bool('g', '') + assert_equals_bool('s', 'something') + assert_equals_bool('o', '/dev/null') + assert_equals_bool('g', 'dustybinqhogx') + + # arrays + assert_equals_bool('ab', [True]) + assert_equals_bool('ab', [False]) + for number in numbers: + assert_equals_bool('a' + number, []) + assert_equals_bool('a' + number, [0]) + assert_equals_bool('as', []) + assert_equals_bool('as', ['']) + assert_equals_bool('ao', []) + assert_equals_bool('ao', ['/']) + assert_equals_bool('ag', []) + assert_equals_bool('ag', ['']) + assert_equals_bool('aai', [[]]) + + # tuples + assert_equals_bool('()', ()) + for number in numbers: + assert_equals_bool('(' + number + ')', (0,)) + assert_equals_bool('(s)', ('',)) + assert_equals_bool('(o)', ('/',)) + assert_equals_bool('(g)', ('',)) + assert_equals_bool('(())', ((),)) + + # dictionaries + assert_equals_bool('a{si}', {}) + assert_equals_bool('a{si}', {'': 0}) + + # complex types, always True + assert_equals_bool('(as)', ([],)) + assert_equals_bool('a{s(i)}', {'': (0,)}) + + # variant types, recursive unpacking + assert_equals_bool('v', GLib.Variant('i', 0)) + assert_equals_bool('v', GLib.Variant('i', 1)) + + +class TestPango(unittest.TestCase): + + def test_default_font_description(self): + desc = Pango.FontDescription() + self.assertEqual(desc.get_variant(), Pango.Variant.NORMAL) + + def test_font_description(self): + desc = Pango.FontDescription('monospace') + self.assertEqual(desc.get_family(), 'monospace') + self.assertEqual(desc.get_variant(), Pango.Variant.NORMAL) + + def test_layout(self): + self.assertRaises(TypeError, Pango.Layout) + context = Pango.Context() + layout = Pango.Layout(context) + self.assertEqual(layout.get_context(), context) + + layout.set_markup("Foobar") + self.assertEqual(layout.get_text(), "Foobar") + + +class TestGdk(unittest.TestCase): + + def test_constructor(self): + attribute = Gdk.WindowAttr() + attribute.window_type = Gdk.WindowType.CHILD + attributes_mask = Gdk.WindowAttributesType.X | \ + Gdk.WindowAttributesType.Y + window = Gdk.Window(None, attribute, attributes_mask) + self.assertEqual(window.get_window_type(), Gdk.WindowType.CHILD) + + def test_color(self): + color = Gdk.Color(100, 200, 300) + self.assertEqual(color.red, 100) + self.assertEqual(color.green, 200) + self.assertEqual(color.blue, 300) + self.assertEqual(color, Gdk.Color(100, 200, 300)) + self.assertNotEquals(color, Gdk.Color(1, 2, 3)) + + def test_rgba(self): + self.assertEqual(Gdk.RGBA, overrides.Gdk.RGBA) + rgba = Gdk.RGBA(0.1, 0.2, 0.3, 0.4) + self.assertEqual(rgba, Gdk.RGBA(0.1, 0.2, 0.3, 0.4)) + self.assertNotEquals(rgba, Gdk.RGBA(0.0, 0.2, 0.3, 0.4)) + self.assertEqual(rgba.red, 0.1) + self.assertEqual(rgba.green, 0.2) + self.assertEqual(rgba.blue, 0.3) + self.assertEqual(rgba.alpha, 0.4) + rgba.green = 0.9 + self.assertEqual(rgba.green, 0.9) + + def test_event(self): + event = Gdk.Event.new(Gdk.EventType.CONFIGURE) + self.assertEqual(event.type, Gdk.EventType.CONFIGURE) + self.assertEqual(event.send_event, 0) + + event = Gdk.Event.new(Gdk.EventType.DRAG_MOTION) + event.x_root, event.y_root = 0, 5 + self.assertEqual(event.x_root, 0) + self.assertEqual(event.y_root, 5) + + event = Gdk.Event() + event.type = Gdk.EventType.SCROLL + self.assertRaises(AttributeError, lambda: getattr(event, 'foo_bar')) + + def test_event_structures(self): + def button_press_cb(button, event): + self.assertTrue(isinstance(event, Gdk.EventButton)) + self.assertTrue(event.type == Gdk.EventType.BUTTON_PRESS) + self.assertEqual(event.send_event, 0) + self.assertEqual(event.get_state(), Gdk.ModifierType.CONTROL_MASK) + self.assertEqual(event.get_root_coords(), (2, 5)) + + event.time = 12345 + self.assertEqual(event.get_time(), 12345) - while Gtk.events_pending(): - Gtk.main_iteration() + w = Gtk.Window() + b = Gtk.Button() + b.connect('button-press-event', button_press_cb) + w.add(b) + w.show_all() + Gdk.test_simulate_button(b.get_window(), + 2, 5, + 0, + Gdk.ModifierType.CONTROL_MASK, + Gdk.EventType.BUTTON_PRESS) + + def test_cursor(self): + self.assertEqual(Gdk.Cursor, overrides.Gdk.Cursor) + c = Gdk.Cursor(Gdk.CursorType.WATCH) + self.assertNotEqual(c, None) + c = Gdk.Cursor(cursor_type=Gdk.CursorType.WATCH) + self.assertNotEqual(c, None) + + display_manager = Gdk.DisplayManager.get() + display = display_manager.get_default_display() + + test_pixbuf = GdkPixbuf.Pixbuf.new(GdkPixbuf.Colorspace.RGB, + False, + 8, + 5, + 10) + + c = Gdk.Cursor(display, + test_pixbuf, + y=0, x=0) + + self.assertNotEqual(c, None) + self.assertRaises(ValueError, Gdk.Cursor, 1, 2, 3) -@unittest.skipUnless(Gtk, 'Gtk not available') -@ignore_gi_deprecation_warnings class TestGtk(unittest.TestCase): + def test_container(self): box = Gtk.Box() self.assertTrue(isinstance(box, Gtk.Box)) @@ -73,29 +589,30 @@ class TestGtk(unittest.TestCase): self.assertTrue(label2 in box) self.assertEqual(len(box), 2) self.assertTrue(box) - labels = [x for x in box] - self.assertEqual(labels, [label, label2]) + l = [x for x in box] + self.assertEqual(l, [label, label2]) - @unittest.skipIf(Gtk._version == "4.0", "not in gtk4") def test_actions(self): - self.assertEqual(Gtk.Action, gi.overrides.Gtk.Action) - action = Gtk.Action(name="test", label="Test", tooltip="Test Action", stock_id=Gtk.STOCK_COPY) + self.assertEqual(Gtk.Action, overrides.Gtk.Action) + self.assertRaises(TypeError, Gtk.Action) + action = Gtk.Action("test", "Test", "Test Action", Gtk.STOCK_COPY) self.assertEqual(action.get_name(), "test") self.assertEqual(action.get_label(), "Test") self.assertEqual(action.get_tooltip(), "Test Action") self.assertEqual(action.get_stock_id(), Gtk.STOCK_COPY) - self.assertEqual(Gtk.RadioAction, gi.overrides.Gtk.RadioAction) - action = Gtk.RadioAction(name="test", label="Test", tooltip="Test Action", stock_id=Gtk.STOCK_COPY, value=1) + self.assertEqual(Gtk.RadioAction, overrides.Gtk.RadioAction) + self.assertRaises(TypeError, Gtk.RadioAction) + action = Gtk.RadioAction("test", "Test", "Test Action", Gtk.STOCK_COPY, 1) self.assertEqual(action.get_name(), "test") self.assertEqual(action.get_label(), "Test") self.assertEqual(action.get_tooltip(), "Test Action") self.assertEqual(action.get_stock_id(), Gtk.STOCK_COPY) self.assertEqual(action.get_current_value(), 1) - @unittest.skipIf(Gtk._version == "4.0", "not in gtk4") def test_actiongroup(self): - self.assertEqual(Gtk.ActionGroup, gi.overrides.Gtk.ActionGroup) + self.assertEqual(Gtk.ActionGroup, overrides.Gtk.ActionGroup) + self.assertRaises(TypeError, Gtk.ActionGroup) action_group = Gtk.ActionGroup(name='TestActionGroup') callback_data = "callback data" @@ -110,12 +627,12 @@ class TestGtk(unittest.TestCase): ('test-action1', None, 'Test Action 1', None, None, test_action_callback_data), ('test-action2', Gtk.STOCK_COPY, 'Test Action 2', - None, None, test_action_callback_data)], callback_data) + None, None, test_action_callback_data)], callback_data) action_group.add_toggle_actions([ ('test-toggle-action1', None, 'Test Toggle Action 1', None, None, test_action_callback_data, False), ('test-toggle-action2', Gtk.STOCK_COPY, 'Test Toggle Action 2', - None, None, test_action_callback_data, True)], callback_data) + None, None, test_action_callback_data, True)], callback_data) action_group.add_radio_actions([ ('test-radio-action1', None, 'Test Radio Action 1'), ('test-radio-action2', Gtk.STOCK_COPY, 'Test Radio Action 2')], 1, @@ -135,11 +652,12 @@ class TestGtk(unittest.TestCase): expected_results.remove(a) action.activate() - @unittest.skipIf(Gtk._version == "4.0", "not in gtk4") def test_uimanager(self): - self.assertEqual(Gtk.UIManager, gi.overrides.Gtk.UIManager) + self.assertEqual(Gtk.UIManager, overrides.Gtk.UIManager) ui = Gtk.UIManager() - ui.add_ui_from_string("""<ui> + ui.add_ui_from_string( +""" +<ui> <menubar name="menubar1"></menubar> </ui> """ @@ -155,141 +673,114 @@ class TestGtk(unittest.TestCase): self.assertEqual(ag, groups[-2]) self.assertEqual(ag2, groups[-1]) - @unittest.skipIf(Gtk._version == "4.0", "not in gtk4") - def test_uimanager_nonascii(self): - ui = Gtk.UIManager() - ui.add_ui_from_string(b'<ui><menubar name="menub\xc3\xa6r1" /></ui>'.decode('UTF-8')) - mi = ui.get_widget("/menubær1") - self.assertEqual(type(mi), Gtk.MenuBar) + def test_builder(self): + self.assertEqual(Gtk.Builder, overrides.Gtk.Builder) - def test_window(self): - # standard Window - w = Gtk.Window() - self.assertEqual(w.get_property('type'), Gtk.WindowType.TOPLEVEL) + class SignalTest(GObject.GObject): + __gtype_name__ = "GIOverrideSignalTest" + __gsignals__ = { + "test-signal": (GObject.SignalFlags.RUN_FIRST, + None, + []), + } + + class SignalCheck: + def __init__(self): + self.sentinel = 0 + self.after_sentinel = 0 + + def on_signal_1(self, *args): + self.sentinel += 1 + self.after_sentinel += 1 - # type works as keyword argument - w = Gtk.Window(type=Gtk.WindowType.POPUP) - self.assertEqual(w.get_property('type'), Gtk.WindowType.POPUP) + def on_signal_3(self, *args): + self.sentinel += 3 - class TestWindow(Gtk.Window): - __gtype_name__ = "TestWindow" + def on_signal_after(self, *args): + if self.after_sentinel == 1: + self.after_sentinel += 1 - # works from builder + signal_checker = SignalCheck() builder = Gtk.Builder() - builder.add_from_string(''' + + # add object1 to the builder + builder.add_from_string( +""" <interface> - <object class="GtkWindow" id="win"> - <property name="type">popup</property> + <object class="GIOverrideSignalTest" id="object1"> + <signal name="test-signal" after="yes" handler="on_signal_after" /> + <signal name="test-signal" handler="on_signal_1" /> </object> - <object class="TestWindow" id="testwin"> +</interface> +""") + + # only add object3 to the builder + builder.add_objects_from_string( +""" +<interface> + <object class="GIOverrideSignalTest" id="object2"> + <signal name="test-signal" handler="on_signal_2" /> </object> - <object class="TestWindow" id="testpop"> - <property name="type">popup</property> + <object class="GIOverrideSignalTest" id="object3"> + <signal name="test-signal" handler="on_signal_3" /> </object> -</interface>''') - self.assertEqual(builder.get_object('win').get_property('type'), - Gtk.WindowType.POPUP) - self.assertEqual(builder.get_object('testwin').get_property('type'), - Gtk.WindowType.TOPLEVEL) - self.assertEqual(builder.get_object('testpop').get_property('type'), - Gtk.WindowType.POPUP) - - def test_dialog_classes(self): - self.assertEqual(Gtk.Dialog, gi.overrides.Gtk.Dialog) - self.assertEqual(Gtk.FileChooserDialog, gi.overrides.Gtk.FileChooserDialog) - self.assertEqual(Gtk.RecentChooserDialog, gi.overrides.Gtk.RecentChooserDialog) - if Gtk._version != "4.0": - self.assertEqual(Gtk.ColorSelectionDialog, gi.overrides.Gtk.ColorSelectionDialog) - self.assertEqual(Gtk.FontSelectionDialog, gi.overrides.Gtk.FontSelectionDialog) - - def test_dialog_base(self): - dialog = Gtk.Dialog(title='Foo', modal=True) + <object class="GIOverrideSignalTest" id="object4"> + <signal name="test-signal" handler="on_signal_4" /> + </object> +</interface> + +""", + ['object3']) + + # hook up signals + builder.connect_signals(signal_checker) + + # call their notify signals and check sentinel + objects = builder.get_objects() + self.assertEqual(len(objects), 2) + for obj in objects: + obj.emit('test-signal') + + self.assertEqual(signal_checker.sentinel, 4) + self.assertEqual(signal_checker.after_sentinel, 2) + + def test_dialogs(self): + self.assertEqual(Gtk.Dialog, overrides.Gtk.Dialog) + self.assertEqual(Gtk.AboutDialog, overrides.Gtk.AboutDialog) + self.assertEqual(Gtk.MessageDialog, overrides.Gtk.MessageDialog) + self.assertEqual(Gtk.ColorSelectionDialog, overrides.Gtk.ColorSelectionDialog) + self.assertEqual(Gtk.FileChooserDialog, overrides.Gtk.FileChooserDialog) + self.assertEqual(Gtk.FontSelectionDialog, overrides.Gtk.FontSelectionDialog) + self.assertEqual(Gtk.RecentChooserDialog, overrides.Gtk.RecentChooserDialog) + + # Gtk.Dialog + dialog = Gtk.Dialog(title='Foo', + flags=Gtk.DialogFlags.MODAL, + buttons=('test-button1', 1)) self.assertTrue(isinstance(dialog, Gtk.Dialog)) self.assertTrue(isinstance(dialog, Gtk.Window)) + + dialog.add_buttons('test-button2', 2, Gtk.STOCK_CLOSE, Gtk.ResponseType.CLOSE) + self.assertEqual('Foo', dialog.get_title()) self.assertTrue(dialog.get_modal()) - - def test_dialog_deprecations(self): - with warnings.catch_warnings(record=True) as warn: - warnings.simplefilter('always') - dialog = Gtk.Dialog(title='Foo', flags=Gtk.DialogFlags.MODAL) - self.assertTrue(dialog.get_modal()) - self.assertEqual(len(warn), 1) - self.assertTrue(issubclass(warn[0].category, PyGTKDeprecationWarning)) - self.assertRegexpMatches(str(warn[0].message), - '.*flags.*modal.*') - - with warnings.catch_warnings(record=True) as warn: - warnings.simplefilter('always') - dialog = Gtk.Dialog(title='Foo', flags=Gtk.DialogFlags.DESTROY_WITH_PARENT) - self.assertTrue(dialog.get_destroy_with_parent()) - self.assertEqual(len(warn), 1) - self.assertTrue(issubclass(warn[0].category, PyGTKDeprecationWarning)) - self.assertRegexpMatches(str(warn[0].message), - '.*flags.*destroy_with_parent.*') - - def test_dialog_deprecation_stacklevels(self): - # Test warning levels are setup to give the correct filename for - # deprecations in different classes in the inheritance hierarchy. - - # Base class - self.assertEqual(Gtk.Dialog, gi.overrides.Gtk.Dialog) - with warnings.catch_warnings(record=True) as warn: - warnings.simplefilter('always') - Gtk.Dialog(flags=Gtk.DialogFlags.MODAL) - self.assertEqual(len(warn), 1) - self.assertRegexpMatches(warn[0].filename, '.*test_overrides_gtk.*') - - # Validate overridden base with overridden sub-class. - self.assertEqual(Gtk.MessageDialog, gi.overrides.Gtk.MessageDialog) - with warnings.catch_warnings(record=True) as warn: - warnings.simplefilter('always') - Gtk.MessageDialog(flags=Gtk.DialogFlags.MODAL) - self.assertEqual(len(warn), 1) - self.assertRegexpMatches(warn[0].filename, '.*test_overrides_gtk.*') - - # Validate overridden base with non-overridden sub-class. - self.assertEqual(Gtk.AboutDialog, gi.repository.Gtk.AboutDialog) - with warnings.catch_warnings(record=True) as warn: - warnings.simplefilter('always') - Gtk.AboutDialog(flags=Gtk.DialogFlags.MODAL) - self.assertEqual(len(warn), 1) - self.assertRegexpMatches(warn[0].filename, '.*test_overrides_gtk.*') - - def test_dialog_add_buttons(self): - # The overloaded "buttons" keyword gives a warning when attempting - # to use it for adding buttons as was available in PyGTK. - with warnings.catch_warnings(record=True) as warn: - warnings.simplefilter('always') - dialog = Gtk.Dialog(title='Foo', modal=True, - buttons=('test-button1', 1)) - self.assertEqual(len(warn), 1) - self.assertTrue(issubclass(warn[0].category, PyGTKDeprecationWarning)) - self.assertRegexpMatches(str(warn[0].message), - '.*ButtonsType.*add_buttons.*') - - dialog.add_buttons('test-button2', 2, 'gtk-close', Gtk.ResponseType.CLOSE) button = dialog.get_widget_for_response(1) self.assertEqual('test-button1', button.get_label()) button = dialog.get_widget_for_response(2) self.assertEqual('test-button2', button.get_label()) button = dialog.get_widget_for_response(Gtk.ResponseType.CLOSE) - self.assertEqual('gtk-close', button.get_label()) + self.assertEqual(Gtk.STOCK_CLOSE, button.get_label()) - def test_about_dialog(self): + # Gtk.AboutDialog dialog = Gtk.AboutDialog() self.assertTrue(isinstance(dialog, Gtk.Dialog)) self.assertTrue(isinstance(dialog, Gtk.Window)) - # AboutDialog is not sub-classed in overrides, make sure - # the mro still injects the base class "add_buttons" override. - self.assertTrue(hasattr(dialog, 'add_buttons')) - - def test_message_dialog(self): + # Gtk.MessageDialog dialog = Gtk.MessageDialog(title='message dialog test', - modal=True, + flags=Gtk.DialogFlags.MODAL, buttons=Gtk.ButtonsType.OK, - text='dude!') + message_format='dude!') self.assertTrue(isinstance(dialog, Gtk.Dialog)) self.assertTrue(isinstance(dialog, Gtk.Window)) @@ -306,48 +797,52 @@ class TestGtk(unittest.TestCase): self.assertEqual(dialog.get_property('secondary-text'), '2nd markup') self.assertTrue(dialog.get_property('secondary-use-markup')) - @unittest.skipIf(Gtk._version == "4.0", "not in gtk4") - def test_color_selection_dialog(self): - dialog = Gtk.ColorSelectionDialog(title="color selection dialog test") + # Gtk.ColorSelectionDialog + dialog = Gtk.ColorSelectionDialog("color selection dialog test") self.assertTrue(isinstance(dialog, Gtk.Dialog)) self.assertTrue(isinstance(dialog, Gtk.Window)) self.assertEqual('color selection dialog test', dialog.get_title()) - def test_file_chooser_dialog(self): - # might cause a GVFS warning, do not break on this - with capture_glib_warnings(allow_warnings=True): - dialog = Gtk.FileChooserDialog(title='file chooser dialog test', - action=Gtk.FileChooserAction.SAVE) - + # Gtk.FileChooserDialog + dialog = Gtk.FileChooserDialog(title='file chooser dialog test', + buttons=('test-button1', 1), + action=Gtk.FileChooserAction.SAVE) self.assertTrue(isinstance(dialog, Gtk.Dialog)) self.assertTrue(isinstance(dialog, Gtk.Window)) - self.assertEqual('file chooser dialog test', dialog.get_title()) + dialog.add_buttons('test-button2', 2, Gtk.STOCK_CLOSE, Gtk.ResponseType.CLOSE) + self.assertEqual('file chooser dialog test', dialog.get_title()) + button = dialog.get_widget_for_response(1) + self.assertEqual('test-button1', button.get_label()) + button = dialog.get_widget_for_response(2) + self.assertEqual('test-button2', button.get_label()) + button = dialog.get_widget_for_response(Gtk.ResponseType.CLOSE) + self.assertEqual(Gtk.STOCK_CLOSE, button.get_label()) action = dialog.get_property('action') self.assertEqual(Gtk.FileChooserAction.SAVE, action) - def test_file_chooser_dialog_default_action(self): - # might cause a GVFS warning, do not break on this - with capture_glib_warnings(allow_warnings=True): - dialog = Gtk.FileChooserDialog(title='file chooser dialog test') - - action = dialog.get_property('action') - self.assertEqual(Gtk.FileChooserAction.OPEN, action) - - @unittest.skipIf(Gtk._version == "4.0", "not in gtk4") - def test_font_selection_dialog(self): - dialog = Gtk.FontSelectionDialog(title="font selection dialog test") + # Gtk.FontSelectionDialog + dialog = Gtk.ColorSelectionDialog("font selection dialog test") self.assertTrue(isinstance(dialog, Gtk.Dialog)) self.assertTrue(isinstance(dialog, Gtk.Window)) self.assertEqual('font selection dialog test', dialog.get_title()) - def test_recent_chooser_dialog(self): + # Gtk.RecentChooserDialog test_manager = Gtk.RecentManager() dialog = Gtk.RecentChooserDialog(title='recent chooser dialog test', - recent_manager=test_manager) + buttons=('test-button1', 1), + manager=test_manager) self.assertTrue(isinstance(dialog, Gtk.Dialog)) self.assertTrue(isinstance(dialog, Gtk.Window)) + + dialog.add_buttons('test-button2', 2, Gtk.STOCK_CLOSE, Gtk.ResponseType.CLOSE) self.assertEqual('recent chooser dialog test', dialog.get_title()) + button = dialog.get_widget_for_response(1) + self.assertEqual('test-button1', button.get_label()) + button = dialog.get_widget_for_response(2) + self.assertEqual('test-button2', button.get_label()) + button = dialog.get_widget_for_response(Gtk.ResponseType.CLOSE) + self.assertEqual(Gtk.STOCK_CLOSE, button.get_label()) class TestClass(GObject.GObject): __gtype_name__ = "GIOverrideTreeAPITest" @@ -362,532 +857,11 @@ class TestGtk(unittest.TestCase): self.tester.assertEqual(int_value, self.int_value) self.tester.assertEqual(string_value, self.string_value) - def test_buttons(self): - self.assertEqual(Gtk.Button, gi.overrides.Gtk.Button) - - # test Gtk.Button - button = Gtk.Button() - self.assertTrue(isinstance(button, Gtk.Button)) - self.assertTrue(isinstance(button, Gtk.Container)) - self.assertTrue(isinstance(button, Gtk.Widget)) - - if Gtk._version != "4.0": - # Using stock items causes hard warning in devel versions of GTK+. - with capture_glib_warnings(allow_warnings=True): - button = Gtk.Button.new_from_stock(Gtk.STOCK_CLOSE) - - self.assertEqual(Gtk.STOCK_CLOSE, button.get_label()) - self.assertTrue(button.get_use_stock()) - self.assertTrue(button.get_use_underline()) - - # test Gtk.Button use_stock - button = Gtk.Button(label=Gtk.STOCK_CLOSE, use_stock=True, - use_underline=True) - self.assertEqual(Gtk.STOCK_CLOSE, button.get_label()) - self.assertTrue(button.get_use_stock()) - self.assertTrue(button.get_use_underline()) - - # test Gtk.LinkButton - button = Gtk.LinkButton(uri='http://www.Gtk.org', label='Gtk') - self.assertTrue(isinstance(button, Gtk.Button)) - self.assertTrue(isinstance(button, Gtk.Container)) - self.assertTrue(isinstance(button, Gtk.Widget)) - self.assertEqual('http://www.Gtk.org', button.get_uri()) - self.assertEqual('Gtk', button.get_label()) - - def test_inheritance(self): - for name in gi.overrides.Gtk.__all__: - over = getattr(gi.overrides.Gtk, name) - for element in dir(Gtk): - try: - klass = getattr(Gtk, element) - info = klass.__info__ - except (NotImplementedError, AttributeError): - continue - - # Get all parent classes and interfaces klass inherits from - if isinstance(info, gi.types.ObjectInfo): - classes = list(info.get_interfaces()) - parent = info.get_parent() - while parent.get_name() != "Object": - classes.append(parent) - parent = parent.get_parent() - classes = [kl for kl in classes if kl.get_namespace() == "Gtk"] - else: - continue - - for kl in classes: - if kl.get_name() == name: - self.assertTrue(issubclass(klass, over,), - "%r does not inherit from override %r" % (klass, over,)) - - def test_editable(self): - self.assertEqual(Gtk.Editable, gi.overrides.Gtk.Editable) - - # need to use Gtk.Entry because Editable is an interface - entry = Gtk.Entry() - pos = entry.insert_text('HeWorld', 0) - self.assertEqual(pos, 7) - pos = entry.insert_text('llo ', 2) - self.assertEqual(pos, 6) - text = entry.get_chars(0, 11) - self.assertEqual('Hello World', text) - - def test_label(self): - label = Gtk.Label(label='Hello') - self.assertTrue(isinstance(label, Gtk.Widget)) - self.assertEqual(label.get_text(), 'Hello') - - def adjustment_check(self, adjustment, value=0.0, lower=0.0, upper=0.0, - step_increment=0.0, page_increment=0.0, page_size=0.0): - self.assertEqual(adjustment.get_value(), value) - self.assertEqual(adjustment.get_lower(), lower) - self.assertEqual(adjustment.get_upper(), upper) - self.assertEqual(adjustment.get_step_increment(), step_increment) - self.assertEqual(adjustment.get_page_increment(), page_increment) - self.assertEqual(adjustment.get_page_size(), page_size) - - def test_adjustment(self): - adjustment = Gtk.Adjustment(value=1, lower=0, upper=6, step_increment=4, page_increment=5, page_size=3) - self.adjustment_check(adjustment, value=1, lower=0, upper=6, step_increment=4, page_increment=5, page_size=3) - - adjustment = Gtk.Adjustment(value=1, lower=0, upper=6, step_increment=4, page_increment=5) - self.adjustment_check(adjustment, value=1, lower=0, upper=6, step_increment=4, page_increment=5) - - adjustment = Gtk.Adjustment(value=1, lower=0, upper=6, step_increment=4) - self.adjustment_check(adjustment, value=1, lower=0, upper=6, step_increment=4) - - adjustment = Gtk.Adjustment(value=1, lower=0, upper=6) - self.adjustment_check(adjustment, value=1, lower=0, upper=6) - - adjustment = Gtk.Adjustment() - self.adjustment_check(adjustment) - - @unittest.skipIf(Gtk._version == "4.0", "not in gtk4") - def test_table(self): - table = Gtk.Table() - self.assertTrue(isinstance(table, Gtk.Table)) - self.assertTrue(isinstance(table, Gtk.Container)) - self.assertTrue(isinstance(table, Gtk.Widget)) - self.assertEqual(table.get_size(), (1, 1)) - self.assertEqual(table.get_homogeneous(), False) - - table = Gtk.Table(n_rows=2, n_columns=3) - self.assertEqual(table.get_size(), (2, 3)) - self.assertEqual(table.get_homogeneous(), False) - - table = Gtk.Table(n_rows=2, n_columns=3, homogeneous=True) - self.assertEqual(table.get_size(), (2, 3)) - self.assertEqual(table.get_homogeneous(), True) - - label = Gtk.Label(label='Hello') - self.assertTrue(isinstance(label, Gtk.Widget)) - table.attach(label, 0, 1, 0, 1) - self.assertEqual(label, table.get_children()[0]) - - def test_scrolledwindow(self): - sw = Gtk.ScrolledWindow() - self.assertTrue(isinstance(sw, Gtk.ScrolledWindow)) - self.assertTrue(isinstance(sw, Gtk.Container)) - self.assertTrue(isinstance(sw, Gtk.Widget)) - sb = sw.get_hscrollbar() - self.assertEqual(sw.get_hadjustment(), sb.get_adjustment()) - sb = sw.get_vscrollbar() - self.assertEqual(sw.get_vadjustment(), sb.get_adjustment()) - - def test_widget_drag_methods(self): - widget = Gtk.Button() - - # here we are not checking functionality, only that the methods exist - # and except the right number of arguments - - widget.drag_check_threshold(0, 0, 0, 0) - - # drag_dest_ methods - widget.drag_dest_set(Gtk.DestDefaults.DROP, None, Gdk.DragAction.COPY) - widget.drag_dest_add_image_targets() - widget.drag_dest_add_text_targets() - widget.drag_dest_add_uri_targets() - widget.drag_dest_get_track_motion() - widget.drag_dest_set_track_motion(True) - widget.drag_dest_get_target_list() - widget.drag_dest_set_target_list(None) - widget.drag_dest_set_target_list(Gtk.TargetList.new([Gtk.TargetEntry.new('test', 0, 0)])) - widget.drag_dest_unset() - - widget.drag_highlight() - widget.drag_unhighlight() - - # drag_source_ methods - widget.drag_source_set(Gdk.ModifierType.BUTTON1_MASK, None, Gdk.DragAction.MOVE) - widget.drag_source_add_image_targets() - widget.drag_source_add_text_targets() - widget.drag_source_add_uri_targets() - widget.drag_source_set_icon_name("_About") - widget.drag_source_set_icon_pixbuf(GdkPixbuf.Pixbuf()) - if Gtk._version != "4.0": - widget.drag_source_set_icon_stock(Gtk.STOCK_ABOUT) - widget.drag_source_get_target_list() - widget.drag_source_set_target_list(None) - widget.drag_source_set_target_list(Gtk.TargetList.new([Gtk.TargetEntry.new('test', 0, 0)])) - widget.drag_source_unset() - - # these methods cannot be called because they require a valid drag on - # a real GdkWindow. So we only check that they exist and are callable. - if Gtk._version != "4.0": - self.assertTrue(hasattr(widget, 'drag_dest_set_proxy')) - self.assertTrue(hasattr(widget, 'drag_get_data')) - - def test_drag_target_list(self): - mixed_target_list = [Gtk.TargetEntry.new('test0', 0, 0), - ('test1', 1, 1), - Gtk.TargetEntry.new('test2', 2, 2), - ('test3', 3, 3)] - - def _test_target_list(targets): - for i, target in enumerate(targets): - self.assertTrue(isinstance(target, Gtk.TargetEntry)) - self.assertEqual(target.target, 'test' + str(i)) - self.assertEqual(target.flags, i) - self.assertEqual(target.info, i) - - _test_target_list(Gtk._construct_target_list(mixed_target_list)) - - widget = Gtk.Button() - widget.drag_dest_set(Gtk.DestDefaults.DROP, None, Gdk.DragAction.COPY) - widget.drag_dest_set_target_list(mixed_target_list) - widget.drag_dest_get_target_list() - - widget.drag_source_set(Gdk.ModifierType.BUTTON1_MASK, None, Gdk.DragAction.MOVE) - widget.drag_source_set_target_list(mixed_target_list) - widget.drag_source_get_target_list() - - treeview = Gtk.TreeView() - treeview.enable_model_drag_source(Gdk.ModifierType.BUTTON1_MASK, - mixed_target_list, - Gdk.DragAction.DEFAULT | Gdk.DragAction.MOVE) - - treeview.enable_model_drag_dest(mixed_target_list, - Gdk.DragAction.DEFAULT | Gdk.DragAction.MOVE) - - @unittest.skipIf(Gtk._version == "4.0", "not in gtk4") - def test_scrollbar(self): - adjustment = Gtk.Adjustment() - - hscrollbar = Gtk.HScrollbar() - vscrollbar = Gtk.VScrollbar() - self.assertNotEqual(hscrollbar.props.adjustment, adjustment) - self.assertNotEqual(vscrollbar.props.adjustment, adjustment) - - hscrollbar = Gtk.HScrollbar(adjustment=adjustment) - vscrollbar = Gtk.VScrollbar(adjustment=adjustment) - self.assertEqual(hscrollbar.props.adjustment, adjustment) - self.assertEqual(vscrollbar.props.adjustment, adjustment) - - def test_iconview(self): - # PyGTK compat - iconview = Gtk.IconView() - self.assertEqual(iconview.props.model, None) - - model = Gtk.ListStore(str) - iconview = Gtk.IconView(model=model) - self.assertEqual(iconview.props.model, model) - - @unittest.skipIf(Gtk._version == "4.0", "not in gtk4") - def test_toolbutton(self): - # PyGTK compat - - # Using stock items causes hard warning in devel versions of GTK+. - with capture_glib_warnings(allow_warnings=True): - button = Gtk.ToolButton() - self.assertEqual(button.props.stock_id, None) - - button = Gtk.ToolButton(stock_id='gtk-new') - self.assertEqual(button.props.stock_id, 'gtk-new') - - icon = Gtk.Image.new_from_stock(Gtk.STOCK_OPEN, Gtk.IconSize.SMALL_TOOLBAR) - button = Gtk.ToolButton(label='mylabel', icon_widget=icon) - self.assertEqual(button.props.label, 'mylabel') - self.assertEqual(button.props.icon_widget, icon) - - def test_toolbutton_gtk4(self): - icon = Gtk.Image.new() - button = Gtk.ToolButton(label='mylabel', icon_widget=icon) - self.assertEqual(button.props.label, 'mylabel') - self.assertEqual(button.props.icon_widget, icon) - - @unittest.skipIf(Gtk._version == "4.0", "not in gtk4") - def test_iconset(self): - Gtk.IconSet() - pixbuf = GdkPixbuf.Pixbuf() - Gtk.IconSet.new_from_pixbuf(pixbuf) - - def test_viewport(self): - vadjustment = Gtk.Adjustment() - hadjustment = Gtk.Adjustment() - - viewport = Gtk.Viewport(hadjustment=hadjustment, - vadjustment=vadjustment) - - self.assertEqual(viewport.props.vadjustment, vadjustment) - self.assertEqual(viewport.props.hadjustment, hadjustment) - - @unittest.skipIf(Gtk._version == "4.0", "not in gtk4") - def test_stock_lookup(self): - stock_item = Gtk.stock_lookup('gtk-ok') - self.assertEqual(type(stock_item), Gtk.StockItem) - self.assertEqual(stock_item.stock_id, 'gtk-ok') - self.assertEqual(Gtk.stock_lookup('nosuchthing'), None) - - def test_gtk_main(self): - # with no arguments - GLib.idle_add(Gtk.main_quit) - Gtk.main() - - # overridden function ignores its arguments - GLib.idle_add(Gtk.main_quit, 'hello') - Gtk.main() - - @unittest.skipIf(Gtk._version == "4.0", "not in gtk4") - def test_widget_render_icon(self): - button = Gtk.Button(label='OK') - pixbuf = button.render_icon(Gtk.STOCK_OK, Gtk.IconSize.BUTTON) - self.assertTrue(pixbuf is not None) - - -@unittest.skipUnless(Gtk, 'Gtk not available') -@unittest.skipIf(Gtk._version == "4.0", "not in gtk4") -class TestWidget(unittest.TestCase): - def test_style_get_property_gvalue(self): - button = Gtk.Button() - value = GObject.Value(int, -42) - button.style_get_property('focus-padding', value) - # Test only that the style property changed since we can't actuall - # set it. - self.assertNotEqual(value.get_int(), -42) - - def test_style_get_property_return_with_explicit_gvalue(self): - button = Gtk.Button() - value = GObject.Value(int, -42) - result = button.style_get_property('focus-padding', value) - self.assertIsInstance(result, int) - self.assertNotEqual(result, -42) - - def test_style_get_property_return_with_implicit_gvalue(self): - button = Gtk.Button() - result = button.style_get_property('focus-padding') - self.assertIsInstance(result, int) - self.assertNotEqual(result, -42) - - def test_style_get_property_error(self): - button = Gtk.Button() - with self.assertRaises(ValueError): - button.style_get_property('not-a-valid-style-property') - - -@unittest.skipIf(sys.platform == "darwin", "hangs") -@unittest.skipUnless(Gtk, 'Gtk not available') -class TestSignals(unittest.TestCase): - def test_class_closure_override_with_aliased_type(self): - class WindowWithSizeAllocOverride(Gtk.ScrolledWindow): - __gsignals__ = {'size-allocate': 'override'} - - def __init__(self): - Gtk.ScrolledWindow.__init__(self) - self._alloc_called = False - self._alloc_value = None - self._alloc_error = None - - def do_size_allocate(self, alloc): - self._alloc_called = True - self._alloc_value = alloc - - try: - Gtk.ScrolledWindow.do_size_allocate(self, alloc) - except Exception as e: - self._alloc_error = e - - win = WindowWithSizeAllocOverride() - rect = Gdk.Rectangle() - rect.width = 100 - rect.height = 100 - - with realized(win): - win.show() - win.get_preferred_size() - win.size_allocate(rect) - self.assertTrue(win._alloc_called) - self.assertIsInstance(win._alloc_value, Gdk.Rectangle) - self.assertTrue(win._alloc_error is None, win._alloc_error) - - @unittest.expectedFailure # https://bugzilla.gnome.org/show_bug.cgi?id=735693 - def test_overlay_child_position(self): - def get_child_position(overlay, widget, rect, user_data=None): - rect.x = 1 - rect.y = 2 - rect.width = 3 - rect.height = 4 - return True - - overlay = Gtk.Overlay() - overlay.connect('get-child-position', get_child_position) - - rect = Gdk.Rectangle() - rect.x = -1 - rect.y = -1 - rect.width = -1 - rect.height = -1 - - overlay.emit('get-child-position', None, rect) - self.assertEqual(rect.x, 1) - self.assertEqual(rect.y, 2) - self.assertEqual(rect.width, 3) - self.assertEqual(rect.height, 4) - - -@unittest.skipUnless(Gtk, 'Gtk not available') -class TestBuilder(unittest.TestCase): - class SignalTest(GObject.GObject): - __gtype_name__ = "GIOverrideSignalTest" - __gsignals__ = { - "test-signal": (GObject.SignalFlags.RUN_FIRST, - None, - []), - } - - def test_extract_handler_and_args_object(self): - class Obj(): - pass - - obj = Obj() - obj.foo = lambda: None - - handler, args = Gtk._extract_handler_and_args(obj, 'foo') - self.assertEqual(handler, obj.foo) - self.assertEqual(len(args), 0) - - def test_extract_handler_and_args_dict(self): - obj = {'foo': lambda: None} - - handler, args = Gtk._extract_handler_and_args(obj, 'foo') - self.assertEqual(handler, obj['foo']) - self.assertEqual(len(args), 0) - - def test_extract_handler_and_args_with_seq(self): - obj = {'foo': (lambda: None, 1, 2)} - - handler, args = Gtk._extract_handler_and_args(obj, 'foo') - self.assertEqual(handler, obj['foo'][0]) - self.assertSequenceEqual(args, [1, 2]) - - def test_extract_handler_and_args_no_handler_error(self): - obj = dict(foo=lambda: None) - self.assertRaises(AttributeError, - Gtk._extract_handler_and_args, - obj, 'not_a_handler') - - def test_builder_with_handler_and_args(self): - builder = Gtk.Builder() - builder.add_from_string(""" - <interface> - <object class="GIOverrideSignalTest" id="object_sig_test"> - <signal name="test-signal" handler="on_signal1" /> - <signal name="test-signal" handler="on_signal2" after="yes" /> - </object> - </interface> - """) - - args_collector = [] - - def on_signal(*args): - args_collector.append(args) - - builder.connect_signals({'on_signal1': (on_signal, 1, 2), - 'on_signal2': on_signal}) - - objects = builder.get_objects() - self.assertEqual(len(objects), 1) - obj, = objects - obj.emit('test-signal') - - self.assertEqual(len(args_collector), 2) - self.assertSequenceEqual(args_collector[0], (obj, 1, 2)) - self.assertSequenceEqual(args_collector[1], (obj, )) - - def test_builder(self): - self.assertEqual(Gtk.Builder, gi.overrides.Gtk.Builder) - - class SignalCheck: - def __init__(self): - self.sentinel = 0 - self.after_sentinel = 0 - - def on_signal_1(self, *args): - self.sentinel += 1 - self.after_sentinel += 1 - - def on_signal_3(self, *args): - self.sentinel += 3 - - def on_signal_after(self, *args): - if self.after_sentinel == 1: - self.after_sentinel += 1 - - signal_checker = SignalCheck() - builder = Gtk.Builder() - - # add object1 to the builder - builder.add_from_string(""" -<interface> - <object class="GIOverrideSignalTest" id="object1"> - <signal name="test-signal" after="yes" handler="on_signal_after" /> - <signal name="test-signal" handler="on_signal_1" /> - </object> -</interface> -""") - - # only add object3 to the builder - builder.add_objects_from_string(""" -<interface> - <object class="GIOverrideSignalTest" id="object2"> - <signal name="test-signal" handler="on_signal_2" /> - </object> - <object class="GIOverrideSignalTest" id="object3"> - <signal name="test-signal" handler="on_signal_3" /> - </object> - <object class="GIOverrideSignalTest" id="object4"> - <signal name="test-signal" handler="on_signal_4" /> - </object> -</interface> -""", ['object3']) - - # hook up signals - builder.connect_signals(signal_checker) - - # call their notify signals and check sentinel - objects = builder.get_objects() - self.assertEqual(len(objects), 2) - for obj in objects: - obj.emit('test-signal') - - self.assertEqual(signal_checker.sentinel, 4) - self.assertEqual(signal_checker.after_sentinel, 2) - - -@ignore_gi_deprecation_warnings -@unittest.skipUnless(Gtk, 'Gtk not available') -class TestTreeModel(unittest.TestCase): - def test_tree_model_sort(self): - self.assertEqual(Gtk.TreeModelSort, gi.overrides.Gtk.TreeModelSort) - model = Gtk.TreeStore(int, bool) - model_sort = Gtk.TreeModelSort(model=model) - self.assertEqual(model_sort.get_model(), model) - def test_tree_store(self): - self.assertEqual(Gtk.TreeStore, gi.overrides.Gtk.TreeStore) - self.assertEqual(Gtk.ListStore, gi.overrides.Gtk.ListStore) - self.assertEqual(Gtk.TreeModel, gi.overrides.Gtk.TreeModel) - self.assertEqual(Gtk.TreeViewColumn, gi.overrides.Gtk.TreeViewColumn) + self.assertEqual(Gtk.TreeStore, overrides.Gtk.TreeStore) + self.assertEqual(Gtk.ListStore, overrides.Gtk.ListStore) + self.assertEqual(Gtk.TreeModel, overrides.Gtk.TreeModel) + self.assertEqual(Gtk.TreeViewColumn, overrides.Gtk.TreeViewColumn) class TestPyObject(object): pass @@ -925,33 +899,32 @@ class TestTreeModel(unittest.TestCase): i % 2, bool(i % 2), i, - GLib.MAXULONG, - GLib.MININT64, + GObject.G_MAXULONG, + GObject.G_MININT64, 0xffffffffffffffff, 254, - b'a' + _bytes('a') )) # test set parent = tree_store.append(parent) i = 97 label = 'this is child #%d' % i testobj = TestGtk.TestClass(self, i, label) - tree_store.set(parent, - 0, i, - 2, testobj, - 1, label, - 3, testobj, - 4, test_pyobj, - 5, test_pydict, - 6, test_pylist, - 7, i % 2, - 8, bool(i % 2), - 9, i, - 10, GLib.MAXULONG, - 11, GLib.MININT64, - 12, 0xffffffffffffffff, - 13, 254, - 14, b'a') + tree_store.set(parent, 0, i, + 2, testobj, + 1, label, + 3, testobj, + 4, test_pyobj, + 5, test_pydict, + 6, test_pylist, + 7, i % 2, + 8, bool(i % 2), + 9, i, + 10, GObject.G_MAXULONG, + 11, GObject.G_MININT64, + 12, 0xffffffffffffffff, + 13, 254, + 14, _bytes('a')) parent = tree_store.append(parent) i = 98 @@ -967,11 +940,11 @@ class TestTreeModel(unittest.TestCase): 7: i % 2, 8: bool(i % 2), 9: i, - 10: GLib.MAXULONG, - 11: GLib.MININT64, + 10: GObject.G_MAXULONG, + 11: GObject.G_MININT64, 12: 0xffffffffffffffff, 13: 254, - 14: b'a'}) + 14: _bytes('a')}) parent = tree_store.append(parent) i = 99 @@ -988,11 +961,11 @@ class TestTreeModel(unittest.TestCase): i % 2, bool(i % 2), i, - GLib.MAXULONG, - GLib.MININT64, + GObject.G_MAXULONG, + GObject.G_MININT64, 0xffffffffffffffff, 254, - b'a')) + _bytes('a'))) # len gets the number of children in the root node # since we kept appending to the previous node @@ -1028,9 +1001,9 @@ class TestTreeModel(unittest.TestCase): uint_ = tree_store.get_value(treeiter, 9) self.assertEqual(uint_, i) ulong_ = tree_store.get_value(treeiter, 10) - self.assertEqual(ulong_, GLib.MAXULONG) + self.assertEqual(ulong_, GObject.G_MAXULONG) int64_ = tree_store.get_value(treeiter, 11) - self.assertEqual(int64_, GLib.MININT64) + self.assertEqual(int64_, GObject.G_MININT64) uint64_ = tree_store.get_value(treeiter, 12) self.assertEqual(uint64_, 0xffffffffffffffff) uchar_ = tree_store.get_value(treeiter, 13) @@ -1102,7 +1075,7 @@ class TestTreeModel(unittest.TestCase): bool(i % 2))) i = 93 - label = u'this is row #93' + label = _unicode('this is row #93') treeiter = list_store.append() list_store.set_value(treeiter, 0, i) list_store.set_value(treeiter, 1, label) @@ -1126,7 +1099,7 @@ class TestTreeModel(unittest.TestCase): # test automatic unicode->str conversion i = 94 - label = u'this is row #94' + label = _unicode('this is row #94') treeiter = list_store.append((i, label, TestGtk.TestClass(self, i, label), @@ -1203,15 +1176,14 @@ class TestTreeModel(unittest.TestCase): i = 100 label = 'this is row #100' treeiter = list_store.append() - list_store.set(treeiter, - 1, label, - 0, i, - 2, TestGtk.TestClass(self, i, label), - 3, test_pyobj, - 4, test_pydict, - 5, test_pylist, - 6, 0, - 7, False) + list_store.set(treeiter, 1, label, + 0, i, + 2, TestGtk.TestClass(self, i, label), + 3, test_pyobj, + 4, test_pydict, + 5, test_pylist, + 6, 0, + 7, False) i = 101 label = 'this is row #101' treeiter = list_store.append() @@ -1227,14 +1199,14 @@ class TestTreeModel(unittest.TestCase): label = 'this is row #102' treeiter = list_store.append() list_store.set(treeiter, (1, 0, 2, 3, 4, 5, 6, 7), - (label, - i, - TestGtk.TestClass(self, i, label), - test_pyobj, - test_pydict, - test_pylist, - 0, - False)) + (label, + i, + TestGtk.TestClass(self, i, label), + test_pyobj, + test_pydict, + test_pylist, + 0, + False)) self.assertEqual(len(list_store), 103) @@ -1279,7 +1251,7 @@ class TestTreeModel(unittest.TestCase): return -1 if v2.startswith('m') and not v1.startswith('m'): return 1 - return (v1 > v2) - (v1 < v2) + return cmp(v1, v2) list_store = Gtk.ListStore(int, str) list_store.set_sort_func(2, comp1, None) @@ -1289,16 +1261,16 @@ class TestTreeModel(unittest.TestCase): # not sorted yet, should be original order self.assertEqual([list(i) for i in list_store], - [[1, 'apples'], [3, 'oranges'], [2, 'mango']]) + [[1, 'apples'], [3, 'oranges'], [2, 'mango']]) # sort with our custom function list_store.set_sort_column_id(2, Gtk.SortType.ASCENDING) self.assertEqual([list(i) for i in list_store], - [[2, 'mango'], [1, 'apples'], [3, 'oranges']]) + [[2, 'mango'], [1, 'apples'], [3, 'oranges']]) list_store.set_sort_column_id(2, Gtk.SortType.DESCENDING) self.assertEqual([list(i) for i in list_store], - [[3, 'oranges'], [1, 'apples'], [2, 'mango']]) + [[3, 'oranges'], [1, 'apples'], [2, 'mango']]) def test_list_store_signals(self): list_store = Gtk.ListStore(int, bool) @@ -1342,33 +1314,26 @@ class TestTreeModel(unittest.TestCase): p2 = Gtk.TreePath.new_first() self.assertEqual(p1, p2) self.assertEqual(str(p1), '0') - self.assertEqual(len(p1), 1) p1 = Gtk.TreePath(2) p2 = Gtk.TreePath.new_from_string('2') self.assertEqual(p1, p2) self.assertEqual(str(p1), '2') - self.assertEqual(len(p1), 1) p1 = Gtk.TreePath('1:2:3') p2 = Gtk.TreePath.new_from_string('1:2:3') self.assertEqual(p1, p2) self.assertEqual(str(p1), '1:2:3') - self.assertEqual(len(p1), 3) p1 = Gtk.TreePath((1, 2, 3)) p2 = Gtk.TreePath.new_from_string('1:2:3') self.assertEqual(p1, p2) self.assertEqual(str(p1), '1:2:3') - self.assertEqual(len(p1), 3) - self.assertNotEqual(p1, None) + self.assertTrue(p1 != None) + self.assertFalse(p1 == None) self.assertTrue(p1 > None) self.assertTrue(p1 >= None) self.assertFalse(p1 < None) self.assertFalse(p1 <= None) self.assertEqual(tuple(p1), (1, 2, 3)) - self.assertEqual(p1[0], 1) - self.assertEqual(p1[1], 2) - self.assertEqual(p1[2], 3) - self.assertRaises(IndexError, p1.__getitem__, 3) def test_tree_model(self): tree_store = Gtk.TreeStore(int, str) @@ -1409,7 +1374,7 @@ class TestTreeModel(unittest.TestCase): for i in range(100): label = 'this is row #%d' % i parent = tree_store.append(None, (DerivedIntType(i), DerivedStrType(label),)) - self.assertNotEqual(parent, None) + self.assertNotEquals(parent, None) for j in range(20): label = 'this is child #%d of node #%d' % (j, i) child = tree_store.append(parent, (j, label,)) @@ -1534,24 +1499,6 @@ class TestTreeModel(unittest.TestCase): self.assertRaises(ValueError, tree_store.get, aiter, 1, 100) self.assertEqual(tree_store.get(aiter, 0, 1), (10, 'this is row #10')) - # check __delitem__ - self.assertEqual(len(tree_store), 100) - aiter = tree_store.get_iter(10) - del tree_store[aiter] - self.assertEqual(len(tree_store), 99) - self.assertRaises(TypeError, tree_store.__delitem__, None) - self.assertRaises(IndexError, tree_store.__delitem__, -101) - self.assertRaises(IndexError, tree_store.__delitem__, 101) - - def test_tree_model_get_iter_fail(self): - # TreeModel class with a failing get_iter() - class MyTreeModel(GObject.GObject, Gtk.TreeModel): - def do_get_iter(self, iter): - return (False, None) - - tm = MyTreeModel() - self.assertEqual(tm.get_iter_first(), None) - def test_tree_model_edit(self): model = Gtk.ListStore(int, str, float) model.append([1, "one", -0.1]) @@ -1607,198 +1554,32 @@ class TestTreeModel(unittest.TestCase): def set_row3(): model[0][:2] = ("0", 0) - self.assertRaises(TypeError, set_row3) - - def test_tree_row_sequence(self): - model = Gtk.ListStore(int, str, float) - model.append([1, "one", -0.1]) - - self.assertEqual([1, "one", -0.1], model[0][0, 1, 2]) - self.assertEqual([1, "one"], model[0][0, 1]) - self.assertEqual(["one", -0.1], model[0][1, 2]) - self.assertEqual("one", model[0][1]) - self.assertEqual([1, -0.1], model[0][0, 2]) - self.assertEqual([-0.1, 1], model[0][2, 0]) - - model[0][0, 1, 2] = (2, "two", -0.2) - self.assertEqual([2, "two", -0.2], model[0][0, 1, 2]) - - model[0][0, 1] = (3, "three") - self.assertEqual([3, "three"], model[0][0, 1]) - - model[0][1, 2] = ("four", -0.4) - self.assertEqual(["four", -0.4], model[0][1, 2]) - - model[0][0, 2] = (5, -0.5) - self.assertEqual([5, -0.5], model[0][0, 2]) - - model[0][0, 1, 2] = (6, "six", -0.6) - self.assertEqual([-0.6, 6, "six"], model[0][2, 0, 1]) - - def set_row1(): - model[0][4, 5] = ("shouldn't", "work",) - - self.assertRaises(IndexError, set_row1) - - def set_row2(): - model[0][0, 1] = (0, "zero", 0) - - self.assertRaises(ValueError, set_row2) - - def set_row3(): - model[0][0, 1] = ("shouldn't", 0) - - self.assertRaises(TypeError, set_row3) - - def set_row4(): - model[0][0, "two"] = (0, "zero") - - self.assertRaises(TypeError, set_row4) - - def test_tree_model_set_value_to_none(self): - # Tests allowing the usage of None to set an empty value on a model. - store = Gtk.ListStore(str) - row = store.append(['test']) - self.assertSequenceEqual(store[0][:], ['test']) - store.set_value(row, 0, None) - self.assertSequenceEqual(store[0][:], [None]) - - def test_signal_emission_tree_path_coerce(self): - class Model(GObject.Object, Gtk.TreeModel): - pass - - model = Model() - tree_paths = [] - - def on_any_signal(model, path, *args): - tree_paths.append(path.to_string()) - - model.connect('row-changed', on_any_signal) - model.connect('row-deleted', on_any_signal) - model.connect('row-has-child-toggled', on_any_signal) - model.connect('row-inserted', on_any_signal) - - model.row_changed('0', Gtk.TreeIter()) - self.assertEqual(tree_paths[-1], '0') - - model.row_deleted('1') - self.assertEqual(tree_paths[-1], '1') - - model.row_has_child_toggled('2', Gtk.TreeIter()) - self.assertEqual(tree_paths[-1], '2') - - model.row_inserted('3', Gtk.TreeIter()) - self.assertEqual(tree_paths[-1], '3') - - def test_tree_model_filter(self): - model = Gtk.ListStore(int, str, float) - model.append([1, "one", -0.1]) - model.append([2, "two", -0.2]) - - filtered = Gtk.TreeModelFilter(child_model=model) - - self.assertEqual(filtered[0][1], 'one') - filtered[0][1] = 'ONE' - self.assertEqual(filtered[0][1], 'ONE') - - def test_list_store_performance(self): - model = Gtk.ListStore(int, str) - - iterations = 2000 - start = time.clock() - i = iterations - while i > 0: - model.append([1, 'hello']) - i -= 1 - end = time.clock() - sys.stderr.write('[%.0f µs/append] ' % ((end - start) * 1000000 / iterations)) + self.assertRaises(ValueError, set_row3) - def test_filter_new_default(self): - # Test filter_new accepts implicit default of None - model = Gtk.ListStore(int) - filt = model.filter_new() - self.assertTrue(filt is not None) - - -@unittest.skipIf(sys.platform == "darwin", "hangs") -@unittest.skipUnless(Gtk, 'Gtk not available') -class TestTreeView(unittest.TestCase): def test_tree_view(self): store = Gtk.ListStore(int, str) store.append((0, "foo")) store.append((1, "bar")) view = Gtk.TreeView() + # FIXME: We can't easily call get_cursor() to make sure this works as + # expected as we need to realize and focus the column; the following + # will raise a Gtk-CRITICAL which we ignore for now + old_mask = GLib.log_set_always_fatal( + GLib.LogLevelFlags.LEVEL_WARNING | GLib.LogLevelFlags.LEVEL_ERROR) + view.set_cursor(store[1].path) + view.set_cursor(str(store[1].path)) - with realized(view): - view.set_cursor(store[1].path) - view.set_cursor(str(store[1].path)) + view.get_cell_area(store[1].path) + view.get_cell_area(str(store[1].path)) - view.get_cell_area(store[1].path) - view.get_cell_area(str(store[1].path)) + GLib.log_set_always_fatal(old_mask) def test_tree_view_column(self): cell = Gtk.CellRendererText() - col = Gtk.TreeViewColumn(title='This is just a test', - cell_renderer=cell, - text=0, - style=2) - - # Regression test for: https://bugzilla.gnome.org/show_bug.cgi?id=711173 - col.set_cell_data_func(cell, None, None) - - def test_tree_view_add_column_with_attributes(self): - model = Gtk.ListStore(str, str, str) - # deliberately use out-of-order sorting here; we assign column 0 to - # model index 2, etc. - model.append(['cell13', 'cell11', 'cell12']) - model.append(['cell23', 'cell21', 'cell22']) - - tree = Gtk.TreeView(model=model) - cell1 = Gtk.CellRendererText() - cell2 = Gtk.CellRendererText() - cell3 = Gtk.CellRendererText() - cell4 = Gtk.CellRendererText() - - tree.insert_column_with_attributes(0, 'Head2', cell2, text=2) - tree.insert_column_with_attributes(0, 'Head1', cell1, text=1) - tree.insert_column_with_attributes(-1, 'Head3', cell3, text=0) - # unconnected - tree.insert_column_with_attributes(-1, 'Head4', cell4) - - with realized(tree): - tree.set_cursor(model[0].path) - while Gtk.events_pending(): - Gtk.main_iteration() - - self.assertEqual(tree.get_column(0).get_title(), 'Head1') - self.assertEqual(tree.get_column(1).get_title(), 'Head2') - self.assertEqual(tree.get_column(2).get_title(), 'Head3') - self.assertEqual(tree.get_column(3).get_title(), 'Head4') - - # cursor should be at the first row - self.assertEqual(cell1.props.text, 'cell11') - self.assertEqual(cell2.props.text, 'cell12') - self.assertEqual(cell3.props.text, 'cell13') - self.assertEqual(cell4.props.text, None) - - def test_tree_view_column_set_attributes(self): - store = Gtk.ListStore(int, str) - directors = ['Fellini', 'Tarantino', 'Tarkovskiy'] - for i, director in enumerate(directors): - store.append([i, director]) - - treeview = Gtk.TreeView() - treeview.set_model(store) - - column = Gtk.TreeViewColumn() - treeview.append_column(column) - - cell = Gtk.CellRendererText() - column.pack_start(cell, expand=True) - column.set_attributes(cell, text=1) - - with realized(treeview): - self.assertTrue(cell.props.text in directors) + Gtk.TreeViewColumn(title='This is just a test', + cell_renderer=cell, + text=0, + style=2) def test_tree_selection(self): store = Gtk.ListStore(int, str) @@ -1829,11 +1610,8 @@ class TestTreeView(unittest.TestCase): self.assertEqual(m, store) self.assertEqual(store.get_path(s), firstpath) - -@unittest.skipUnless(Gtk, 'Gtk not available') -class TestTextBuffer(unittest.TestCase): def test_text_buffer(self): - self.assertEqual(Gtk.TextBuffer, gi.overrides.Gtk.TextBuffer) + self.assertEqual(Gtk.TextBuffer, overrides.Gtk.TextBuffer) buffer = Gtk.TextBuffer() tag = buffer.create_tag('title', font='Sans 18') @@ -1875,194 +1653,357 @@ class TestTextBuffer(unittest.TestCase): self.assertTrue(sel[1].equal(end)) buffer.set_text('') - buffer.insert_with_tags(buffer.get_start_iter(), 'HelloHello') - start, end = buffer.get_bounds() - text = buffer.get_text(start, end, False) - self.assertEqual(text, 'HelloHello') - - buffer.set_text('') - buffer.insert_with_tags_by_name(buffer.get_start_iter(), 'HelloHello') - start, end = buffer.get_bounds() - text = buffer.get_text(start, end, False) - self.assertEqual(text, 'HelloHello') - - try: - starts_tag = Gtk.TextIter.starts_tag - except AttributeError: - starts_tag = Gtk.TextIter.begins_tag - - buffer.set_text('') buffer.insert_with_tags(buffer.get_start_iter(), 'HelloHello', tag) (start, end) = buffer.get_bounds() - self.assertTrue(starts_tag(start, tag)) + self.assertTrue(start.begins_tag(tag)) self.assertTrue(start.has_tag(tag)) buffer.set_text('') buffer.insert_with_tags_by_name(buffer.get_start_iter(), 'HelloHello', 'title') (start, end) = buffer.get_bounds() - self.assertTrue(starts_tag(start, tag)) + self.assertTrue(start.begins_tag(tag)) self.assertTrue(start.has_tag(tag)) self.assertRaises(ValueError, buffer.insert_with_tags_by_name, - buffer.get_start_iter(), 'HelloHello', 'unknowntag') + buffer.get_start_iter(), 'HelloHello', 'unknowntag') def test_text_iter(self): - try: - starts_tag = Gtk.TextIter.starts_tag - except AttributeError: - starts_tag = Gtk.TextIter.begins_tag - - self.assertEqual(Gtk.TextIter, gi.overrides.Gtk.TextIter) + self.assertEqual(Gtk.TextIter, overrides.Gtk.TextIter) buffer = Gtk.TextBuffer() buffer.set_text('Hello Jane Hello Bob') tag = buffer.create_tag('title', font='Sans 18') (start, end) = buffer.get_bounds() start.forward_chars(10) buffer.apply_tag(tag, start, end) - self.assertTrue(starts_tag(start)) + self.assertTrue(start.begins_tag()) self.assertTrue(end.ends_tag()) self.assertTrue(start.toggles_tag()) self.assertTrue(end.toggles_tag()) start.backward_chars(1) - self.assertFalse(starts_tag(start)) + self.assertFalse(start.begins_tag()) self.assertFalse(start.ends_tag()) self.assertFalse(start.toggles_tag()) - def test_text_buffer_search(self): - buffer = Gtk.TextBuffer() - buffer.set_text('Hello World Hello GNOME') + def test_buttons(self): + self.assertEqual(Gtk.Button, overrides.Gtk.Button) - i = buffer.get_iter_at_offset(0) - self.assertTrue(isinstance(i, Gtk.TextIter)) + # test Gtk.Button + button = Gtk.Button() + self.assertTrue(isinstance(button, Gtk.Button)) + self.assertTrue(isinstance(button, Gtk.Container)) + self.assertTrue(isinstance(button, Gtk.Widget)) + button = Gtk.Button(stock=Gtk.STOCK_CLOSE) + self.assertEqual(Gtk.STOCK_CLOSE, button.get_label()) + self.assertTrue(button.get_use_stock()) + self.assertTrue(button.get_use_underline()) - self.assertEqual(i.forward_search('world', 0, None), None) + # test Gtk.Button use_stock + button = Gtk.Button(label=Gtk.STOCK_CLOSE, use_stock=True, use_underline=True) + self.assertEqual(Gtk.STOCK_CLOSE, button.get_label()) + self.assertTrue(button.get_use_stock()) + self.assertTrue(button.get_use_underline()) - (start, end) = i.forward_search('World', 0, None) - self.assertEqual(start.get_offset(), 6) - self.assertEqual(end.get_offset(), 11) + # test Gtk.LinkButton + self.assertRaises(TypeError, Gtk.LinkButton) + button = Gtk.LinkButton('http://www.Gtk.org', 'Gtk') + self.assertTrue(isinstance(button, Gtk.Button)) + self.assertTrue(isinstance(button, Gtk.Container)) + self.assertTrue(isinstance(button, Gtk.Widget)) + self.assertEqual('http://www.Gtk.org', button.get_uri()) + self.assertEqual('Gtk', button.get_label()) - (start, end) = i.forward_search('world', - Gtk.TextSearchFlags.CASE_INSENSITIVE, - None) - self.assertEqual(start.get_offset(), 6) - self.assertEqual(end.get_offset(), 11) + def test_inheritance(self): + for name in overrides.Gtk.__all__: + over = getattr(overrides.Gtk, name) + for element in dir(Gtk): + try: + klass = getattr(Gtk, element) + info = klass.__info__ + except (NotImplementedError, AttributeError): + continue - def test_insert_text_signal_location_modification(self): - # Regression test for: https://bugzilla.gnome.org/show_bug.cgi?id=736175 + # Get all parent classes and interfaces klass inherits from + if isinstance(info, gi.types.ObjectInfo): + classes = list(info.get_interfaces()) + parent = info.get_parent() + while parent.get_name() != "Object": + classes.append(parent) + parent = parent.get_parent() + classes = [kl for kl in classes if kl.get_namespace() == "Gtk"] + else: + continue - def callback(buffer, location, text, length): - location.assign(buffer.get_end_iter()) + for kl in classes: + if kl.get_name() == name: + self.assertTrue(issubclass(klass, over,), + "%r does not inherit from override %r" % (klass, over,)) - buffer = Gtk.TextBuffer() - buffer.set_text('first line\n') - buffer.connect('insert-text', callback) + def test_editable(self): + self.assertEqual(Gtk.Editable, overrides.Gtk.Editable) - # attempt insertion at the beginning of the buffer, the callback will - # modify the insert location to the end. - buffer.place_cursor(buffer.get_start_iter()) - buffer.insert_at_cursor('second line\n') + # need to use Gtk.Entry because Editable is an interface + entry = Gtk.Entry() + pos = entry.insert_text('HeWorld', 0) + self.assertEqual(pos, 7) + pos = entry.insert_text('llo ', 2) + self.assertEqual(pos, 6) + text = entry.get_chars(0, 11) + self.assertEqual('Hello World', text) - self.assertEqual(buffer.get_property('text'), - 'first line\nsecond line\n') + def test_label(self): + label = Gtk.Label(label='Hello') + self.assertTrue(isinstance(label, Gtk.Widget)) + self.assertEqual(label.get_text(), 'Hello') - def test_backward_find_char(self): - buffer = Gtk.TextBuffer() - buffer.set_text('abc') - end = buffer.get_iter_at_line(99) + def adjustment_check(self, adjustment, value=0.0, lower=0.0, upper=0.0, + step_increment=0.0, page_increment=0.0, page_size=0.0): + self.assertEqual(adjustment.get_value(), value) + self.assertEqual(adjustment.get_lower(), lower) + self.assertEqual(adjustment.get_upper(), upper) + self.assertEqual(adjustment.get_step_increment(), step_increment) + self.assertEqual(adjustment.get_page_increment(), page_increment) + self.assertEqual(adjustment.get_page_size(), page_size) - values = [] + def test_adjustment(self): + adjustment = Gtk.Adjustment(1, 0, 6, 4, 5, 3) + self.adjustment_check(adjustment, 1, 0, 6, 4, 5, 3) - def pred_func(ch, user_data): - values.append(ch) - return ch == u"a" + adjustment = Gtk.Adjustment(1, 0, 6, 4, 5) + self.adjustment_check(adjustment, 1, 0, 6, 4, 5) - self.assertTrue(end.backward_find_char(pred_func)) - self.assertEqual(values, [u"c", u"b", u"a"]) + adjustment = Gtk.Adjustment(1, 0, 6, 4) + self.adjustment_check(adjustment, 1, 0, 6, 4) + adjustment = Gtk.Adjustment(1, 0, 6) + self.adjustment_check(adjustment, 1, 0, 6) -@unittest.skipUnless(Gtk, 'Gtk not available') -class TestContainer(unittest.TestCase): + adjustment = Gtk.Adjustment() + self.adjustment_check(adjustment) - @unittest.skipIf(Gtk._version == "4.0", "not in gtk4") - def test_child_set_property(self): - box = Gtk.Box() - child = Gtk.Button() - box.pack_start(child, expand=False, fill=True, padding=0) + adjustment = Gtk.Adjustment(value=1, lower=0, upper=6, + step_increment=4, page_increment=5, page_size=3) + self.adjustment_check(adjustment, 1, 0, 6, 4, 5, 3) - box.child_set_property(child, 'padding', 42) + def test_table(self): + table = Gtk.Table() + self.assertTrue(isinstance(table, Gtk.Table)) + self.assertTrue(isinstance(table, Gtk.Container)) + self.assertTrue(isinstance(table, Gtk.Widget)) + self.assertEqual(table.get_size(), (1, 1)) + self.assertEqual(table.get_homogeneous(), False) + table = Gtk.Table(2, 3) + self.assertEqual(table.get_size(), (2, 3)) + self.assertEqual(table.get_homogeneous(), False) + table = Gtk.Table(2, 3, True) + self.assertEqual(table.get_size(), (2, 3)) + self.assertEqual(table.get_homogeneous(), True) - value = GObject.Value(int) - box.child_get_property(child, 'padding', value) - self.assertEqual(value.get_int(), 42) + # Test PyGTK interface + table = Gtk.Table(rows=3, columns=2) + self.assertEqual(table.get_size(), (3, 2)) + # Test using the actual property names + table = Gtk.Table(n_rows=2, n_columns=3, homogeneous=True) + self.assertEqual(table.get_size(), (2, 3)) + self.assertEqual(table.get_homogeneous(), True) - @unittest.skipIf(Gtk._version == "4.0", "not in gtk4") - def test_child_get_property_gvalue(self): - box = Gtk.Box() - child = Gtk.Button() - box.pack_start(child, expand=False, fill=True, padding=42) + label = Gtk.Label(label='Hello') + self.assertTrue(isinstance(label, Gtk.Widget)) + table.attach(label, 0, 1, 0, 1) + self.assertEqual(label, table.get_children()[0]) - value = GObject.Value(int) - box.child_get_property(child, 'padding', value) - self.assertEqual(value.get_int(), 42) + def test_scrolledwindow(self): + sw = Gtk.ScrolledWindow() + self.assertTrue(isinstance(sw, Gtk.ScrolledWindow)) + self.assertTrue(isinstance(sw, Gtk.Container)) + self.assertTrue(isinstance(sw, Gtk.Widget)) + sb = sw.get_hscrollbar() + self.assertEqual(sw.get_hadjustment(), sb.get_adjustment()) + sb = sw.get_vscrollbar() + self.assertEqual(sw.get_vadjustment(), sb.get_adjustment()) - @unittest.skipIf(Gtk._version == "4.0", "not in gtk4") - def test_child_get_property_return_with_explicit_gvalue(self): - box = Gtk.Box() - child = Gtk.Button() - box.pack_start(child, expand=False, fill=True, padding=42) + def test_widget_drag_methods(self): + widget = Gtk.Button() - value = GObject.Value(int) - result = box.child_get_property(child, 'padding', value) - self.assertEqual(result, 42) + # here we are not checking functionality, only that the methods exist + # and except the right number of arguments - @unittest.skipIf(Gtk._version == "4.0", "not in gtk4") - def test_child_get_property_return_with_implicit_gvalue(self): - box = Gtk.Box() - child = Gtk.Button() - box.pack_start(child, expand=False, fill=True, padding=42) + widget.drag_check_threshold(0, 0, 0, 0) - result = box.child_get_property(child, 'padding') - self.assertEqual(result, 42) + # drag_dest_ methods + widget.drag_dest_set(Gtk.DestDefaults.DROP, None, Gdk.DragAction.COPY) + widget.drag_dest_add_image_targets() + widget.drag_dest_add_text_targets() + widget.drag_dest_add_uri_targets() + widget.drag_dest_get_track_motion() + widget.drag_dest_set_track_motion(True) + widget.drag_dest_get_target_list() + widget.drag_dest_set_target_list(Gtk.TargetList.new([Gtk.TargetEntry.new('test', 0, 0)])) + widget.drag_dest_unset() - def test_child_get_property_error(self): - box = Gtk.Box() - child = Gtk.Button() - if Gtk._version == "4.0": - box.pack_start(child, expand=False, fill=True) - else: - box.pack_start(child, expand=False, fill=True, padding=42) - with self.assertRaises(ValueError): - box.child_get_property(child, 'not-a-valid-child-property') - - @unittest.skipIf(Gtk._version == "4.0", "not in gtk4") - def test_child_get_and_set(self): - box = Gtk.Box() - child = Gtk.Button() - box.pack_start(child, expand=True, fill=True, padding=42) - - expand, fill, padding = box.child_get(child, 'expand', 'fill', 'padding') - self.assertEqual(expand, True) - self.assertEqual(fill, True) - self.assertEqual(padding, 42) - - box.child_set(child, expand=False, fill=False, padding=21, pack_type=1) - expand, fill, padding, pack_type = box.child_get(child, 'expand', 'fill', 'padding', 'pack-type') - self.assertEqual(expand, False) - self.assertEqual(fill, False) - self.assertEqual(padding, 21) - - @unittest.skipIf(Gtk._version != "4.0", "only in gtk4") - def test_child_get_and_set_gtk4(self): - # padding got removed in gtk4 - box = Gtk.Box() - child = Gtk.Button() - box.pack_start(child, expand=True, fill=True) + widget.drag_highlight() + widget.drag_unhighlight() + + # drag_source_ methods + widget.drag_source_set(Gdk.ModifierType.BUTTON1_MASK, None, Gdk.DragAction.MOVE) + widget.drag_source_add_image_targets() + widget.drag_source_add_text_targets() + widget.drag_source_add_uri_targets() + widget.drag_source_set_icon_name("") + widget.drag_source_set_icon_pixbuf(GdkPixbuf.Pixbuf()) + widget.drag_source_set_icon_stock("") + widget.drag_source_get_target_list() + widget.drag_source_set_target_list(Gtk.TargetList.new([Gtk.TargetEntry.new('test', 0, 0)])) + widget.drag_source_unset() + + # these methods cannot be called because they require a valid drag on + # a real GdkWindow. So we only check that they exist and are callable. + self.assertTrue(hasattr(widget.drag_dest_set_proxy, '__call__')) + self.assertTrue(hasattr(widget.drag_get_data, '__call__')) + + def test_scrollbar(self): + # PyGTK compat + adjustment = Gtk.Adjustment() + + hscrollbar = Gtk.HScrollbar() + vscrollbar = Gtk.VScrollbar() + self.assertNotEquals(hscrollbar.props.adjustment, adjustment) + self.assertNotEquals(vscrollbar.props.adjustment, adjustment) + + hscrollbar = Gtk.HScrollbar(adjustment) + vscrollbar = Gtk.VScrollbar(adjustment) + self.assertEqual(hscrollbar.props.adjustment, adjustment) + self.assertEqual(vscrollbar.props.adjustment, adjustment) + + def test_iconview(self): + # PyGTK compat + iconview = Gtk.IconView() + self.assertEqual(iconview.props.model, None) + + model = Gtk.ListStore(str) + iconview = Gtk.IconView(model) + self.assertEqual(iconview.props.model, model) + + def test_toolbutton(self): + # PyGTK compat + button = Gtk.ToolButton() + self.assertEqual(button.props.stock_id, None) + + button = Gtk.ToolButton('gtk-new') + self.assertEqual(button.props.stock_id, 'gtk-new') + + icon = Gtk.Image.new_from_stock(Gtk.STOCK_OPEN, Gtk.IconSize.SMALL_TOOLBAR) + + button = Gtk.ToolButton(label='mylabel', icon_widget=icon) + self.assertEqual(button.props.label, 'mylabel') + self.assertEqual(button.props.icon_widget, icon) + + def test_iconset(self): + # PyGTK compat + Gtk.IconSet() + pixbuf = GdkPixbuf.Pixbuf() + Gtk.IconSet(pixbuf) + + def test_viewport(self): + # PyGTK compat + vadjustment = Gtk.Adjustment() + hadjustment = Gtk.Adjustment() + + viewport = Gtk.Viewport(hadjustment=hadjustment, + vadjustment=vadjustment) + + self.assertEqual(viewport.props.vadjustment, vadjustment) + self.assertEqual(viewport.props.hadjustment, hadjustment) - expand, fill = box.child_get(child, 'expand', 'fill') - self.assertEqual(expand, True) - self.assertEqual(fill, True) - box.child_set(child, expand=False, fill=False, pack_type=1) - expand, fill, pack_type = box.child_get(child, 'expand', 'fill', 'pack-type') - self.assertEqual(expand, False) - self.assertEqual(fill, False) +class TestGio(unittest.TestCase): + def setUp(self): + self.settings = Gio.Settings('org.gnome.test') + # we change the values in the tests, so set them to predictable start + # value + self.settings.reset('test-string') + self.settings.reset('test-array') + + def test_file_enumerator(self): + self.assertEqual(Gio.FileEnumerator, overrides.Gio.FileEnumerator) + f = Gio.file_new_for_path("./") + + iter_info = [] + for info in f.enumerate_children("standard::*", 0, None): + iter_info.append(info.get_name()) + + next_info = [] + enumerator = f.enumerate_children("standard::*", 0, None) + while True: + info = enumerator.next_file(None) + if info is None: + break + next_info.append(info.get_name()) + + self.assertEqual(iter_info, next_info) + + def test_gsettings_native(self): + self.assertTrue('test-array' in self.settings.list_keys()) + + # get various types + v = self.settings.get_value('test-boolean') + self.assertEqual(v.get_boolean(), True) + self.assertEqual(self.settings.get_boolean('test-boolean'), True) + + v = self.settings.get_value('test-string') + self.assertEqual(v.get_string(), 'Hello') + self.assertEqual(self.settings.get_string('test-string'), 'Hello') + + v = self.settings.get_value('test-array') + self.assertEqual(v.unpack(), [1, 2]) + + v = self.settings.get_value('test-tuple') + self.assertEqual(v.unpack(), (1, 2)) + + # set a value + self.settings.set_string('test-string', 'World') + self.assertEqual(self.settings.get_string('test-string'), 'World') + + self.settings.set_value('test-string', GLib.Variant('s', 'Goodbye')) + self.assertEqual(self.settings.get_string('test-string'), 'Goodbye') + + def test_gsettings_constructor(self): + # default constructor uses path from schema + self.assertEqual(self.settings.get_property('path'), '/tests/') + + # optional constructor arguments + with_path = Gio.Settings('org.gnome.nopathtest', path='/mypath/') + self.assertEqual(with_path.get_property('path'), '/mypath/') + self.assertEqual(with_path['np-int'], 42) + + def test_gsettings_override(self): + # dictionary interface + self.assertEqual(len(self.settings), 4) + self.assertTrue('test-array' in self.settings) + self.assertTrue('test-array' in self.settings.keys()) + self.assertFalse('nonexisting' in self.settings) + self.assertFalse(4 in self.settings) + self.assertEqual(bool(self.settings), True) + + # get various types + self.assertEqual(self.settings['test-boolean'], True) + self.assertEqual(self.settings['test-string'], 'Hello') + self.assertEqual(self.settings['test-array'], [1, 2]) + self.assertEqual(self.settings['test-tuple'], (1, 2)) + + self.assertRaises(KeyError, self.settings.__getitem__, 'unknown') + self.assertRaises(KeyError, self.settings.__getitem__, 2) + + # set a value + self.settings['test-string'] = 'Goodbye' + self.assertEqual(self.settings['test-string'], 'Goodbye') + self.settings['test-array'] = [3, 4, 5] + self.assertEqual(self.settings['test-array'], [3, 4, 5]) + + self.assertRaises(TypeError, self.settings.__setitem__, 'test-string', 1) + self.assertRaises(KeyError, self.settings.__setitem__, 'unknown', 'moo') + + def test_gsettings_empty(self): + empty = Gio.Settings('org.gnome.empty', path='/tests/') + self.assertEqual(len(empty), 0) + self.assertEqual(bool(empty), True) + self.assertEqual(empty.keys(), []) diff --git a/tests/test_overrides_gdk.py b/tests/test_overrides_gdk.py deleted file mode 100644 index 0974d35..0000000 --- a/tests/test_overrides_gdk.py +++ /dev/null @@ -1,207 +0,0 @@ -# -*- Mode: Python; py-indent-offset: 4 -*- -# vim: tabstop=4 shiftwidth=4 expandtab - -import os -import sys -import unittest - -import gi.overrides -from gi import PyGIDeprecationWarning - -try: - from gi.repository import Gdk, GdkPixbuf, Gtk - Gdk # pyflakes -except ImportError: - Gdk = None - -from helper import capture_glib_deprecation_warnings - - -@unittest.skipUnless(Gdk, 'Gdk not available') -class TestGdk(unittest.TestCase): - - @unittest.skipIf(sys.platform == "darwin" or os.name == "nt", "crashes") - @unittest.skipIf(Gdk._version == "4.0", "not in gdk4") - def test_constructor(self): - attribute = Gdk.WindowAttr() - attribute.window_type = Gdk.WindowType.CHILD - attributes_mask = Gdk.WindowAttributesType.X | \ - Gdk.WindowAttributesType.Y - window = Gdk.Window(None, attribute, attributes_mask) - self.assertEqual(window.get_window_type(), Gdk.WindowType.CHILD) - - @unittest.skipIf(Gdk._version == "4.0", "not in gdk4") - def test_color(self): - color = Gdk.Color(100, 200, 300) - self.assertEqual(color.red, 100) - self.assertEqual(color.green, 200) - self.assertEqual(color.blue, 300) - with capture_glib_deprecation_warnings(): - self.assertEqual(color, Gdk.Color(100, 200, 300)) - self.assertNotEqual(color, Gdk.Color(1, 2, 3)) - - @unittest.skipIf(Gdk._version == "4.0", "not in gdk4") - def test_color_floats(self): - self.assertEqual(Gdk.Color(13107, 21845, 65535), - Gdk.Color.from_floats(0.2, 1.0 / 3.0, 1.0)) - - self.assertEqual(Gdk.Color(13107, 21845, 65535).to_floats(), - (0.2, 1.0 / 3.0, 1.0)) - - self.assertEqual(Gdk.RGBA(0.2, 1.0 / 3.0, 1.0, 0.5).to_color(), - Gdk.Color.from_floats(0.2, 1.0 / 3.0, 1.0)) - - self.assertEqual(Gdk.RGBA.from_color(Gdk.Color(13107, 21845, 65535)), - Gdk.RGBA(0.2, 1.0 / 3.0, 1.0, 1.0)) - - def test_rgba(self): - self.assertEqual(Gdk.RGBA, gi.overrides.Gdk.RGBA) - rgba = Gdk.RGBA(0.1, 0.2, 0.3, 0.4) - self.assertEqual(rgba, Gdk.RGBA(0.1, 0.2, 0.3, 0.4)) - self.assertNotEqual(rgba, Gdk.RGBA(0.0, 0.2, 0.3, 0.4)) - self.assertEqual(rgba.red, 0.1) - self.assertEqual(rgba.green, 0.2) - self.assertEqual(rgba.blue, 0.3) - self.assertEqual(rgba.alpha, 0.4) - rgba.green = 0.9 - self.assertEqual(rgba.green, 0.9) - - # Iterator/tuple convsersion - self.assertEqual(tuple(Gdk.RGBA(0.1, 0.2, 0.3, 0.4)), - (0.1, 0.2, 0.3, 0.4)) - - def test_event(self): - event = Gdk.Event.new(Gdk.EventType.CONFIGURE) - self.assertEqual(event.type, Gdk.EventType.CONFIGURE) - self.assertEqual(event.send_event, 0) - - event = Gdk.Event() - event.type = Gdk.EventType.SCROLL - self.assertRaises(AttributeError, lambda: getattr(event, 'foo_bar')) - - def test_event_touch(self): - event = Gdk.Event.new(Gdk.EventType.TOUCH_BEGIN) - self.assertEqual(event.type, Gdk.EventType.TOUCH_BEGIN) - - # emulating_pointer is unique to touch events - self.assertFalse(event.emulating_pointer) - self.assertFalse(event.touch.emulating_pointer) - - event.emulating_pointer = True - self.assertTrue(event.emulating_pointer) - self.assertTrue(event.touch.emulating_pointer) - - def test_event_setattr(self): - event = Gdk.Event.new(Gdk.EventType.DRAG_MOTION) - event.x_root, event.y_root = 0, 5 - self.assertEqual(event.dnd.x_root, 0) - self.assertEqual(event.dnd.y_root, 5) - self.assertEqual(event.x_root, 0) - self.assertEqual(event.y_root, 5) - - # this used to work, keep it that way - self.assertFalse(hasattr(event, "foo_bar")) - event.foo_bar = 42 - - def test_event_repr(self): - event = Gdk.Event.new(Gdk.EventType.CONFIGURE) - self.assertTrue("CONFIGURE" in repr(event)) - - @unittest.skipIf(Gdk._version == "4.0", "not in gdk4") - def test_event_structures(self): - def button_press_cb(button, event): - self.assertTrue(isinstance(event, Gdk.EventButton)) - self.assertTrue(event.type == Gdk.EventType.BUTTON_PRESS) - self.assertEqual(event.send_event, 0) - self.assertEqual(event.get_state(), Gdk.ModifierType.CONTROL_MASK) - self.assertEqual(event.get_root_coords(), (2, 5)) - - event.time = 12345 - self.assertEqual(event.get_time(), 12345) - - w = Gtk.Window() - b = Gtk.Button() - b.connect('button-press-event', button_press_cb) - w.add(b) - b.show() - b.realize() - Gdk.test_simulate_button(b.get_window(), - 2, 5, - 0, - Gdk.ModifierType.CONTROL_MASK, - Gdk.EventType.BUTTON_PRESS) - - @unittest.skipIf(Gdk._version == "4.0", "not in gdk4") - def test_cursor(self): - self.assertEqual(Gdk.Cursor, gi.overrides.Gdk.Cursor) - with capture_glib_deprecation_warnings(): - c = Gdk.Cursor(Gdk.CursorType.WATCH) - self.assertNotEqual(c, None) - with capture_glib_deprecation_warnings(): - c = Gdk.Cursor(cursor_type=Gdk.CursorType.WATCH) - self.assertNotEqual(c, None) - - display_manager = Gdk.DisplayManager.get() - display = display_manager.get_default_display() - - test_pixbuf = GdkPixbuf.Pixbuf.new(GdkPixbuf.Colorspace.RGB, - False, - 8, - 5, - 10) - - with capture_glib_deprecation_warnings() as warn: - c = Gdk.Cursor(display, - test_pixbuf, - y=0, x=0) - self.assertNotEqual(c, None) - - self.assertEqual(len(warn), 1) - self.assertTrue(issubclass(warn[0].category, PyGIDeprecationWarning)) - self.assertRegexpMatches(str(warn[0].message), - '.*new_from_pixbuf.*') - - self.assertRaises(ValueError, Gdk.Cursor, 1, 2, 3) - - def test_flags(self): - self.assertEqual(Gdk.ModifierType.META_MASK | 0, 0x10000000) - self.assertEqual(hex(Gdk.ModifierType.META_MASK), '0x10000000') - self.assertEqual(str(Gdk.ModifierType.META_MASK), - '<flags GDK_META_MASK of type Gdk.ModifierType>') - - self.assertEqual(Gdk.ModifierType.RELEASE_MASK | 0, 0x40000000) - self.assertEqual(hex(Gdk.ModifierType.RELEASE_MASK), '0x40000000') - self.assertEqual(str(Gdk.ModifierType.RELEASE_MASK), - '<flags GDK_RELEASE_MASK of type Gdk.ModifierType>') - - self.assertEqual(Gdk.ModifierType.RELEASE_MASK | Gdk.ModifierType.META_MASK, 0x50000000) - self.assertEqual(str(Gdk.ModifierType.RELEASE_MASK | Gdk.ModifierType.META_MASK), - '<flags GDK_META_MASK | GDK_RELEASE_MASK of type Gdk.ModifierType>') - - @unittest.skipIf(Gdk._version == "4.0", "not in gdk4") - def test_color_parse(self): - with capture_glib_deprecation_warnings(): - c = Gdk.color_parse('#00FF80') - self.assertEqual(c.red, 0) - self.assertEqual(c.green, 65535) - self.assertEqual(c.blue, 32896) - self.assertEqual(Gdk.color_parse('bogus'), None) - - @unittest.skipIf(Gdk._version == "4.0", "not in gdk4") - def test_color_representations(self): - # __repr__ should generate a string which is parsable when possible - # http://docs.python.org/2/reference/datamodel.html#object.__repr__ - color = Gdk.Color(red=65535, green=32896, blue=1) - self.assertEqual(eval(repr(color)), color) - - rgba = Gdk.RGBA(red=1.0, green=0.8, blue=0.6, alpha=0.4) - self.assertEqual(eval(repr(rgba)), rgba) - - def test_rectangle_functions(self): - # https://bugzilla.gnome.org/show_bug.cgi?id=756364 - a = Gdk.Rectangle() - b = Gdk.Rectangle() - self.assertTrue(isinstance(Gdk.rectangle_union(a, b), Gdk.Rectangle)) - intersect, rect = Gdk.rectangle_intersect(a, b) - self.assertTrue(isinstance(rect, Gdk.Rectangle)) - self.assertTrue(isinstance(intersect, bool)) diff --git a/tests/test_overrides_glib.py b/tests/test_overrides_glib.py deleted file mode 100644 index 891923e..0000000 --- a/tests/test_overrides_glib.py +++ /dev/null @@ -1,533 +0,0 @@ -# -*- Mode: Python; py-indent-offset: 4 -*- -# vim: tabstop=4 shiftwidth=4 expandtab - -import gc -import unittest - -import gi -from gi.repository import GLib -from compathelper import _long - - -class TestGVariant(unittest.TestCase): - def test_create_simple(self): - variant = GLib.Variant('i', 42) - self.assertTrue(isinstance(variant, GLib.Variant)) - self.assertEqual(variant.get_int32(), 42) - - variant = GLib.Variant('s', '') - self.assertTrue(isinstance(variant, GLib.Variant)) - self.assertEqual(variant.get_string(), '') - - variant = GLib.Variant('s', 'hello') - self.assertTrue(isinstance(variant, GLib.Variant)) - self.assertEqual(variant.get_string(), 'hello') - - def test_create_variant(self): - variant = GLib.Variant('v', GLib.Variant('i', 42)) - self.assertTrue(isinstance(variant, GLib.Variant)) - self.assertTrue(isinstance(variant.get_variant(), GLib.Variant)) - self.assertEqual(variant.get_type_string(), 'v') - self.assertEqual(variant.get_variant().get_type_string(), 'i') - self.assertEqual(variant.get_variant().get_int32(), 42) - - variant = GLib.Variant('v', GLib.Variant('v', GLib.Variant('i', 42))) - self.assertEqual(variant.get_type_string(), 'v') - self.assertEqual(variant.get_variant().get_type_string(), 'v') - self.assertEqual(variant.get_variant().get_variant().get_type_string(), 'i') - self.assertEqual(variant.get_variant().get_variant().get_int32(), 42) - - def test_create_tuple(self): - variant = GLib.Variant('()', ()) - self.assertEqual(variant.get_type_string(), '()') - self.assertEqual(variant.n_children(), 0) - - variant = GLib.Variant('(i)', (3,)) - self.assertEqual(variant.get_type_string(), '(i)') - self.assertTrue(isinstance(variant, GLib.Variant)) - self.assertEqual(variant.n_children(), 1) - self.assertTrue(isinstance(variant.get_child_value(0), GLib.Variant)) - self.assertEqual(variant.get_child_value(0).get_int32(), 3) - - variant = GLib.Variant('(ss)', ('mec', 'mac')) - self.assertEqual(variant.get_type_string(), '(ss)') - self.assertTrue(isinstance(variant, GLib.Variant)) - self.assertTrue(isinstance(variant.get_child_value(0), GLib.Variant)) - self.assertTrue(isinstance(variant.get_child_value(1), GLib.Variant)) - self.assertEqual(variant.get_child_value(0).get_string(), 'mec') - self.assertEqual(variant.get_child_value(1).get_string(), 'mac') - - # nested tuples - variant = GLib.Variant('((si)(ub))', (('hello', -1), (42, True))) - self.assertEqual(variant.get_type_string(), '((si)(ub))') - self.assertEqual(variant.unpack(), (('hello', -1), (_long(42), True))) - - def test_new_tuple_sink(self): - # https://bugzilla.gnome.org/show_bug.cgi?id=735166 - variant = GLib.Variant.new_tuple(GLib.Variant.new_tuple()) - del variant - gc.collect() - - def test_create_dictionary(self): - variant = GLib.Variant('a{si}', {}) - self.assertTrue(isinstance(variant, GLib.Variant)) - self.assertEqual(variant.get_type_string(), 'a{si}') - self.assertEqual(variant.n_children(), 0) - - variant = GLib.Variant('a{si}', {'': 1, 'key1': 2, 'key2': 3}) - self.assertEqual(variant.get_type_string(), 'a{si}') - self.assertTrue(isinstance(variant, GLib.Variant)) - self.assertTrue(isinstance(variant.get_child_value(0), GLib.Variant)) - self.assertTrue(isinstance(variant.get_child_value(1), GLib.Variant)) - self.assertTrue(isinstance(variant.get_child_value(2), GLib.Variant)) - self.assertEqual(variant.unpack(), {'': 1, 'key1': 2, 'key2': 3}) - - # nested dictionaries - variant = GLib.Variant('a{sa{si}}', {}) - self.assertTrue(isinstance(variant, GLib.Variant)) - self.assertEqual(variant.get_type_string(), 'a{sa{si}}') - self.assertEqual(variant.n_children(), 0) - - d = {'': {'': 1, 'keyn1': 2}, - 'key1': {'key11': 11, 'key12': 12}} - variant = GLib.Variant('a{sa{si}}', d) - self.assertEqual(variant.get_type_string(), 'a{sa{si}}') - self.assertTrue(isinstance(variant, GLib.Variant)) - self.assertEqual(variant.unpack(), d) - - def test_create_array(self): - variant = GLib.Variant('ai', []) - self.assertEqual(variant.get_type_string(), 'ai') - self.assertEqual(variant.n_children(), 0) - - variant = GLib.Variant('ai', [1, 2]) - self.assertEqual(variant.get_type_string(), 'ai') - self.assertTrue(isinstance(variant, GLib.Variant)) - self.assertTrue(isinstance(variant.get_child_value(0), GLib.Variant)) - self.assertTrue(isinstance(variant.get_child_value(1), GLib.Variant)) - self.assertEqual(variant.get_child_value(0).get_int32(), 1) - self.assertEqual(variant.get_child_value(1).get_int32(), 2) - - variant = GLib.Variant('as', []) - self.assertEqual(variant.get_type_string(), 'as') - self.assertEqual(variant.n_children(), 0) - - variant = GLib.Variant('as', ['']) - self.assertEqual(variant.get_type_string(), 'as') - self.assertTrue(isinstance(variant, GLib.Variant)) - self.assertTrue(isinstance(variant.get_child_value(0), GLib.Variant)) - self.assertEqual(variant.get_child_value(0).get_string(), '') - - variant = GLib.Variant('as', ['hello', 'world']) - self.assertEqual(variant.get_type_string(), 'as') - self.assertTrue(isinstance(variant, GLib.Variant)) - self.assertTrue(isinstance(variant.get_child_value(0), GLib.Variant)) - self.assertTrue(isinstance(variant.get_child_value(1), GLib.Variant)) - self.assertEqual(variant.get_child_value(0).get_string(), 'hello') - self.assertEqual(variant.get_child_value(1).get_string(), 'world') - - # nested arrays - variant = GLib.Variant('aai', []) - self.assertEqual(variant.get_type_string(), 'aai') - self.assertEqual(variant.n_children(), 0) - - variant = GLib.Variant('aai', [[]]) - self.assertEqual(variant.get_type_string(), 'aai') - self.assertEqual(variant.n_children(), 1) - self.assertEqual(variant.get_child_value(0).n_children(), 0) - - variant = GLib.Variant('aai', [[1, 2], [3, 4, 5]]) - self.assertEqual(variant.get_type_string(), 'aai') - self.assertEqual(variant.unpack(), [[1, 2], [3, 4, 5]]) - - def test_create_complex(self): - variant = GLib.Variant('(as)', ([],)) - self.assertEqual(variant.get_type_string(), '(as)') - self.assertEqual(variant.n_children(), 1) - self.assertEqual(variant.get_child_value(0).n_children(), 0) - - variant = GLib.Variant('(as)', ([''],)) - self.assertEqual(variant.get_type_string(), '(as)') - self.assertEqual(variant.n_children(), 1) - self.assertEqual(variant.get_child_value(0).n_children(), 1) - self.assertEqual(variant.get_child_value(0).get_child_value(0).get_string(), '') - - variant = GLib.Variant('(as)', (['hello'],)) - self.assertEqual(variant.get_type_string(), '(as)') - self.assertEqual(variant.n_children(), 1) - self.assertEqual(variant.get_child_value(0).n_children(), 1) - self.assertEqual(variant.get_child_value(0).get_child_value(0).get_string(), 'hello') - - variant = GLib.Variant('a(ii)', []) - self.assertEqual(variant.get_type_string(), 'a(ii)') - self.assertEqual(variant.n_children(), 0) - - variant = GLib.Variant('a(ii)', [(5, 6)]) - self.assertEqual(variant.get_type_string(), 'a(ii)') - self.assertEqual(variant.n_children(), 1) - self.assertEqual(variant.get_child_value(0).n_children(), 2) - self.assertEqual(variant.get_child_value(0).get_child_value(0).get_int32(), 5) - self.assertEqual(variant.get_child_value(0).get_child_value(1).get_int32(), 6) - - variant = GLib.Variant('(a(ii))', ([],)) - self.assertEqual(variant.get_type_string(), '(a(ii))') - self.assertEqual(variant.n_children(), 1) - self.assertEqual(variant.get_child_value(0).n_children(), 0) - - variant = GLib.Variant('(a(ii))', ([(5, 6)],)) - self.assertEqual(variant.get_type_string(), '(a(ii))') - self.assertEqual(variant.n_children(), 1) - self.assertEqual(variant.get_child_value(0).n_children(), 1) - self.assertEqual(variant.get_child_value(0).get_child_value(0).n_children(), 2) - self.assertEqual(variant.get_child_value(0).get_child_value(0).get_child_value(0).get_int32(), 5) - self.assertEqual(variant.get_child_value(0).get_child_value(0).get_child_value(1).get_int32(), 6) - - obj = {'a1': (1, True), 'a2': (2, False)} - variant = GLib.Variant('a{s(ib)}', obj) - self.assertEqual(variant.get_type_string(), 'a{s(ib)}') - self.assertEqual(variant.unpack(), obj) - - obj = {'a1': (1, GLib.Variant('b', True)), 'a2': (2, GLib.Variant('y', 255))} - variant = GLib.Variant('a{s(iv)}', obj) - self.assertEqual(variant.get_type_string(), 'a{s(iv)}') - self.assertEqual(variant.unpack(), {'a1': (1, True), 'a2': (2, 255)}) - - obj = (1, {'a': {'a1': True, 'a2': False}, - 'b': {'b1': False}, - 'c': {} - }, - 'foo') - variant = GLib.Variant('(ia{sa{sb}}s)', obj) - self.assertEqual(variant.get_type_string(), '(ia{sa{sb}}s)') - self.assertEqual(variant.unpack(), obj) - - obj = {"frequency": GLib.Variant('t', 738000000), - "hierarchy": GLib.Variant('i', 0), - "bandwidth": GLib.Variant('x', 8), - "code-rate-hp": GLib.Variant('d', 2.0 / 3.0), - "constellation": GLib.Variant('s', "QAM16"), - "guard-interval": GLib.Variant('u', 4)} - variant = GLib.Variant('a{sv}', obj) - self.assertEqual(variant.get_type_string(), 'a{sv}') - self.assertEqual(variant.unpack(), - {"frequency": 738000000, - "hierarchy": 0, - "bandwidth": 8, - "code-rate-hp": 2.0 / 3.0, - "constellation": "QAM16", - "guard-interval": 4 - }) - - def test_create_errors(self): - # excess arguments - self.assertRaises(TypeError, GLib.Variant, 'i', 42, 3) - self.assertRaises(TypeError, GLib.Variant, '(i)', (42, 3)) - - # not enough arguments - self.assertRaises(TypeError, GLib.Variant, '(ii)', (42,)) - - # data type mismatch - self.assertRaises(TypeError, GLib.Variant, 'i', 'hello') - self.assertRaises(TypeError, GLib.Variant, 's', 42) - self.assertRaises(TypeError, GLib.Variant, '(ss)', 'mec', 'mac') - self.assertRaises(TypeError, GLib.Variant, '(s)', 'hello') - - # unimplemented data type - self.assertRaises(NotImplementedError, GLib.Variant, 'Q', 1) - - # invalid types - self.assertRaises(TypeError, GLib.Variant, '(ii', (42, 3)) - self.assertRaises(TypeError, GLib.Variant, '(ii))', (42, 3)) - self.assertRaises(TypeError, GLib.Variant, 'a{si', {}) - self.assertRaises(TypeError, GLib.Variant, 'a{si}}', {}) - self.assertRaises(TypeError, GLib.Variant, 'a{iii}', {}) - - def test_unpack(self): - # simple values - res = GLib.Variant.new_int32(-42).unpack() - self.assertEqual(res, -42) - - res = GLib.Variant.new_uint64(34359738368).unpack() - self.assertEqual(res, 34359738368) - - res = GLib.Variant.new_boolean(True).unpack() - self.assertEqual(res, True) - - res = GLib.Variant.new_object_path('/foo/Bar').unpack() - self.assertEqual(res, '/foo/Bar') - - # variant - res = GLib.Variant('v', GLib.Variant.new_int32(-42)).unpack() - self.assertEqual(res, -42) - - GLib.Variant('v', GLib.Variant('v', GLib.Variant('i', 42))) - self.assertEqual(res, -42) - - # tuple - res = GLib.Variant.new_tuple(GLib.Variant.new_int32(-1), - GLib.Variant.new_string('hello')).unpack() - self.assertEqual(res, (-1, 'hello')) - - # array - vb = GLib.VariantBuilder.new(gi._gi.variant_type_from_string('ai')) - vb.add_value(GLib.Variant.new_int32(-1)) - vb.add_value(GLib.Variant.new_int32(3)) - res = vb.end().unpack() - self.assertEqual(res, [-1, 3]) - - # dictionary - res = GLib.Variant('a{si}', {'key1': 1, 'key2': 2}).unpack() - self.assertEqual(res, {'key1': 1, 'key2': 2}) - - # maybe - v = GLib.Variant.new_maybe(GLib.VariantType.new('i'), GLib.Variant('i', 1)) - res = v.unpack() - self.assertEqual(res, 1) - v = GLib.Variant.new_maybe(GLib.VariantType.new('i'), None) - res = v.unpack() - self.assertEqual(res, None) - - def test_iteration(self): - # array index access - vb = GLib.VariantBuilder.new(gi._gi.variant_type_from_string('ai')) - vb.add_value(GLib.Variant.new_int32(-1)) - vb.add_value(GLib.Variant.new_int32(3)) - v = vb.end() - - self.assertEqual(len(v), 2) - self.assertEqual(v[0], -1) - self.assertEqual(v[1], 3) - self.assertEqual(v[-1], 3) - self.assertEqual(v[-2], -1) - self.assertRaises(IndexError, v.__getitem__, 2) - self.assertRaises(IndexError, v.__getitem__, -3) - self.assertRaises(ValueError, v.__getitem__, 'a') - - # array iteration - self.assertEqual([x for x in v], [-1, 3]) - self.assertEqual(list(v), [-1, 3]) - - # tuple index access - v = GLib.Variant.new_tuple(GLib.Variant.new_int32(-1), - GLib.Variant.new_string('hello')) - self.assertEqual(len(v), 2) - self.assertEqual(v[0], -1) - self.assertEqual(v[1], 'hello') - self.assertEqual(v[-1], 'hello') - self.assertEqual(v[-2], -1) - self.assertRaises(IndexError, v.__getitem__, 2) - self.assertRaises(IndexError, v.__getitem__, -3) - self.assertRaises(ValueError, v.__getitem__, 'a') - - # tuple iteration - self.assertEqual([x for x in v], [-1, 'hello']) - self.assertEqual(tuple(v), (-1, 'hello')) - - # dictionary index access - vsi = GLib.Variant('a{si}', {'key1': 1, 'key2': 2}) - vis = GLib.Variant('a{is}', {1: 'val1', 5: 'val2'}) - - self.assertEqual(len(vsi), 2) - self.assertEqual(vsi['key1'], 1) - self.assertEqual(vsi['key2'], 2) - self.assertRaises(KeyError, vsi.__getitem__, 'unknown') - - self.assertEqual(len(vis), 2) - self.assertEqual(vis[1], 'val1') - self.assertEqual(vis[5], 'val2') - self.assertRaises(KeyError, vsi.__getitem__, 3) - - # dictionary iteration - self.assertEqual(set(vsi.keys()), set(['key1', 'key2'])) - self.assertEqual(set(vis.keys()), set([1, 5])) - - # string index access - v = GLib.Variant('s', 'hello') - self.assertEqual(len(v), 5) - self.assertEqual(v[0], 'h') - self.assertEqual(v[4], 'o') - self.assertEqual(v[-1], 'o') - self.assertEqual(v[-5], 'h') - self.assertRaises(IndexError, v.__getitem__, 5) - self.assertRaises(IndexError, v.__getitem__, -6) - - # string iteration - self.assertEqual([x for x in v], ['h', 'e', 'l', 'l', 'o']) - - def test_split_signature(self): - self.assertEqual(GLib.Variant.split_signature('()'), []) - - self.assertEqual(GLib.Variant.split_signature('s'), ['s']) - - self.assertEqual(GLib.Variant.split_signature('as'), ['as']) - - self.assertEqual(GLib.Variant.split_signature('(s)'), ['s']) - - self.assertEqual(GLib.Variant.split_signature('(iso)'), ['i', 's', 'o']) - - self.assertEqual(GLib.Variant.split_signature('(s(ss)i(ii))'), - ['s', '(ss)', 'i', '(ii)']) - - self.assertEqual(GLib.Variant.split_signature('(as)'), ['as']) - - self.assertEqual(GLib.Variant.split_signature('(s(ss)iaiaasa(ii))'), - ['s', '(ss)', 'i', 'ai', 'aas', 'a(ii)']) - - self.assertEqual(GLib.Variant.split_signature('(a{iv}(ii)((ss)a{s(ss)}))'), - ['a{iv}', '(ii)', '((ss)a{s(ss)})']) - - def test_hash(self): - v1 = GLib.Variant('s', 'somestring') - v2 = GLib.Variant('s', 'somestring') - v3 = GLib.Variant('s', 'somestring2') - - self.assertTrue(v2 in set([v1, v3])) - self.assertTrue(v2 in frozenset([v1, v3])) - self.assertTrue(v2 in {v1: '1', v3: '2'}) - - def test_compare(self): - # Check if identical GVariant are equal - - def assert_equal(vtype, value): - self.assertEqual(GLib.Variant(vtype, value), GLib.Variant(vtype, value)) - - def assert_not_equal(vtype1, value1, vtype2, value2): - self.assertNotEqual(GLib.Variant(vtype1, value1), GLib.Variant(vtype2, value2)) - - numbers = ['y', 'n', 'q', 'i', 'u', 'x', 't', 'h', 'd'] - for num in numbers: - assert_equal(num, 42) - assert_not_equal(num, 42, num, 41) - assert_not_equal(num, 42, 's', '42') - - assert_equal('s', 'something') - assert_not_equal('s', 'something', 's', 'somethingelse') - assert_not_equal('s', 'something', 'i', 1234) - - assert_equal('g', 'dustybinqhogx') - assert_not_equal('g', 'dustybinqhogx', 'g', 'dustybin') - assert_not_equal('g', 'dustybinqhogx', 'i', 1234) - - assert_equal('o', '/dev/null') - assert_not_equal('o', '/dev/null', 'o', '/dev/zero') - assert_not_equal('o', '/dev/null', 'i', 1234) - - assert_equal('(s)', ('strtuple',)) - assert_not_equal('(s)', ('strtuple',), '(s)', ('strtuple2',)) - - assert_equal('a{si}', {'str': 42}) - assert_not_equal('a{si}', {'str': 42}, 'a{si}', {'str': 43}) - - assert_equal('v', GLib.Variant('i', 42)) - assert_not_equal('v', GLib.Variant('i', 42), 'v', GLib.Variant('i', 43)) - - def test_bool(self): - # Check if the GVariant bool matches the unpacked Pythonic bool - - def assert_equals_bool(vtype, value): - self.assertEqual(bool(GLib.Variant(vtype, value)), bool(value)) - - # simple values - assert_equals_bool('b', True) - assert_equals_bool('b', False) - - numbers = ['y', 'n', 'q', 'i', 'u', 'x', 't', 'h', 'd'] - for number in numbers: - assert_equals_bool(number, 0) - assert_equals_bool(number, 1) - - assert_equals_bool('s', '') - assert_equals_bool('g', '') - assert_equals_bool('s', 'something') - assert_equals_bool('o', '/dev/null') - assert_equals_bool('g', 'dustybinqhogx') - - # arrays - assert_equals_bool('ab', [True]) - assert_equals_bool('ab', [False]) - for number in numbers: - assert_equals_bool('a' + number, []) - assert_equals_bool('a' + number, [0]) - assert_equals_bool('as', []) - assert_equals_bool('as', ['']) - assert_equals_bool('ao', []) - assert_equals_bool('ao', ['/']) - assert_equals_bool('ag', []) - assert_equals_bool('ag', ['']) - assert_equals_bool('aai', [[]]) - - # tuples - assert_equals_bool('()', ()) - for number in numbers: - assert_equals_bool('(' + number + ')', (0,)) - assert_equals_bool('(s)', ('',)) - assert_equals_bool('(o)', ('/',)) - assert_equals_bool('(g)', ('',)) - assert_equals_bool('(())', ((),)) - - # dictionaries - assert_equals_bool('a{si}', {}) - assert_equals_bool('a{si}', {'': 0}) - - # complex types, always True - assert_equals_bool('(as)', ([],)) - assert_equals_bool('a{s(i)}', {'': (0,)}) - - # variant types, recursive unpacking - assert_equals_bool('v', GLib.Variant('i', 0)) - assert_equals_bool('v', GLib.Variant('i', 1)) - - def test_repr(self): - # with C constructor - v = GLib.Variant.new_uint32(42) - self.assertEqual(repr(v), "GLib.Variant('u', 42)") - - # with override constructor - v = GLib.Variant('(is)', (1, 'somestring')) - self.assertEqual(repr(v), "GLib.Variant('(is)', (1, 'somestring'))") - - def test_str(self): - # with C constructor - v = GLib.Variant.new_uint32(42) - self.assertEqual(str(v), 'uint32 42') - - # with override constructor - v = GLib.Variant('(is)', (1, 'somestring')) - self.assertEqual(str(v), "(1, 'somestring')") - - def test_parse_error(self): - # This test doubles as a test for GLib.Error marshaling. - source_str = 'abc' - with self.assertRaises(GLib.Error) as context: - GLib.Variant.parse(None, source_str, None, None) - e = context.exception - text = GLib.Variant.parse_error_print_context(e, source_str) - self.assertTrue(source_str in text) - - def test_parse_error_exceptions(self): - source_str = 'abc' - self.assertRaisesRegexp(TypeError, 'Must be GLib.Error, not int', - GLib.Variant.parse_error_print_context, - 42, source_str) - - gerror = GLib.Error(message=42) # not a string - self.assertRaisesRegexp(ValueError, ".*must have a 'message'.*", - GLib.Variant.parse_error_print_context, - gerror, source_str) - - gerror = GLib.Error(domain=42) # not a string - self.assertRaisesRegexp(ValueError, ".*must have a 'domain'.*", - GLib.Variant.parse_error_print_context, - gerror, source_str) - - gerror = GLib.Error(code='not an int') - self.assertRaisesRegexp(ValueError, ".*must have a 'code' int.*", - GLib.Variant.parse_error_print_context, - gerror, source_str) - - -class TestConstants(unittest.TestCase): - - def test_basic_types_limits(self): - self.assertTrue(isinstance(GLib.MINFLOAT, float)) - self.assertTrue(isinstance(GLib.MAXLONG, (int, _long))) diff --git a/tests/test_overrides_pango.py b/tests/test_overrides_pango.py deleted file mode 100644 index 5c09a6a..0000000 --- a/tests/test_overrides_pango.py +++ /dev/null @@ -1,47 +0,0 @@ -# -*- Mode: Python; py-indent-offset: 4 -*- -# vim: tabstop=4 shiftwidth=4 expandtab - -import unittest - -try: - from gi.repository import Pango - from gi.repository import PangoCairo -except ImportError: - Pango = None - PangoCairo = None - - -@unittest.skipUnless(Pango, 'Pango not available') -class TestPango(unittest.TestCase): - - def test_default_font_description(self): - desc = Pango.FontDescription() - self.assertEqual(desc.get_variant(), Pango.Variant.NORMAL) - - def test_font_description(self): - desc = Pango.FontDescription('monospace') - self.assertEqual(desc.get_family(), 'monospace') - self.assertEqual(desc.get_variant(), Pango.Variant.NORMAL) - - def test_layout(self): - self.assertRaises(TypeError, Pango.Layout) - context = Pango.Context() - layout = Pango.Layout(context) - self.assertEqual(layout.get_context(), context) - - layout.set_markup("Foobar") - self.assertEqual(layout.get_text(), "Foobar") - - def test_break_keyword_escape(self): - # https://bugzilla.gnome.org/show_bug.cgi?id=697363 - self.assertTrue(hasattr(Pango, 'break_')) - self.assertTrue(Pango.break_ is not None) - - def test_context_get_metrics(self): - # Test default "language" argument - font_map = PangoCairo.font_map_get_default() - context = font_map.create_context() - desc = Pango.FontDescription('monospace') - metrics1 = context.get_metrics(desc) - metrics2 = context.get_metrics(desc, context.get_language()) - self.assertEqual(metrics1.get_ascent(), metrics2.get_ascent()) diff --git a/tests/test_properties.py b/tests/test_properties.py index ce035cd..5ae2b47 100644 --- a/tests/test_properties.py +++ b/tests/test_properties.py @@ -1,156 +1,93 @@ # coding=utf-8 -import os -import gc import sys import struct -import types import unittest -import tempfile from gi.repository import GObject -from gi.repository.GObject import ParamFlags, GType, new +from gi.repository.GObject import GType, new, PARAM_READWRITE, \ + PARAM_CONSTRUCT, PARAM_READABLE, PARAM_WRITABLE, PARAM_CONSTRUCT_ONLY from gi.repository.GObject import \ - TYPE_INT, TYPE_UINT, TYPE_LONG, TYPE_ULONG, TYPE_INT64, \ - TYPE_UINT64, TYPE_GTYPE, TYPE_INVALID, TYPE_NONE, TYPE_STRV, \ - TYPE_INTERFACE, TYPE_CHAR, TYPE_UCHAR, TYPE_BOOLEAN, TYPE_FLOAT, \ - TYPE_DOUBLE, TYPE_POINTER, TYPE_BOXED, TYPE_PARAM, TYPE_OBJECT, \ - TYPE_STRING, TYPE_PYOBJECT, TYPE_VARIANT - -from gi.repository.GLib import \ - MININT, MAXINT, MAXUINT, MINLONG, MAXLONG, MAXULONG, \ - MAXUINT64, MAXINT64, MININT64 + TYPE_INT, TYPE_UINT, TYPE_LONG, TYPE_ULONG, TYPE_INT64, \ + TYPE_UINT64, TYPE_GTYPE, TYPE_INVALID, TYPE_NONE +from gi.repository.GObject import \ + G_MININT, G_MAXINT, G_MAXUINT, G_MINLONG, G_MAXLONG, \ + G_MAXULONG from gi.repository import Gio from gi.repository import GLib from gi.repository import GIMarshallingTests -from gi.repository import Regress -from gi import _propertyhelper as propertyhelper + +if sys.version_info < (3, 0): + TEST_UTF8 = "\xe2\x99\xa5" + UNICODE_UTF8 = unicode(TEST_UTF8, 'UTF-8') +else: + TEST_UTF8 = "♥" + UNICODE_UTF8 = TEST_UTF8 from compathelper import _long -from helper import capture_glib_warnings, capture_output class PropertyObject(GObject.GObject): normal = GObject.Property(type=str) construct = GObject.Property( type=str, - flags=ParamFlags.READABLE | ParamFlags.WRITABLE | ParamFlags.CONSTRUCT, - default='default') - + flags=PARAM_READWRITE | PARAM_CONSTRUCT, default='default') construct_only = GObject.Property( type=str, - flags=ParamFlags.READABLE | ParamFlags.WRITABLE | ParamFlags.CONSTRUCT_ONLY) - + flags=PARAM_READWRITE | PARAM_CONSTRUCT_ONLY) uint64 = GObject.Property( - type=TYPE_UINT64, - flags=ParamFlags.READABLE | ParamFlags.WRITABLE | ParamFlags.CONSTRUCT) + type=TYPE_UINT64, flags=PARAM_READWRITE | PARAM_CONSTRUCT) enum = GObject.Property( type=Gio.SocketType, default=Gio.SocketType.STREAM) boxed = GObject.Property( - type=GLib.Regex, - flags=ParamFlags.READABLE | ParamFlags.WRITABLE | ParamFlags.CONSTRUCT) + type=GLib.Regex, flags=PARAM_READWRITE | PARAM_CONSTRUCT) flags = GObject.Property( - type=GIMarshallingTests.Flags, - flags=ParamFlags.READABLE | ParamFlags.WRITABLE | ParamFlags.CONSTRUCT, + type=GIMarshallingTests.Flags, flags=PARAM_READWRITE | PARAM_CONSTRUCT, default=GIMarshallingTests.Flags.VALUE1) gtype = GObject.Property( - type=TYPE_GTYPE, - flags=ParamFlags.READABLE | ParamFlags.WRITABLE | ParamFlags.CONSTRUCT) - - strings = GObject.Property( - type=TYPE_STRV, - flags=ParamFlags.READABLE | ParamFlags.WRITABLE | ParamFlags.CONSTRUCT) - - variant = GObject.Property( - type=TYPE_VARIANT, - flags=ParamFlags.READABLE | ParamFlags.WRITABLE | ParamFlags.CONSTRUCT) - - variant_def = GObject.Property( - type=TYPE_VARIANT, - flags=ParamFlags.READABLE | ParamFlags.WRITABLE | ParamFlags.CONSTRUCT, - default=GLib.Variant('i', 42)) - - interface = GObject.Property( - type=Gio.File, - flags=ParamFlags.READABLE | ParamFlags.WRITABLE | ParamFlags.CONSTRUCT) - + type=TYPE_GTYPE, flags=PARAM_READWRITE | PARAM_CONSTRUCT) -class PropertyInheritanceObject(Regress.TestObj): - # override property from the base class, with a different type - string = GObject.Property(type=int) - # a property entirely defined at the Python level - python_prop = GObject.Property(type=str) - - -class PropertySubClassObject(PropertyInheritanceObject): - # override property from the base class, with a different type - python_prop = GObject.Property(type=int) - - -class TestPropertyInheritanceObject(unittest.TestCase): - def test_override_gi_property(self): - self.assertNotEqual(Regress.TestObj.props.string.value_type, - PropertyInheritanceObject.props.string.value_type) - obj = PropertyInheritanceObject() - self.assertEqual(type(obj.props.string), int) - obj.props.string = 4 - self.assertEqual(obj.props.string, 4) - - def test_override_python_property(self): - obj = PropertySubClassObject() - self.assertEqual(type(obj.props.python_prop), int) - obj.props.python_prop = 5 - self.assertEqual(obj.props.python_prop, 5) - - -class TestPropertyObject(unittest.TestCase): - def test_get_set(self): +class TestProperties(unittest.TestCase): + def testGetSet(self): obj = PropertyObject() obj.props.normal = "value" self.assertEqual(obj.props.normal, "value") - def test_hasattr_on_object(self): + def testListWithInstance(self): obj = PropertyObject() self.assertTrue(hasattr(obj.props, "normal")) - def test_hasattr_on_class(self): + def testListWithoutInstance(self): self.assertTrue(hasattr(PropertyObject.props, "normal")) - def test_set_on_class(self): + def testSetNoInstance(self): def set(obj): obj.props.normal = "foobar" self.assertRaises(TypeError, set, PropertyObject) - def test_iteration(self): + def testIterator(self): for obj in (PropertyObject.props, PropertyObject().props): - names = [] for pspec in obj: gtype = GType(pspec) self.assertEqual(gtype.parent.name, 'GParam') - names.append(pspec.name) - - names.sort() - self.assertEqual(names, ['boxed', - 'construct', - 'construct-only', - 'enum', - 'flags', - 'gtype', - 'interface', - 'normal', - 'strings', - 'uint64', - 'variant', - 'variant-def']) - - def test_normal(self): + self.assertTrue(pspec.name in ['normal', + 'construct', + 'construct-only', + 'uint64', + 'enum', + 'flags', + 'gtype', + 'boxed']) + self.assertEqual(len(obj), 8) + + def testNormal(self): obj = new(PropertyObject, normal="123") self.assertEqual(obj.props.normal, "123") obj.set_property('normal', '456') @@ -158,7 +95,7 @@ class TestPropertyObject(unittest.TestCase): obj.props.normal = '789' self.assertEqual(obj.props.normal, "789") - def test_construct(self): + def testConstruct(self): obj = new(PropertyObject, construct="123") self.assertEqual(obj.props.construct, "123") obj.set_property('construct', '456') @@ -166,17 +103,15 @@ class TestPropertyObject(unittest.TestCase): obj.props.construct = '789' self.assertEqual(obj.props.construct, "789") - def test_utf8(self): - test_utf8 = "♥" - unicode_utf8 = u"♥" - obj = new(PropertyObject, construct_only=unicode_utf8) - self.assertEqual(obj.props.construct_only, test_utf8) - obj.set_property('construct', unicode_utf8) - self.assertEqual(obj.props.construct, test_utf8) - obj.props.normal = unicode_utf8 - self.assertEqual(obj.props.normal, test_utf8) - - def test_int_to_str(self): + def testUTF8(self): + obj = new(PropertyObject, construct_only=UNICODE_UTF8) + self.assertEqual(obj.props.construct_only, TEST_UTF8) + obj.set_property('construct', UNICODE_UTF8) + self.assertEqual(obj.props.construct, TEST_UTF8) + obj.props.normal = UNICODE_UTF8 + self.assertEqual(obj.props.normal, TEST_UTF8) + + def testIntToStr(self): obj = new(PropertyObject, construct_only=1) self.assertEqual(obj.props.construct_only, '1') obj.set_property('construct', '2') @@ -184,7 +119,7 @@ class TestPropertyObject(unittest.TestCase): obj.props.normal = 3 self.assertEqual(obj.props.normal, '3') - def test_construct_only(self): + def testConstructOnly(self): obj = new(PropertyObject, construct_only="123") self.assertEqual(obj.props.construct_only, "123") self.assertRaises(TypeError, @@ -192,7 +127,7 @@ class TestPropertyObject(unittest.TestCase): self.assertRaises(TypeError, obj.set_property, 'construct-only', '456') - def test_uint64(self): + def testUint64(self): obj = new(PropertyObject) self.assertEqual(obj.props.uint64, 0) obj.props.uint64 = _long(1) @@ -203,19 +138,19 @@ class TestPropertyObject(unittest.TestCase): self.assertRaises((TypeError, OverflowError), obj.set_property, "uint64", _long(-1)) self.assertRaises((TypeError, OverflowError), obj.set_property, "uint64", -1) - def test_uint64_default_value(self): + def testUInt64DefaultValue(self): try: class TimeControl(GObject.GObject): __gproperties__ = { 'time': (TYPE_UINT64, 'Time', 'Time', _long(0), (1 << 64) - 1, _long(0), - ParamFlags.READABLE) + PARAM_READABLE) } except OverflowError: (etype, ex) = sys.exc_info()[2:] self.fail(str(ex)) - def test_enum(self): + def testEnum(self): obj = new(PropertyObject) self.assertEqual(obj.props.enum, Gio.SocketType.STREAM) self.assertEqual(obj.enum, Gio.SocketType.STREAM) @@ -243,7 +178,7 @@ class TestPropertyObject(unittest.TestCase): self.assertRaises(TypeError, GObject.Property, type=Gio.SocketType, default=1) - def test_flags(self): + def testFlags(self): obj = new(PropertyObject) self.assertEqual(obj.props.flags, GIMarshallingTests.Flags.VALUE1) self.assertEqual(obj.flags, GIMarshallingTests.Flags.VALUE1) @@ -257,13 +192,13 @@ class TestPropertyObject(unittest.TestCase): self.assertRaises(TypeError, setattr, obj, 'flags', None) self.assertRaises(TypeError, GObject.Property, - type=GIMarshallingTests.Flags, default='foo') + type=GIMarshallingTests.Flags, default='foo') self.assertRaises(TypeError, GObject.Property, - type=GIMarshallingTests.Flags, default=object()) + type=GIMarshallingTests.Flags, default=object()) self.assertRaises(TypeError, GObject.Property, - type=GIMarshallingTests.Flags, default=None) + type=GIMarshallingTests.Flags, default=None) - def test_gtype(self): + def testGType(self): obj = new(PropertyObject) self.assertEqual(obj.props.gtype, TYPE_NONE) @@ -279,142 +214,34 @@ class TestPropertyObject(unittest.TestCase): # GType parameters do not support defaults in GLib self.assertRaises(TypeError, GObject.Property, type=TYPE_GTYPE, - default=TYPE_INT) + default=TYPE_INT) # incompatible type self.assertRaises(TypeError, setattr, obj, 'gtype', 'foo') self.assertRaises(TypeError, setattr, obj, 'gtype', object()) self.assertRaises(TypeError, GObject.Property, type=TYPE_GTYPE, - default='foo') + default='foo') self.assertRaises(TypeError, GObject.Property, type=TYPE_GTYPE, - default=object()) + default=object()) # set in constructor obj = new(PropertyObject, gtype=TYPE_UINT) self.assertEqual(obj.props.gtype, TYPE_UINT) self.assertEqual(obj.gtype, TYPE_UINT) - def test_boxed(self): + def textBoxed(self): obj = new(PropertyObject) regex = GLib.Regex.new('[a-z]*', 0, 0) obj.props.boxed = regex self.assertEqual(obj.props.boxed.get_pattern(), '[a-z]*') - self.assertEqual(obj.boxed.get_pattern(), '[a-z]*') + self.assertEqual(obj.boxed.get_patttern(), '[a-z]*') self.assertRaises(TypeError, setattr, obj, 'boxed', 'foo') self.assertRaises(TypeError, setattr, obj, 'boxed', object()) - def test_strings(self): - obj = new(PropertyObject) - - # Should work with actual GStrv objects as well as - # Python string lists - class GStrv(list): - __gtype__ = GObject.TYPE_STRV - - self.assertEqual(obj.props.strings, GStrv([])) - self.assertEqual(obj.strings, GStrv([])) - self.assertEqual(obj.props.strings, []) - self.assertEqual(obj.strings, []) - - obj.strings = ['hello', 'world'] - self.assertEqual(obj.props.strings, ['hello', 'world']) - self.assertEqual(obj.strings, ['hello', 'world']) - - obj.strings = GStrv(['hello', 'world']) - self.assertEqual(obj.props.strings, GStrv(['hello', 'world'])) - self.assertEqual(obj.strings, GStrv(['hello', 'world'])) - - obj.strings = [] - self.assertEqual(obj.strings, []) - obj.strings = GStrv([]) - self.assertEqual(obj.strings, GStrv([])) - - p = GObject.Property(type=TYPE_STRV, default=['hello', '1']) - self.assertEqual(p.default, ['hello', '1']) - self.assertEqual(p.type, TYPE_STRV) - p = GObject.Property(type=TYPE_STRV, default=GStrv(['hello', '1'])) - self.assertEqual(p.default, ['hello', '1']) - self.assertEqual(p.type, TYPE_STRV) - - # set in constructor - obj = new(PropertyObject, strings=['hello', 'world']) - self.assertEqual(obj.props.strings, ['hello', 'world']) - self.assertEqual(obj.strings, ['hello', 'world']) - - # wrong types - self.assertRaises(TypeError, setattr, obj, 'strings', 1) - self.assertRaises(TypeError, setattr, obj, 'strings', 'foo') - self.assertRaises(TypeError, setattr, obj, 'strings', ['foo', 1]) - - self.assertRaises(TypeError, GObject.Property, type=TYPE_STRV, - default=1) - self.assertRaises(TypeError, GObject.Property, type=TYPE_STRV, - default='foo') - self.assertRaises(TypeError, GObject.Property, type=TYPE_STRV, - default=['hello', 1]) - - def test_variant(self): - obj = new(PropertyObject) - - self.assertEqual(obj.props.variant, None) - self.assertEqual(obj.variant, None) - - obj.variant = GLib.Variant('s', 'hello') - self.assertEqual(obj.variant.print_(True), "'hello'") - - obj.variant = GLib.Variant('b', True) - self.assertEqual(obj.variant.print_(True), "true") - - obj.props.variant = GLib.Variant('y', 2) - self.assertEqual(obj.variant.print_(True), "byte 0x02") - - obj.variant = None - self.assertEqual(obj.variant, None) - - # set in constructor - obj = new(PropertyObject, variant=GLib.Variant('u', 5)) - self.assertEqual(obj.props.variant.print_(True), 'uint32 5') - - GObject.Property(type=TYPE_VARIANT, default=GLib.Variant('i', 1)) - - # incompatible types - self.assertRaises(TypeError, setattr, obj, 'variant', 'foo') - self.assertRaises(TypeError, setattr, obj, 'variant', 42) - - self.assertRaises(TypeError, GObject.Property, type=TYPE_VARIANT, - default='foo') - self.assertRaises(TypeError, GObject.Property, type=TYPE_VARIANT, - default=object()) - - def test_variant_default(self): - obj = new(PropertyObject) - - self.assertEqual(obj.props.variant_def.print_(True), '42') - self.assertEqual(obj.variant_def.print_(True), '42') - - obj.props.variant_def = GLib.Variant('y', 2) - self.assertEqual(obj.variant_def.print_(True), "byte 0x02") - - # set in constructor - obj = new(PropertyObject, variant_def=GLib.Variant('u', 5)) - self.assertEqual(obj.props.variant_def.print_(True), 'uint32 5') - - def test_interface(self): - obj = new(PropertyObject) - - path = os.path.join(tempfile.gettempdir(), "some", "path") - file = Gio.File.new_for_path(path) - obj.props.interface = file - self.assertEqual(obj.props.interface.get_path(), path) - self.assertEqual(obj.interface.get_path(), path) - - self.assertRaises(TypeError, setattr, obj, 'interface', 'foo') - self.assertRaises(TypeError, setattr, obj, 'interface', object()) - - def test_range(self): + def testRange(self): # kiwi code def max(c): return 2 ** ((8 * struct.calcsize(c)) - 1) - 1 @@ -432,22 +259,22 @@ class TestPropertyObject(unittest.TestCase): minint64 = -maxint64 - 1 maxuint64 = umax('Q') - types_ = dict(int=(TYPE_INT, minint, maxint), - uint=(TYPE_UINT, 0, maxuint), - long=(TYPE_LONG, minlong, maxlong), - ulong=(TYPE_ULONG, 0, maxulong), - int64=(TYPE_INT64, minint64, maxint64), - uint64=(TYPE_UINT64, 0, maxuint64)) + types = dict(int=(TYPE_INT, minint, maxint), + uint=(TYPE_UINT, 0, maxuint), + long=(TYPE_LONG, minlong, maxlong), + ulong=(TYPE_ULONG, 0, maxulong), + int64=(TYPE_INT64, minint64, maxint64), + uint64=(TYPE_UINT64, 0, maxuint64)) - def build_gproperties(types_): + def build_gproperties(types): d = {} - for key, (gtype, min, max) in types_.items(): + for key, (gtype, min, max) in types.items(): d[key] = (gtype, 'blurb', 'desc', min, max, 0, - ParamFlags.READABLE | ParamFlags.WRITABLE) + PARAM_READABLE | PARAM_WRITABLE) return d class RangeCheck(GObject.GObject): - __gproperties__ = build_gproperties(types_) + __gproperties__ = build_gproperties(types) def __init__(self): self.values = {} @@ -473,7 +300,7 @@ class TestPropertyObject(unittest.TestCase): self.assertEqual(RangeCheck.props.uint64.maximum, maxuint64) obj = RangeCheck() - for key, (gtype, min, max) in types_.items(): + for key, (gtype, min, max) in types.items(): self.assertEqual(obj.get_property(key), getattr(RangeCheck.props, key).default_value) @@ -483,7 +310,7 @@ class TestPropertyObject(unittest.TestCase): obj.set_property(key, max) self.assertEqual(obj.get_property(key), max) - def test_multi(self): + def testMulti(self): obj = PropertyObject() obj.set_properties(normal="foo", uint64=7) @@ -493,7 +320,7 @@ class TestPropertyObject(unittest.TestCase): class TestProperty(unittest.TestCase): - def test_simple(self): + def testSimple(self): class C(GObject.GObject): str = GObject.Property(type=str) int = GObject.Property(type=int) @@ -522,7 +349,7 @@ class TestProperty(unittest.TestCase): o.long = _long(100) self.assertEqual(o.long, _long(100)) - def test_custom_getter(self): + def testCustomGetter(self): class C(GObject.GObject): def get_prop(self): return 'value' @@ -532,27 +359,7 @@ class TestProperty(unittest.TestCase): self.assertEqual(o.prop, 'value') self.assertRaises(TypeError, setattr, o, 'prop', 'xxx') - @unittest.expectedFailure # https://bugzilla.gnome.org/show_bug.cgi?id=575652 - def test_getter_exception(self): - class C(GObject.Object): - @GObject.Property(type=int) - def prop(self): - raise ValueError('something bad happend') - - o = C() - - # silence exception printed to stderr - with capture_output(): - with self.assertRaisesRegex(ValueError, 'something bad happend'): - o.prop - - with self.assertRaisesRegex(ValueError, 'something bad happend'): - o.get_property('prop') - - with self.assertRaisesRegex(ValueError, 'something bad happend'): - o.props.prop - - def test_custom_setter(self): + def testCustomSetter(self): class C(GObject.GObject): def set_prop(self, value): self._value = value @@ -568,7 +375,7 @@ class TestProperty(unittest.TestCase): self.assertEqual(o._value, 'bar') self.assertRaises(TypeError, getattr, o, 'prop') - def test_decorator_default(self): + def testDecoratorDefault(self): class C(GObject.GObject): _value = 'value' @@ -586,25 +393,7 @@ class TestProperty(unittest.TestCase): self.assertEqual(o.value, 'blah') self.assertEqual(o.props.value, 'blah') - def test_decorator_private_setter(self): - class C(GObject.GObject): - _value = 'value' - - @GObject.Property - def value(self): - return self._value - - @value.setter - def _set_value(self, value): - self._value = value - - o = C() - self.assertEqual(o.value, 'value') - o.value = 'blah' - self.assertEqual(o.value, 'blah') - self.assertEqual(o.props.value, 'blah') - - def test_decorator_with_call(self): + def testDecoratorWithCall(self): class C(GObject.GObject): _value = 1 @@ -622,7 +411,7 @@ class TestProperty(unittest.TestCase): self.assertEqual(o.typedValue, 5) self.assertEqual(o.props.typedValue, 5) - def test_errors(self): + def testErrors(self): self.assertRaises(TypeError, GObject.Property, type='str') self.assertRaises(TypeError, GObject.Property, nick=False) self.assertRaises(TypeError, GObject.Property, blurb=False) @@ -634,32 +423,38 @@ class TestProperty(unittest.TestCase): self.assertRaises(TypeError, GObject.Property, type=bool) self.assertRaises(TypeError, GObject.Property, type=object, default=0) self.assertRaises(TypeError, GObject.Property, type=complex) + self.assertRaises(TypeError, GObject.Property, flags=-10) - def test_defaults(self): + def testDefaults(self): GObject.Property(type=bool, default=True) GObject.Property(type=bool, default=False) - def test_name_with_underscore(self): + def testNameWithUnderscore(self): class C(GObject.GObject): prop_name = GObject.Property(type=int) o = C() o.prop_name = 10 self.assertEqual(o.prop_name, 10) - def test_range(self): - types_ = [ - (TYPE_INT, MININT, MAXINT), - (TYPE_UINT, 0, MAXUINT), - (TYPE_LONG, MINLONG, MAXLONG), - (TYPE_ULONG, 0, MAXULONG), - (TYPE_INT64, MININT64, MAXINT64), - (TYPE_UINT64, 0, MAXUINT64), + def testRange(self): + maxint64 = 2 ** 62 - 1 + minint64 = -2 ** 62 - 1 + maxuint64 = 2 ** 63 - 1 + + types = [ + (TYPE_INT, G_MININT, G_MAXINT), + (TYPE_UINT, 0, G_MAXUINT), + (TYPE_LONG, G_MINLONG, G_MAXLONG), + (TYPE_ULONG, 0, G_MAXULONG), + (TYPE_INT64, minint64, maxint64), + (TYPE_UINT64, 0, maxuint64), ] - for gtype, min, max in types_: + for gtype, min, max in types: # Normal, everything is alright prop = GObject.Property(type=gtype, minimum=min, maximum=max) - subtype = type('', (GObject.GObject,), dict(prop=prop)) + subtype = type('', (GObject.GObject,), + dict(prop=prop)) self.assertEqual(subtype.props.prop.minimum, min) self.assertEqual(subtype.props.prop.maximum, max) @@ -673,7 +468,7 @@ class TestProperty(unittest.TestCase): GObject.Property, type=gtype, minimum=min, maximum=max + 1) - def test_min_max(self): + def testMinMax(self): class C(GObject.GObject): prop_int = GObject.Property(type=int, minimum=1, maximum=100, default=1) prop_float = GObject.Property(type=float, minimum=0.1, maximum=10.5, default=1.1) @@ -683,7 +478,8 @@ class TestProperty(unittest.TestCase): # we test known-bad values here which cause Gtk-WARNING logs. # Explicitly allow these for this test. - with capture_glib_warnings(allow_warnings=True): + old_mask = GLib.log_set_always_fatal(GLib.LogLevelFlags.LEVEL_CRITICAL) + try: o = C() self.assertEqual(o.prop_int, 1) @@ -706,8 +502,10 @@ class TestProperty(unittest.TestCase): o.prop_float = 10.51 self.assertEqual(o.prop_float, 7.75) + finally: + GLib.log_set_always_fatal(old_mask) - def test_multiple_instances(self): + def testMultipleInstances(self): class C(GObject.GObject): prop = GObject.Property(type=str, default='default') @@ -719,7 +517,7 @@ class TestProperty(unittest.TestCase): self.assertEqual(o1.prop, 'value') self.assertEqual(o2.prop, 'default') - def test_object_property(self): + def testObjectProperty(self): class PropertyObject(GObject.GObject): obj = GObject.Property(type=GObject.GObject) @@ -732,7 +530,7 @@ class TestProperty(unittest.TestCase): pobj1 = pobj2.obj self.assertEqual(hash(pobj1), obj1_hash) - def test_object_subclass_property(self): + def testObjectSubclassProperty(self): class ObjectSubclass(GObject.GObject): __gtype_name__ = 'ObjectSubclass' @@ -741,7 +539,7 @@ class TestProperty(unittest.TestCase): PropertyObjectSubclass(obj=ObjectSubclass()) - def test_property_subclass(self): + def testPropertySubclass(self): # test for #470718 class A(GObject.GObject): prop1 = GObject.Property(type=int) @@ -755,26 +553,7 @@ class TestProperty(unittest.TestCase): b.prop1 = 20 self.assertEqual(b.prop1, 20) - def test_property_subclass_c(self): - class A(Regress.TestSubObj): - prop1 = GObject.Property(type=int) - - a = A() - a.prop1 = 10 - self.assertEqual(a.prop1, 10) - - # also has parent properties - a.props.int = 20 - self.assertEqual(a.props.int, 20) - - # Some of which are unusable without introspection - a.props.list = ("str1", "str2") - self.assertEqual(a.props.list, ["str1", "str2"]) - - a.set_property("list", ("str3", "str4")) - self.assertEqual(a.props.list, ["str3", "str4"]) - - def test_property_subclass_custom_setter(self): + def testPropertySubclassCustomSetter(self): # test for #523352 class A(GObject.GObject): def get_first(self): @@ -796,7 +575,7 @@ class TestProperty(unittest.TestCase): self.assertEqual(b.second, 'second') self.assertRaises(TypeError, setattr, b, 'second', 'foo') - def test_property_subclass_custom_setter_error(self): + def testPropertySubclassCustomSetterError(self): try: class A(GObject.GObject): def get_first(self): @@ -819,7 +598,7 @@ class TestProperty(unittest.TestCase): # Bug 644039 - def test_reference_count(self): + def testReferenceCount(self): # We can check directly if an object gets finalized, so we will # observe it indirectly through the refcount of a member object. @@ -840,483 +619,14 @@ class TestProperty(unittest.TestCase): del t self.assertEqual(sys.getrefcount(o), rc) - def test_doc_strings(self): + def testDocStringAsBlurb(self): class C(GObject.GObject): - foo_blurbed = GObject.Property(type=int, blurb='foo_blurbed doc string') - @GObject.Property - def foo_getter(self): - """foo_getter doc string""" + def blurbed(self): + """blurbed doc string""" return 0 - self.assertEqual(C.foo_blurbed.blurb, 'foo_blurbed doc string') - self.assertEqual(C.foo_blurbed.__doc__, 'foo_blurbed doc string') - - self.assertEqual(C.foo_getter.blurb, 'foo_getter doc string') - self.assertEqual(C.foo_getter.__doc__, 'foo_getter doc string') - - def test_python_to_glib_type_mapping(self): - tester = GObject.Property() - self.assertEqual(tester._type_from_python(int), GObject.TYPE_INT) - if sys.version_info < (3, 0): - self.assertEqual(tester._type_from_python(long), GObject.TYPE_LONG) - self.assertEqual(tester._type_from_python(bool), GObject.TYPE_BOOLEAN) - self.assertEqual(tester._type_from_python(float), GObject.TYPE_DOUBLE) - self.assertEqual(tester._type_from_python(str), GObject.TYPE_STRING) - self.assertEqual(tester._type_from_python(object), GObject.TYPE_PYOBJECT) - - self.assertEqual(tester._type_from_python(GObject.GObject), GObject.GObject.__gtype__) - self.assertEqual(tester._type_from_python(GObject.GEnum), GObject.GEnum.__gtype__) - self.assertEqual(tester._type_from_python(GObject.GFlags), GObject.GFlags.__gtype__) - self.assertEqual(tester._type_from_python(GObject.GBoxed), GObject.GBoxed.__gtype__) - self.assertEqual(tester._type_from_python(GObject.GInterface), GObject.GInterface.__gtype__) - - for type_ in [TYPE_NONE, TYPE_INTERFACE, TYPE_CHAR, TYPE_UCHAR, - TYPE_INT, TYPE_UINT, TYPE_BOOLEAN, TYPE_LONG, - TYPE_ULONG, TYPE_INT64, TYPE_UINT64, - TYPE_FLOAT, TYPE_DOUBLE, TYPE_POINTER, - TYPE_BOXED, TYPE_PARAM, TYPE_OBJECT, TYPE_STRING, - TYPE_PYOBJECT, TYPE_GTYPE, TYPE_STRV]: - self.assertEqual(tester._type_from_python(type_), type_) - - self.assertRaises(TypeError, tester._type_from_python, types.CodeType) - - -class TestInstallProperties(unittest.TestCase): - # These tests only test how signalhelper.install_signals works - # with the __gsignals__ dict and therefore does not need to use - # GObject as a base class because that would automatically call - # install_signals within the meta-class. - class Base(object): - __gproperties__ = {'test': (0, '', '', 0, 0, 0, 0)} - - class Sub1(Base): - pass - - class Sub2(Base): - @GObject.Property(type=int) - def sub2test(self): - return 123 - - class ClassWithPropertyAndGetterVFunc(object): - @GObject.Property(type=int) - def sub2test(self): - return 123 - - def do_get_property(self, name): - return 321 - - class ClassWithPropertyRedefined(object): - __gproperties__ = {'test': (0, '', '', 0, 0, 0, 0)} - test = GObject.Property(type=int) - - def setUp(self): - self.assertEqual(len(self.Base.__gproperties__), 1) - propertyhelper.install_properties(self.Base) - self.assertEqual(len(self.Base.__gproperties__), 1) - - def test_subclass_without_properties_is_not_modified(self): - self.assertFalse('__gproperties__' in self.Sub1.__dict__) - propertyhelper.install_properties(self.Sub1) - self.assertFalse('__gproperties__' in self.Sub1.__dict__) - - def test_subclass_with_decorator_gets_gproperties_dict(self): - # Sub2 has Property instances but will not have a __gproperties__ - # until install_properties is called - self.assertFalse('__gproperties__' in self.Sub2.__dict__) - self.assertFalse('do_get_property' in self.Sub2.__dict__) - self.assertFalse('do_set_property' in self.Sub2.__dict__) - - propertyhelper.install_properties(self.Sub2) - self.assertTrue('__gproperties__' in self.Sub2.__dict__) - self.assertEqual(len(self.Base.__gproperties__), 1) - self.assertEqual(len(self.Sub2.__gproperties__), 1) - self.assertTrue('sub2test' in self.Sub2.__gproperties__) - - # get/set vfuncs should have been added - self.assertTrue('do_get_property' in self.Sub2.__dict__) - self.assertTrue('do_set_property' in self.Sub2.__dict__) - - def test_object_with_property_and_do_get_property_vfunc_raises(self): - self.assertRaises(TypeError, propertyhelper.install_properties, - self.ClassWithPropertyAndGetterVFunc) - - def test_same_name_property_definitions_raises(self): - self.assertRaises(ValueError, propertyhelper.install_properties, - self.ClassWithPropertyRedefined) - - -class CPropertiesTestBase(object): - # Tests for properties implemented in C not Python. - - def setUp(self): - self.obj = GIMarshallingTests.PropertiesObject() - - def get_prop(self, obj, name): - raise NotImplementedError - - def set_prop(self, obj, name, value): - raise NotImplementedError - - # https://bugzilla.gnome.org/show_bug.cgi?id=780652 - @unittest.skipUnless( - "some_flags" in dir(GIMarshallingTests.PropertiesObject.props), - "tool old gi") - def test_flags(self): - self.assertEqual( - self.get_prop(self.obj, 'some-flags'), - GIMarshallingTests.Flags.VALUE1) - self.set_prop(self.obj, 'some-flags', GIMarshallingTests.Flags.VALUE2) - self.assertEqual(self.get_prop(self.obj, 'some-flags'), - GIMarshallingTests.Flags.VALUE2) - - obj = GIMarshallingTests.PropertiesObject( - some_flags=GIMarshallingTests.Flags.VALUE3) - self.assertEqual(self.get_prop(obj, 'some-flags'), - GIMarshallingTests.Flags.VALUE3) - - # https://bugzilla.gnome.org/show_bug.cgi?id=780652 - @unittest.skipUnless( - "some_enum" in dir(GIMarshallingTests.PropertiesObject.props), - "tool old gi") - def test_enum(self): - self.assertEqual( - self.get_prop(self.obj, 'some-enum'), - GIMarshallingTests.GEnum.VALUE1) - self.set_prop(self.obj, 'some-enum', GIMarshallingTests.GEnum.VALUE2) - self.assertEqual(self.get_prop(self.obj, 'some-enum'), - GIMarshallingTests.GEnum.VALUE2) - - obj = GIMarshallingTests.PropertiesObject( - some_enum=GIMarshallingTests.GEnum.VALUE3) - self.assertEqual(self.get_prop(obj, 'some-enum'), - GIMarshallingTests.GEnum.VALUE3) - - def test_boolean(self): - self.assertEqual(self.get_prop(self.obj, 'some-boolean'), False) - self.set_prop(self.obj, 'some-boolean', True) - self.assertEqual(self.get_prop(self.obj, 'some-boolean'), True) - - obj = GIMarshallingTests.PropertiesObject(some_boolean=True) - self.assertEqual(self.get_prop(obj, 'some-boolean'), True) - - def test_char(self): - self.assertEqual(self.get_prop(self.obj, 'some-char'), 0) - self.set_prop(self.obj, 'some-char', GLib.MAXINT8) - self.assertEqual(self.get_prop(self.obj, 'some-char'), GLib.MAXINT8) - - obj = GIMarshallingTests.PropertiesObject(some_char=-42) - self.assertEqual(self.get_prop(obj, 'some-char'), -42) - - def test_uchar(self): - self.assertEqual(self.get_prop(self.obj, 'some-uchar'), 0) - self.set_prop(self.obj, 'some-uchar', GLib.MAXUINT8) - self.assertEqual(self.get_prop(self.obj, 'some-uchar'), GLib.MAXUINT8) - - obj = GIMarshallingTests.PropertiesObject(some_uchar=42) - self.assertEqual(self.get_prop(obj, 'some-uchar'), 42) - - def test_int(self): - self.assertEqual(self.get_prop(self.obj, 'some_int'), 0) - self.set_prop(self.obj, 'some-int', GLib.MAXINT) - self.assertEqual(self.get_prop(self.obj, 'some_int'), GLib.MAXINT) - - obj = GIMarshallingTests.PropertiesObject(some_int=-42) - self.assertEqual(self.get_prop(obj, 'some-int'), -42) - - self.assertRaises(TypeError, self.set_prop, self.obj, 'some-int', 'foo') - self.assertRaises(TypeError, self.set_prop, self.obj, 'some-int', None) - - self.assertEqual(self.get_prop(obj, 'some-int'), -42) - - def test_uint(self): - self.assertEqual(self.get_prop(self.obj, 'some_uint'), 0) - self.set_prop(self.obj, 'some-uint', GLib.MAXUINT) - self.assertEqual(self.get_prop(self.obj, 'some_uint'), GLib.MAXUINT) - - obj = GIMarshallingTests.PropertiesObject(some_uint=42) - self.assertEqual(self.get_prop(obj, 'some-uint'), 42) - - self.assertRaises(TypeError, self.set_prop, self.obj, 'some-uint', 'foo') - self.assertRaises(TypeError, self.set_prop, self.obj, 'some-uint', None) - - self.assertEqual(self.get_prop(obj, 'some-uint'), 42) - - def test_long(self): - self.assertEqual(self.get_prop(self.obj, 'some_long'), 0) - self.set_prop(self.obj, 'some-long', GLib.MAXLONG) - self.assertEqual(self.get_prop(self.obj, 'some_long'), GLib.MAXLONG) - - obj = GIMarshallingTests.PropertiesObject(some_long=-42) - self.assertEqual(self.get_prop(obj, 'some-long'), -42) - - self.assertRaises(TypeError, self.set_prop, self.obj, 'some-long', 'foo') - self.assertRaises(TypeError, self.set_prop, self.obj, 'some-long', None) - - self.assertEqual(self.get_prop(obj, 'some-long'), -42) - - def test_ulong(self): - self.assertEqual(self.get_prop(self.obj, 'some_ulong'), 0) - self.set_prop(self.obj, 'some-ulong', GLib.MAXULONG) - self.assertEqual(self.get_prop(self.obj, 'some_ulong'), GLib.MAXULONG) - - obj = GIMarshallingTests.PropertiesObject(some_ulong=42) - self.assertEqual(self.get_prop(obj, 'some-ulong'), 42) - - self.assertRaises(TypeError, self.set_prop, self.obj, 'some-ulong', 'foo') - self.assertRaises(TypeError, self.set_prop, self.obj, 'some-ulong', None) - - self.assertEqual(self.get_prop(obj, 'some-ulong'), 42) - - def test_int64(self): - self.assertEqual(self.get_prop(self.obj, 'some-int64'), 0) - self.set_prop(self.obj, 'some-int64', GLib.MAXINT64) - self.assertEqual(self.get_prop(self.obj, 'some-int64'), GLib.MAXINT64) - - obj = GIMarshallingTests.PropertiesObject(some_int64=-4200000000000000) - self.assertEqual(self.get_prop(obj, 'some-int64'), -4200000000000000) - - def test_uint64(self): - self.assertEqual(self.get_prop(self.obj, 'some-uint64'), 0) - self.set_prop(self.obj, 'some-uint64', GLib.MAXUINT64) - self.assertEqual(self.get_prop(self.obj, 'some-uint64'), GLib.MAXUINT64) - - obj = GIMarshallingTests.PropertiesObject(some_uint64=4200000000000000) - self.assertEqual(self.get_prop(obj, 'some-uint64'), 4200000000000000) - - def test_float(self): - self.assertEqual(self.get_prop(self.obj, 'some-float'), 0) - self.set_prop(self.obj, 'some-float', GLib.MAXFLOAT) - self.assertEqual(self.get_prop(self.obj, 'some-float'), GLib.MAXFLOAT) - - obj = GIMarshallingTests.PropertiesObject(some_float=42.42) - self.assertAlmostEqual(self.get_prop(obj, 'some-float'), 42.42, places=4) - - obj = GIMarshallingTests.PropertiesObject(some_float=42) - self.assertAlmostEqual(self.get_prop(obj, 'some-float'), 42.0, places=4) - - self.assertRaises(TypeError, self.set_prop, self.obj, 'some-float', 'foo') - self.assertRaises(TypeError, self.set_prop, self.obj, 'some-float', None) - - self.assertAlmostEqual(self.get_prop(obj, 'some-float'), 42.0, places=4) - - def test_double(self): - self.assertEqual(self.get_prop(self.obj, 'some-double'), 0) - self.set_prop(self.obj, 'some-double', GLib.MAXDOUBLE) - self.assertEqual(self.get_prop(self.obj, 'some-double'), GLib.MAXDOUBLE) - - obj = GIMarshallingTests.PropertiesObject(some_double=42.42) - self.assertAlmostEqual(self.get_prop(obj, 'some-double'), 42.42) - - obj = GIMarshallingTests.PropertiesObject(some_double=42) - self.assertAlmostEqual(self.get_prop(obj, 'some-double'), 42.0) - - self.assertRaises(TypeError, self.set_prop, self.obj, 'some-double', 'foo') - self.assertRaises(TypeError, self.set_prop, self.obj, 'some-double', None) - - self.assertAlmostEqual(self.get_prop(obj, 'some-double'), 42.0) - - def test_strv(self): - self.assertEqual(self.get_prop(self.obj, 'some-strv'), []) - self.set_prop(self.obj, 'some-strv', ['hello', 'world']) - self.assertEqual(self.get_prop(self.obj, 'some-strv'), ['hello', 'world']) - - self.assertRaises(TypeError, self.set_prop, self.obj, 'some-strv', 1) - self.assertRaises(TypeError, self.set_prop, self.obj, 'some-strv', 'foo') - self.assertRaises(TypeError, self.set_prop, self.obj, 'some-strv', [1, 2]) - self.assertRaises(TypeError, self.set_prop, self.obj, 'some-strv', ['foo', 1]) - - self.assertEqual(self.get_prop(self.obj, 'some-strv'), ['hello', 'world']) - - obj = GIMarshallingTests.PropertiesObject(some_strv=['hello', 'world']) - self.assertEqual(self.get_prop(obj, 'some-strv'), ['hello', 'world']) - - # unicode on py2 - obj = GIMarshallingTests.PropertiesObject(some_strv=[u'foo']) - self.assertEqual(self.get_prop(obj, 'some-strv'), [u'foo']) - self.assertRaises(TypeError, self.set_prop, self.obj, 'some-strv', - [u'foo', 1]) - - def test_boxed_struct(self): - self.assertEqual(self.get_prop(self.obj, 'some-boxed-struct'), None) - - class GStrv(list): - __gtype__ = GObject.TYPE_STRV - - struct1 = GIMarshallingTests.BoxedStruct() - struct1.long_ = 1 - - self.set_prop(self.obj, 'some-boxed-struct', struct1) - self.assertEqual(self.get_prop(self.obj, 'some-boxed-struct').long_, 1) - self.assertEqual(self.obj.some_boxed_struct.long_, 1) - - self.assertRaises(TypeError, self.set_prop, self.obj, 'some-boxed-struct', 1) - self.assertRaises(TypeError, self.set_prop, self.obj, 'some-boxed-struct', 'foo') - - obj = GIMarshallingTests.PropertiesObject(some_boxed_struct=struct1) - self.assertEqual(self.get_prop(obj, 'some-boxed-struct').long_, 1) - - def test_boxed_glist(self): - self.assertEqual(self.get_prop(self.obj, 'some-boxed-glist'), []) - - list_ = [GLib.MININT, 42, GLib.MAXINT] - self.set_prop(self.obj, 'some-boxed-glist', list_) - self.assertEqual(self.get_prop(self.obj, 'some-boxed-glist'), list_) - self.set_prop(self.obj, 'some-boxed-glist', []) - self.assertEqual(self.get_prop(self.obj, 'some-boxed-glist'), []) - - self.assertRaises(TypeError, self.set_prop, self.obj, 'some-boxed-glist', 1) - self.assertRaises(TypeError, self.set_prop, self.obj, 'some-boxed-glist', 'foo') - self.assertRaises(TypeError, self.set_prop, self.obj, 'some-boxed-glist', ['a']) - - def test_annotated_glist(self): - obj = Regress.TestObj() - self.assertEqual(self.get_prop(obj, 'list'), []) - - self.set_prop(obj, 'list', ['1', '2', '3']) - self.assertTrue(isinstance(self.get_prop(obj, 'list'), list)) - self.assertEqual(self.get_prop(obj, 'list'), ['1', '2', '3']) - - @unittest.expectedFailure - def test_boxed_glist_ctor(self): - list_ = [GLib.MININT, 42, GLib.MAXINT] - obj = GIMarshallingTests.PropertiesObject(some_boxed_glist=list_) - self.assertEqual(self.get_prop(obj, 'some-boxed-glist'), list_) - - def test_variant(self): - self.assertEqual(self.get_prop(self.obj, 'some-variant'), None) - - self.set_prop(self.obj, 'some-variant', GLib.Variant('o', '/myobj')) - self.assertEqual(self.get_prop(self.obj, 'some-variant').get_type_string(), 'o') - self.assertEqual(self.get_prop(self.obj, 'some-variant').print_(False), "'/myobj'") - - self.set_prop(self.obj, 'some-variant', None) - self.assertEqual(self.get_prop(self.obj, 'some-variant'), None) - - obj = GIMarshallingTests.PropertiesObject(some_variant=GLib.Variant('b', True)) - self.assertEqual(self.get_prop(obj, 'some-variant').get_type_string(), 'b') - self.assertEqual(self.get_prop(obj, 'some-variant').get_boolean(), True) - - self.assertRaises(TypeError, self.set_prop, self.obj, 'some-variant', 'foo') - self.assertRaises(TypeError, self.set_prop, self.obj, 'some-variant', 23) - - self.assertEqual(self.get_prop(obj, 'some-variant').get_type_string(), 'b') - self.assertEqual(self.get_prop(obj, 'some-variant').get_boolean(), True) - - def test_setting_several_properties(self): - obj = GIMarshallingTests.PropertiesObject() - obj.set_properties(some_uchar=54, some_int=42) - self.assertEqual(42, self.get_prop(obj, 'some-int')) - self.assertEqual(54, self.get_prop(obj, 'some-uchar')) - - def test_gtype(self): - obj = Regress.TestObj() - self.assertEqual(self.get_prop(obj, 'gtype'), GObject.TYPE_INVALID) - self.set_prop(obj, 'gtype', int) - self.assertEqual(self.get_prop(obj, 'gtype'), GObject.TYPE_INT) - - obj = Regress.TestObj(gtype=int) - self.assertEqual(self.get_prop(obj, 'gtype'), GObject.TYPE_INT) - self.set_prop(obj, 'gtype', str) - self.assertEqual(self.get_prop(obj, 'gtype'), GObject.TYPE_STRING) - - def test_hash_table(self): - obj = Regress.TestObj() - self.assertEqual(self.get_prop(obj, 'hash-table'), None) - - self.set_prop(obj, 'hash-table', {'mec': 56}) - self.assertTrue(isinstance(self.get_prop(obj, 'hash-table'), dict)) - self.assertEqual(list(self.get_prop(obj, 'hash-table').items())[0], - ('mec', 56)) - - def test_parent_class(self): - class A(Regress.TestObj): - prop1 = GObject.Property(type=int) - - a = A() - self.set_prop(a, 'int', 20) - self.assertEqual(self.get_prop(a, 'int'), 20) - - # test parent property which needs introspection - self.set_prop(a, 'list', ("str1", "str2")) - self.assertEqual(self.get_prop(a, 'list'), ["str1", "str2"]) - - def test_held_object_ref_count_getter(self): - holder = GIMarshallingTests.PropertiesObject() - held = GObject.Object() - - self.assertEqual(holder.__grefcount__, 1) - self.assertEqual(held.__grefcount__, 1) - - self.set_prop(holder, 'some-object', held) - self.assertEqual(holder.__grefcount__, 1) - - initial_ref_count = held.__grefcount__ - self.get_prop(holder, 'some-object') - gc.collect() - self.assertEqual(held.__grefcount__, initial_ref_count) - - def test_held_object_ref_count_setter(self): - holder = GIMarshallingTests.PropertiesObject() - held = GObject.Object() - - self.assertEqual(holder.__grefcount__, 1) - self.assertEqual(held.__grefcount__, 1) - - # Setting property should only increase ref count by 1 - self.set_prop(holder, 'some-object', held) - self.assertEqual(holder.__grefcount__, 1) - self.assertEqual(held.__grefcount__, 2) - - # Clearing should pull it back down - self.set_prop(holder, 'some-object', None) - self.assertEqual(held.__grefcount__, 1) - - def test_set_object_property_to_invalid_type(self): - obj = GIMarshallingTests.PropertiesObject() - self.assertRaises(TypeError, self.set_prop, obj, 'some-object', 'not_an_object') - - -class TestCPropsAccessor(CPropertiesTestBase, unittest.TestCase): - # C property tests using the "props" accessor. - def get_prop(self, obj, name): - return getattr(obj.props, name.replace('-', '_')) - - def set_prop(self, obj, name, value): - setattr(obj.props, name.replace('-', '_'), value) - - def test_props_accessor_dir(self): - # Test class - props = dir(GIMarshallingTests.PropertiesObject.props) - self.assertTrue('some_float' in props) - self.assertTrue('some_double' in props) - self.assertTrue('some_variant' in props) - - # Test instance - obj = GIMarshallingTests.PropertiesObject() - props = dir(obj.props) - self.assertTrue('some_float' in props) - self.assertTrue('some_double' in props) - self.assertTrue('some_variant' in props) - - def test_param_spec_dir(self): - attrs = dir(GIMarshallingTests.PropertiesObject.props.some_float) - self.assertTrue('name' in attrs) - self.assertTrue('nick' in attrs) - self.assertTrue('blurb' in attrs) - self.assertTrue('flags' in attrs) - self.assertTrue('default_value' in attrs) - self.assertTrue('minimum' in attrs) - self.assertTrue('maximum' in attrs) - - -class TestCGetPropertyMethod(CPropertiesTestBase, unittest.TestCase): - # C property tests using the "props" accessor. - def get_prop(self, obj, name): - return obj.get_property(name) - - def set_prop(self, obj, name, value): - obj.set_property(name, value) + self.assertEqual(C.blurbed.blurb, 'blurbed doc string') if __name__ == '__main__': diff --git a/tests/test_pygtkcompat.py b/tests/test_pygtkcompat.py new file mode 100644 index 0000000..21ad863 --- /dev/null +++ b/tests/test_pygtkcompat.py @@ -0,0 +1,123 @@ +# -*- Mode: Python; py-indent-offset: 4 -*- +# vim: tabstop=4 shiftwidth=4 expandtab + +import unittest + +import sys +sys.path.insert(0, "../") + +from gi.repository import Gdk +from gi.repository import Gtk + +import gi.pygtkcompat + +gi.pygtkcompat.enable() +gi.pygtkcompat.enable_gtk(version='3.0') + +import atk +import pango +import pangocairo +import gtk +import gtk.gdk + + +class TestATKCompat(unittest.TestCase): + def testObject(self): + self.assertTrue(hasattr(atk, 'Object')) + + +class TestPangoCompat(unittest.TestCase): + def testLayout(self): + self.assertTrue(hasattr(pango, 'Layout')) + + +class TestPangoCairoCompat(unittest.TestCase): + def testErrorUnderlinePath(self): + self.assertTrue(hasattr(pangocairo, 'error_underline_path')) + + +class TestGTKCompat(unittest.TestCase): + def testButtons(self): + self.assertEqual(Gdk._2BUTTON_PRESS, 5) + self.assertEqual(Gdk.BUTTON_PRESS, 4) + + def testEnums(self): + self.assertEqual(gtk.WINDOW_TOPLEVEL, Gtk.WindowType.TOPLEVEL) + self.assertEqual(gtk.PACK_START, Gtk.PackType.START) + + def testFlags(self): + self.assertEqual(gtk.EXPAND, Gtk.AttachOptions.EXPAND) + + def testKeysyms(self): + import gtk.keysyms + self.assertEqual(gtk.keysyms.Escape, Gdk.KEY_Escape) + self.assertTrue(gtk.keysyms._0, Gdk.KEY_0) + + def testStyle(self): + widget = gtk.Button() + self.assertTrue(isinstance(widget.style.base[gtk.STATE_NORMAL], + gtk.gdk.Color)) + + def testAlignment(self): + a = gtk.Alignment() + self.assertEqual(a.props.xalign, 0.0) + self.assertEqual(a.props.yalign, 0.0) + self.assertEqual(a.props.xscale, 0.0) + self.assertEqual(a.props.yscale, 0.0) + + def testBox(self): + box = gtk.Box() + child = gtk.Button() + + box.pack_start(child) + expand, fill, padding, pack_type = box.query_child_packing(child) + self.assertTrue(expand) + self.assertTrue(fill) + self.assertEqual(padding, 0) + self.assertEqual(pack_type, gtk.PACK_START) + + child = gtk.Button() + box.pack_end(child) + expand, fill, padding, pack_type = box.query_child_packing(child) + self.assertTrue(expand) + self.assertTrue(fill) + self.assertEqual(padding, 0) + self.assertEqual(pack_type, gtk.PACK_END) + + def testComboBoxEntry(self): + liststore = gtk.ListStore(int, str) + liststore.append((1, 'One')) + liststore.append((2, 'Two')) + liststore.append((3, 'Three')) + combo = gtk.ComboBoxEntry(model=liststore) + combo.set_text_column(1) + combo.set_active(0) + self.assertEqual(combo.get_text_column(), 1) + self.assertEqual(combo.get_child().get_text(), 'One') + combo = gtk.combo_box_entry_new() + combo.set_model(liststore) + combo.set_text_column(1) + combo.set_active(0) + self.assertEqual(combo.get_text_column(), 1) + self.assertEqual(combo.get_child().get_text(), 'One') + combo = gtk.combo_box_entry_new_with_model(liststore) + combo.set_text_column(1) + combo.set_active(0) + self.assertEqual(combo.get_text_column(), 1) + self.assertEqual(combo.get_child().get_text(), 'One') + + def testSizeRequest(self): + box = gtk.Box() + self.assertEqual(box.size_request(), [0, 0]) + + def testPixbuf(self): + gtk.gdk.Pixbuf() + + def testPixbufLoader(self): + loader = gtk.gdk.PixbufLoader('png') + loader.close() + + def testGdkWindow(self): + w = gtk.Window() + w.realize() + self.assertEqual(w.get_window().get_origin(), (0, 0)) diff --git a/tests/test_repository.py b/tests/test_repository.py deleted file mode 100644 index d7b6d2e..0000000 --- a/tests/test_repository.py +++ /dev/null @@ -1,390 +0,0 @@ -# -*- Mode: Python; py-indent-offset: 4 -*- -# vim: tabstop=4 shiftwidth=4 expandtab -# -# Copyright (C) 2013 Simon Feltman <sfeltman@gnome.org> -# -# test_repository.py: Test for the GIRepository module -# -# This library is free software; you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public -# License as published by the Free Software Foundation; either -# version 2.1 of the License, or (at your option) any later version. -# -# This library is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 -# USA - -import unittest -import collections - -import gi._gi as GIRepository -from gi.module import repository as repo -from gi.repository import GObject -from gi.repository import GIMarshallingTests -from gi.repository import GIRepository as IntrospectedRepository - -from helper import capture_glib_warnings - - -def find_child_info(info, getter_name, name): - getter = getattr(info, getter_name) - for child in getter(): - if child.get_name() == name: - return child - else: - raise ValueError('child info %s not found' % name) - - -class Test(unittest.TestCase): - def setUp(self): - repo.require('GLib') - repo.require('GObject') - repo.require('GIMarshallingTests') - - def test_repo_get_dependencies(self): - self.assertRaises(TypeError, repo.get_dependencies) - self.assertEqual(repo.get_dependencies("GLib"), []) - self.assertEqual(repo.get_dependencies("GObject"), ["GLib-2.0"]) - - def test_repo_is_registered(self): - self.assertRaises(TypeError, repo.is_registered) - self.assertRaises(TypeError, repo.is_registered, None) - self.assertTrue(repo.is_registered("GIRepository")) - self.assertTrue(repo.is_registered("GIRepository", None)) - self.assertTrue(isinstance(repo.is_registered("GIRepository"), bool)) - self.assertTrue(repo.is_registered("GIRepository", "2.0")) - self.assertFalse(repo.is_registered("GIRepository", "")) - self.assertFalse(repo.is_registered("GIRepository", "99.0")) - self.assertFalse(repo.is_registered("GIRepository", "1.0")) - - def test_repo_get_immediate_dependencies(self): - self.assertRaises(TypeError, repo.get_immediate_dependencies) - self.assertEqual(repo.get_immediate_dependencies("GLib"), []) - self.assertEqual( - repo.get_immediate_dependencies("GObject"), ["GLib-2.0"]) - self.assertEqual( - repo.get_immediate_dependencies(namespace="GObject"), ["GLib-2.0"]) - self.assertEqual( - repo.get_immediate_dependencies("GIMarshallingTests"), ["Gio-2.0"]) - - def test_arg_info(self): - func_info = repo.find_by_name('GIMarshallingTests', 'array_fixed_out_struct') - args = func_info.get_arguments() - self.assertTrue(len(args), 1) - - arg = args[0] - self.assertEqual(arg.get_container(), func_info) - self.assertEqual(arg.get_direction(), GIRepository.Direction.OUT) - self.assertEqual(arg.get_name(), 'structs') - self.assertEqual(arg.get_namespace(), 'GIMarshallingTests') - self.assertFalse(arg.is_caller_allocates()) - self.assertFalse(arg.is_optional()) - self.assertFalse(arg.is_return_value()) - self.assertFalse(arg.may_be_null()) - self.assertEqual(arg.get_destroy(), -1) - self.assertEqual(arg.get_ownership_transfer(), GIRepository.Transfer.NOTHING) - self.assertEqual(arg.get_scope(), GIRepository.ScopeType.INVALID) - self.assertEqual(arg.get_type().get_tag(), GIRepository.TypeTag.ARRAY) - - def test_base_info(self): - info = repo.find_by_name('GIMarshallingTests', 'Object') - self.assertEqual(info.__name__, 'Object') - self.assertEqual(info.get_name(), 'Object') - self.assertEqual(info.__module__, 'gi.repository.GIMarshallingTests') - self.assertEqual(info.get_name_unescaped(), 'Object') - self.assertEqual(info.get_namespace(), 'GIMarshallingTests') - self.assertEqual(info.get_container(), None) - info2 = repo.find_by_name('GIMarshallingTests', 'Object') - self.assertFalse(info is info2) - self.assertEqual(info, info2) - self.assertTrue(info.equal(info2)) - - def test_object_info(self): - info = repo.find_by_name('GIMarshallingTests', 'Object') - self.assertEqual(info.get_parent(), repo.find_by_name('GObject', 'Object')) - self.assertTrue(isinstance(info.get_methods(), collections.Iterable)) - self.assertTrue(isinstance(info.get_fields(), collections.Iterable)) - self.assertTrue(isinstance(info.get_interfaces(), collections.Iterable)) - self.assertTrue(isinstance(info.get_constants(), collections.Iterable)) - self.assertTrue(isinstance(info.get_vfuncs(), collections.Iterable)) - self.assertTrue(isinstance(info.get_properties(), collections.Iterable)) - self.assertFalse(info.get_abstract()) - self.assertEqual(info.get_class_struct(), repo.find_by_name('GIMarshallingTests', 'ObjectClass')) - self.assertEqual(info.get_type_name(), 'GIMarshallingTestsObject') - self.assertEqual(info.get_type_init(), 'gi_marshalling_tests_object_get_type') - self.assertFalse(info.get_fundamental()) - self.assertEqual(info.get_parent(), repo.find_by_name('GObject', 'Object')) - - def test_callable_inheritance(self): - self.assertTrue(issubclass(GIRepository.CallableInfo, GIRepository.BaseInfo)) - self.assertTrue(issubclass(GIRepository.CallbackInfo, GIRepository.CallableInfo)) - self.assertTrue(issubclass(GIRepository.FunctionInfo, GIRepository.CallableInfo)) - self.assertTrue(issubclass(GIRepository.VFuncInfo, GIRepository.CallableInfo)) - self.assertTrue(issubclass(GIRepository.SignalInfo, GIRepository.CallableInfo)) - - def test_registered_type_info(self): - info = repo.find_by_name('GIMarshallingTests', 'Object') - # Call these from the class because GIObjectInfo overrides them - self.assertEqual(GIRepository.RegisteredTypeInfo.get_g_type(info), - GObject.type_from_name('GIMarshallingTestsObject')) - self.assertEqual(GIRepository.RegisteredTypeInfo.get_type_name(info), - 'GIMarshallingTestsObject') - self.assertEqual(GIRepository.RegisteredTypeInfo.get_type_init(info), - 'gi_marshalling_tests_object_get_type') - - def test_fundamental_object_info(self): - repo.require('Regress') - info = repo.find_by_name('Regress', 'TestFundamentalObject') - self.assertTrue(info.get_abstract()) - self.assertTrue(info.get_fundamental()) - self.assertEqual(info.get_ref_function(), 'regress_test_fundamental_object_ref') - self.assertEqual(info.get_unref_function(), 'regress_test_fundamental_object_unref') - self.assertEqual(info.get_get_value_function(), 'regress_test_value_get_fundamental_object') - self.assertEqual(info.get_set_value_function(), 'regress_test_value_set_fundamental_object') - - def test_interface_info(self): - info = repo.find_by_name('GIMarshallingTests', 'Interface') - self.assertTrue(isinstance(info.get_methods(), collections.Iterable)) - self.assertTrue(isinstance(info.get_vfuncs(), collections.Iterable)) - self.assertTrue(isinstance(info.get_constants(), collections.Iterable)) - self.assertTrue(isinstance(info.get_prerequisites(), collections.Iterable)) - self.assertTrue(isinstance(info.get_properties(), collections.Iterable)) - self.assertTrue(isinstance(info.get_signals(), collections.Iterable)) - - method = info.find_method('test_int8_in') - vfunc = info.find_vfunc('test_int8_in') - self.assertEqual(method.get_name(), 'test_int8_in') - self.assertEqual(vfunc.get_invoker(), method) - self.assertEqual(method.get_vfunc(), vfunc) - - iface = info.get_iface_struct() - self.assertEqual(iface, repo.find_by_name('GIMarshallingTests', 'InterfaceIface')) - - def test_struct_info(self): - info = repo.find_by_name('GIMarshallingTests', 'InterfaceIface') - self.assertTrue(isinstance(info, GIRepository.StructInfo)) - self.assertTrue(isinstance(info.get_fields(), collections.Iterable)) - self.assertTrue(isinstance(info.get_methods(), collections.Iterable)) - self.assertTrue(isinstance(info.get_size(), int)) - self.assertTrue(isinstance(info.get_alignment(), int)) - self.assertTrue(info.is_gtype_struct()) - self.assertFalse(info.is_foreign()) - - def test_enum_info(self): - info = repo.find_by_name('GIMarshallingTests', 'Enum') - self.assertTrue(isinstance(info, GIRepository.EnumInfo)) - self.assertTrue(isinstance(info.get_values(), collections.Iterable)) - self.assertTrue(isinstance(info.get_methods(), collections.Iterable)) - self.assertFalse(info.is_flags()) - self.assertTrue(info.get_storage_type() > 0) # might be platform dependent - - def test_union_info(self): - info = repo.find_by_name('GIMarshallingTests', 'Union') - self.assertTrue(isinstance(info, GIRepository.UnionInfo)) - self.assertTrue(isinstance(info.get_fields(), collections.Iterable)) - self.assertTrue(isinstance(info.get_methods(), collections.Iterable)) - self.assertTrue(isinstance(info.get_size(), int)) - - def test_type_info(self): - func_info = repo.find_by_name('GIMarshallingTests', 'array_fixed_out_struct') - arg_info, = func_info.get_arguments() - type_info = arg_info.get_type() - - self.assertTrue(type_info.is_pointer()) - self.assertEqual(type_info.get_tag(), GIRepository.TypeTag.ARRAY) - self.assertEqual(type_info.get_tag_as_string(), 'array') - self.assertEqual(type_info.get_param_type(0).get_tag(), - GIRepository.TypeTag.INTERFACE) - self.assertEqual(type_info.get_param_type(0).get_interface(), - repo.find_by_name('GIMarshallingTests', 'SimpleStruct')) - self.assertEqual(type_info.get_interface(), None) - self.assertEqual(type_info.get_array_length(), -1) - self.assertEqual(type_info.get_array_fixed_size(), 2) - self.assertFalse(type_info.is_zero_terminated()) - self.assertEqual(type_info.get_array_type(), GIRepository.ArrayType.C) - - def test_field_info(self): - info = repo.find_by_name('GIMarshallingTests', 'InterfaceIface') - field = find_child_info(info, 'get_fields', 'test_int8_in') - self.assertEqual(field.get_name(), 'test_int8_in') - self.assertTrue(field.get_flags() & GIRepository.FieldInfoFlags.IS_READABLE) - self.assertFalse(field.get_flags() & GIRepository.FieldInfoFlags.IS_WRITABLE) - self.assertEqual(field.get_type().get_tag(), GIRepository.TypeTag.INTERFACE) - - # don't test actual values because that might fail with architecture differences - self.assertTrue(isinstance(field.get_size(), int)) - self.assertTrue(isinstance(field.get_offset(), int)) - - def test_property_info(self): - info = repo.find_by_name('GIMarshallingTests', 'PropertiesObject') - prop = find_child_info(info, 'get_properties', 'some-object') - - flags = GObject.ParamFlags.READABLE | GObject.ParamFlags.WRITABLE | GObject.ParamFlags.CONSTRUCT - self.assertEqual(prop.get_flags(), flags) - self.assertEqual(prop.get_type().get_tag(), GIRepository.TypeTag.INTERFACE) - self.assertEqual(prop.get_type().get_interface(), - repo.find_by_name('GObject', 'Object')) - self.assertEqual(prop.get_ownership_transfer(), GIRepository.Transfer.NOTHING) - - def test_callable_info(self): - func_info = repo.find_by_name('GIMarshallingTests', 'array_fixed_out_struct') - self.assertTrue(hasattr(func_info, 'invoke')) - self.assertTrue(isinstance(func_info.get_arguments(), collections.Iterable)) - self.assertEqual(func_info.get_caller_owns(), GIRepository.Transfer.NOTHING) - self.assertFalse(func_info.may_return_null()) - self.assertEqual(func_info.get_return_type().get_tag(), GIRepository.TypeTag.VOID) - self.assertRaises(AttributeError, func_info.get_return_attribute, '_not_an_attr') - - def test_signal_info(self): - repo.require('Regress') - info = repo.find_by_name('Regress', 'TestObj') - sig_info = find_child_info(info, 'get_signals', 'test') - - sig_flags = GObject.SignalFlags.RUN_LAST | \ - GObject.SignalFlags.NO_RECURSE | GObject.SignalFlags.NO_HOOKS - - self.assertTrue(sig_info is not None) - self.assertTrue(isinstance(sig_info, GIRepository.CallableInfo)) - self.assertTrue(isinstance(sig_info, GIRepository.SignalInfo)) - self.assertEqual(sig_info.get_name(), 'test') - self.assertEqual(sig_info.get_class_closure(), None) - self.assertFalse(sig_info.true_stops_emit()) - self.assertEqual(sig_info.get_flags(), sig_flags) - - def test_notify_signal_info_with_obj(self): - repo.require('Regress') - info = repo.find_by_name('Regress', 'TestObj') - sig_info = find_child_info(info, 'get_signals', 'sig-with-array-prop') - - sig_flags = GObject.SignalFlags.RUN_LAST - - self.assertTrue(sig_info is not None) - self.assertTrue(isinstance(sig_info, GIRepository.CallableInfo)) - self.assertTrue(isinstance(sig_info, GIRepository.SignalInfo)) - self.assertEqual(sig_info.get_name(), 'sig-with-array-prop') - self.assertEqual(sig_info.get_class_closure(), None) - self.assertFalse(sig_info.true_stops_emit()) - self.assertEqual(sig_info.get_flags(), sig_flags) - - def test_object_constructor(self): - info = repo.find_by_name('GIMarshallingTests', 'Object') - method = find_child_info(info, 'get_methods', 'new') - - self.assertTrue(isinstance(method, GIRepository.CallableInfo)) - self.assertTrue(isinstance(method, GIRepository.FunctionInfo)) - self.assertTrue(method in info.get_methods()) - self.assertEqual(method.get_name(), 'new') - self.assertFalse(method.is_method()) - self.assertTrue(method.is_constructor()) - self.assertEqual(method.get_symbol(), 'gi_marshalling_tests_object_new') - - flags = method.get_flags() - self.assertFalse(flags & GIRepository.FunctionInfoFlags.IS_METHOD) - self.assertTrue(flags & GIRepository.FunctionInfoFlags.IS_CONSTRUCTOR) - self.assertFalse(flags & GIRepository.FunctionInfoFlags.IS_GETTER) - self.assertFalse(flags & GIRepository.FunctionInfoFlags.IS_SETTER) - self.assertFalse(flags & GIRepository.FunctionInfoFlags.WRAPS_VFUNC) - self.assertFalse(flags & GIRepository.FunctionInfoFlags.THROWS) - - def test_method_info(self): - info = repo.find_by_name('GIMarshallingTests', 'Object') - method = find_child_info(info, 'get_methods', 'vfunc_return_value_only') - - self.assertTrue(isinstance(method, GIRepository.CallableInfo)) - self.assertTrue(isinstance(method, GIRepository.FunctionInfo)) - self.assertTrue(method in info.get_methods()) - self.assertEqual(method.get_name(), 'vfunc_return_value_only') - self.assertFalse(method.is_constructor()) - self.assertEqual(method.get_symbol(), 'gi_marshalling_tests_object_vfunc_return_value_only') - self.assertTrue(method.is_method()) - - flags = method.get_flags() - self.assertTrue(flags & GIRepository.FunctionInfoFlags.IS_METHOD) - self.assertFalse(flags & GIRepository.FunctionInfoFlags.IS_CONSTRUCTOR) - self.assertFalse(flags & GIRepository.FunctionInfoFlags.IS_GETTER) - self.assertFalse(flags & GIRepository.FunctionInfoFlags.IS_SETTER) - self.assertFalse(flags & GIRepository.FunctionInfoFlags.WRAPS_VFUNC) - self.assertFalse(flags & GIRepository.FunctionInfoFlags.THROWS) - - def test_vfunc_info(self): - info = repo.find_by_name('GIMarshallingTests', 'Object') - invoker = find_child_info(info, 'get_methods', 'vfunc_return_value_only') - vfunc = find_child_info(info, 'get_vfuncs', 'vfunc_return_value_only') - - self.assertTrue(isinstance(vfunc, GIRepository.CallableInfo)) - self.assertTrue(isinstance(vfunc, GIRepository.VFuncInfo)) - self.assertEqual(vfunc.get_name(), 'vfunc_return_value_only') - self.assertEqual(vfunc.get_invoker(), invoker) - self.assertEqual(invoker, info.find_method('vfunc_return_value_only')) - self.assertEqual(vfunc.get_flags(), 0) - self.assertEqual(vfunc.get_offset(), 0xFFFF) # unknown offset - self.assertEqual(vfunc.get_signal(), None) - - def test_callable_can_throw_gerror(self): - info = repo.find_by_name('GIMarshallingTests', 'Object') - invoker = find_child_info(info, 'get_methods', 'vfunc_meth_with_error') - vfunc = find_child_info(info, 'get_vfuncs', 'vfunc_meth_with_err') - - self.assertTrue(invoker.can_throw_gerror()) - self.assertTrue(vfunc.can_throw_gerror()) - - # Test that args do not include the GError** - self.assertEqual(len(invoker.get_arguments()), 1) - self.assertEqual(len(vfunc.get_arguments()), 1) - - # Sanity check method that does not throw. - invoker_no_throws = find_child_info(info, 'get_methods', 'method_int8_in') - self.assertFalse(invoker_no_throws.can_throw_gerror()) - - def test_flags_double_registration_error(self): - # a warning is printed for double registration and pygobject will - # also raise a RuntimeError. - GIMarshallingTests.NoTypeFlags # cause flags registration - info = repo.find_by_name('GIMarshallingTests', 'NoTypeFlags') - with capture_glib_warnings(allow_warnings=True): - self.assertRaises(RuntimeError, - GIRepository.flags_register_new_gtype_and_add, - info) - - def test_enum_double_registration_error(self): - # a warning is printed for double registration and pygobject will - # also raise a RuntimeError. - GIMarshallingTests.Enum # cause enum registration - info = repo.find_by_name('GIMarshallingTests', 'Enum') - with capture_glib_warnings(allow_warnings=True): - self.assertRaises(RuntimeError, - GIRepository.enum_register_new_gtype_and_add, - info) - - def test_enums(self): - self.assertTrue(hasattr(GIRepository, 'Direction')) - self.assertTrue(hasattr(GIRepository, 'Transfer')) - self.assertTrue(hasattr(GIRepository, 'ArrayType')) - self.assertTrue(hasattr(GIRepository, 'ScopeType')) - self.assertTrue(hasattr(GIRepository, 'VFuncInfoFlags')) - self.assertTrue(hasattr(GIRepository, 'FieldInfoFlags')) - self.assertTrue(hasattr(GIRepository, 'FunctionInfoFlags')) - self.assertTrue(hasattr(GIRepository, 'TypeTag')) - self.assertTrue(hasattr(GIRepository, 'InfoType')) - - def test_introspected_argument_info(self): - self.assertTrue(isinstance(IntrospectedRepository.Argument.__info__, - GIRepository.UnionInfo)) - - arg = IntrospectedRepository.Argument() - self.assertTrue(isinstance(arg.__info__, GIRepository.UnionInfo)) - - old_info = IntrospectedRepository.Argument.__info__ - IntrospectedRepository.Argument.__info__ = 'not an info' - self.assertRaises(TypeError, IntrospectedRepository.Argument) - IntrospectedRepository.Argument.__info__ = old_info - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/test_resulttuple.py b/tests/test_resulttuple.py deleted file mode 100644 index 20f80f3..0000000 --- a/tests/test_resulttuple.py +++ /dev/null @@ -1,87 +0,0 @@ -# -*- Mode: Python; py-indent-offset: 4 -*- -# vim: tabstop=4 shiftwidth=4 expandtab -# -# Copyright (C) 2015 Christoph Reiter <reiter.christoph@gmail.com> -# -# This library is free software; you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public -# License as published by the Free Software Foundation; either -# version 2.1 of the License, or (at your option) any later version. -# -# This library is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 -# USA - -import unittest -import pickle - -import gi -from gi.repository import GIMarshallingTests -from gi.repository import Regress - - -ResultTuple = gi._gi.ResultTuple - - -class TestResultTuple(unittest.TestCase): - - def test_base(self): - self.assertTrue(issubclass(ResultTuple, tuple)) - - def test_create(self): - new = ResultTuple._new_type([None, "foo", None, "bar"]) - self.assertTrue(issubclass(new, ResultTuple)) - - def test_repr_dir(self): - new = ResultTuple._new_type([None, "foo", None, "bar"]) - inst = new([1, 2, 3, "a"]) - - self.assertEqual(repr(inst), "(1, foo=2, 3, bar='a')") - self.assertTrue("foo" in dir(inst)) - - def test_repr_dir_empty(self): - new = ResultTuple._new_type([]) - inst = new() - self.assertEqual(repr(inst), "()") - dir(inst) - - def test_getatttr(self): - new = ResultTuple._new_type([None, "foo", None, "bar"]) - inst = new([1, 2, 3, "a"]) - - self.assertTrue(hasattr(inst, "foo")) - self.assertEqual(inst.foo, inst[1]) - self.assertRaises(AttributeError, getattr, inst, "nope") - - def test_pickle(self): - new = ResultTuple._new_type([None, "foo", None, "bar"]) - inst = new([1, 2, 3, "a"]) - - inst2 = pickle.loads(pickle.dumps(inst)) - self.assertEqual(inst2, inst) - self.assertTrue(isinstance(inst2, tuple)) - self.assertFalse(isinstance(inst2, new)) - - def test_gi(self): - res = GIMarshallingTests.init_function([]) - self.assertEqual(repr(res), "(True, argv=[])") - - res = GIMarshallingTests.array_return_etc(5, 9) - self.assertEqual(repr(res), "([5, 0, 1, 9], sum=14)") - - res = GIMarshallingTests.array_out_etc(-5, 9) - self.assertEqual(repr(res), "(ints=[-5, 0, 1, 9], sum=4)") - - cb = lambda: (1, 2) - res = GIMarshallingTests.callback_multiple_out_parameters(cb) - self.assertEqual(repr(res), "(a=1.0, b=2.0)") - - def test_regress(self): - res = Regress.TestObj().skip_return_val(50, 42.0, 60, 2, 3) - self.assertEqual(repr(res), "(out_b=51, inout_d=61, out_sum=32)") diff --git a/tests/test_signal.py b/tests/test_signal.py index 4e81c1e..918dad4 100644 --- a/tests/test_signal.py +++ b/tests/test_signal.py @@ -3,13 +3,10 @@ import gc import unittest import sys -import weakref -from gi.repository import GObject, GLib, Regress -from gi import _signalhelper as signalhelper +from gi.repository import GObject import testhelper from compathelper import _long -from helper import capture_glib_warnings, capture_gi_deprecation_warnings class C(GObject.GObject): @@ -51,11 +48,11 @@ class TestChaining(unittest.TestCase): assert args[2:] == (1, 2, 3) - def test_chaining(self): + def testChaining(self): self.inst.emit("my_signal", 42) assert self.inst.arg == 42 - def test_chaining2(self): + def testChaining2(self): inst2 = D() inst2.emit("my_signal", 44) assert inst2.arg == 44 @@ -65,32 +62,30 @@ class TestChaining(unittest.TestCase): class TestGSignalsError(unittest.TestCase): - def test_invalid_type(self, *args): + def testInvalidType(self, *args): def foo(): class Foo(GObject.GObject): __gsignals__ = None self.assertRaises(TypeError, foo) gc.collect() - def test_invalid_name(self, *args): + def testInvalidName(self, *args): def foo(): class Foo(GObject.GObject): __gsignals__ = {'not-exists': 'override'} - - with capture_glib_warnings(allow_warnings=True): - self.assertRaises(TypeError, foo) + self.assertRaises(TypeError, foo) gc.collect() class TestGPropertyError(unittest.TestCase): - def test_invalid_type(self, *args): + def testInvalidType(self, *args): def foo(): class Foo(GObject.GObject): __gproperties__ = None self.assertRaises(TypeError, foo) gc.collect() - def test_invalid_name(self, *args): + def testInvalidName(self, *args): def foo(): class Foo(GObject.GObject): __gproperties__ = {None: None} @@ -100,7 +95,7 @@ class TestGPropertyError(unittest.TestCase): class TestList(unittest.TestCase): - def test_list_names(self): + def testListObject(self): self.assertEqual(GObject.signal_list_names(C), ('my-signal',)) @@ -114,54 +109,38 @@ def my_accumulator(ihint, return_accu, handler_return, user_data): class Foo(GObject.GObject): - my_acc_signal = GObject.Signal(return_type=GObject.TYPE_INT, - flags=GObject.SignalFlags.RUN_LAST, - accumulator=my_accumulator, - accu_data="accum data") - - my_other_acc_signal = GObject.Signal(return_type=GObject.TYPE_BOOLEAN, - flags=GObject.SignalFlags.RUN_LAST, - accumulator=GObject.signal_accumulator_true_handled) - - my_acc_first_wins = GObject.Signal(return_type=GObject.TYPE_BOOLEAN, - flags=GObject.SignalFlags.RUN_LAST, - accumulator=GObject.signal_accumulator_first_wins) + __gsignals__ = { + 'my-acc-signal': (GObject.SignalFlags.RUN_LAST, GObject.TYPE_INT, + (), my_accumulator, "accum data"), + 'my-other-acc-signal': (GObject.SignalFlags.RUN_LAST, GObject.TYPE_BOOLEAN, + (), GObject.signal_accumulator_true_handled) + } class TestAccumulator(unittest.TestCase): - def test_accumulator(self): + def testAccumulator(self): inst = Foo() - inst.my_acc_signal.connect(lambda obj: 1) - inst.my_acc_signal.connect(lambda obj: 2) - # the value returned in the following handler will not be - # considered, because at this point the accumulator already - # reached its limit. - inst.my_acc_signal.connect(lambda obj: 3) - retval = inst.my_acc_signal.emit() + inst.connect("my-acc-signal", lambda obj: 1) + inst.connect("my-acc-signal", lambda obj: 2) + ## the value returned in the following handler will not be + ## considered, because at this point the accumulator already + ## reached its limit. + inst.connect("my-acc-signal", lambda obj: 3) + retval = inst.emit("my-acc-signal") self.assertEqual(retval, 3) - def test_accumulator_true_handled(self): + def testAccumulatorTrueHandled(self): inst = Foo() - inst.my_other_acc_signal.connect(self._true_handler1) - inst.my_other_acc_signal.connect(self._true_handler2) - # the following handler will not be called because handler2 - # returns True, so it should stop the emission. - inst.my_other_acc_signal.connect(self._true_handler3) + inst.connect("my-other-acc-signal", self._true_handler1) + inst.connect("my-other-acc-signal", self._true_handler2) + ## the following handler will not be called because handler2 + ## returns True, so it should stop the emission. + inst.connect("my-other-acc-signal", self._true_handler3) self.__true_val = None - inst.my_other_acc_signal.emit() + inst.emit("my-other-acc-signal") self.assertEqual(self.__true_val, 2) - def test_accumulator_first_wins(self): - # First signal hit will always win - inst = Foo() - inst.my_acc_first_wins.connect(self._true_handler3) - inst.my_acc_first_wins.connect(self._true_handler1) - inst.my_acc_first_wins.connect(self._true_handler2) - self.__true_val = None - inst.my_acc_first_wins.emit() - self.assertEqual(self.__true_val, 3) - def _true_handler1(self, obj): self.__true_val = 1 return False @@ -179,9 +158,6 @@ class E(GObject.GObject): __gsignals__ = {'signal': (GObject.SignalFlags.RUN_FIRST, None, ())} - # Property used to test detailed signal - prop = GObject.Property(type=int, default=0) - def __init__(self): GObject.GObject.__init__(self) self.status = 0 @@ -204,7 +180,7 @@ class F(GObject.GObject): class TestEmissionHook(unittest.TestCase): - def test_add(self): + def testAdd(self): self.hook = True e = E() e.connect('signal', self._callback) @@ -212,7 +188,7 @@ class TestEmissionHook(unittest.TestCase): e.emit('signal') self.assertEqual(e.status, 3) - def test_remove(self): + def testRemove(self): self.hook = False e = E() e.connect('signal', self._callback) @@ -232,7 +208,7 @@ class TestEmissionHook(unittest.TestCase): self.assertEqual(e.status, 1) e.status = 3 - def test_callback_return_false(self): + def testCallbackReturnFalse(self): self.hook = False obj = F() @@ -244,7 +220,7 @@ class TestEmissionHook(unittest.TestCase): obj.emit('signal') self.assertEqual(obj.status, 3) - def test_callback_return_true(self): + def testCallbackReturnTrue(self): self.hook = False obj = F() @@ -257,7 +233,7 @@ class TestEmissionHook(unittest.TestCase): GObject.remove_emission_hook(obj, "signal", hook_id) self.assertEqual(obj.status, 4) - def test_callback_return_true_but_remove(self): + def testCallbackReturnTrueButRemove(self): self.hook = False obj = F() @@ -271,155 +247,36 @@ class TestEmissionHook(unittest.TestCase): self.assertEqual(obj.status, 3) -class TestMatching(unittest.TestCase): - class Object(GObject.Object): - status = 0 - prop = GObject.Property(type=int, default=0) - - @GObject.Signal() - def my_signal(self): - pass - - @unittest.expectedFailure # https://bugzilla.gnome.org/show_bug.cgi?id=692918 - def test_signal_handler_block_matching(self): - def dummy(*args): - "Hack to work around: " - - def foo(obj): - obj.status += 1 - - obj = self.Object() - handler_id = GObject.signal_connect_closure(obj, 'my-signal', foo, after=False) - handler_id - - self.assertEqual(obj.status, 0) - obj.emit('my-signal') - self.assertEqual(obj.status, 1) - - # Blocking by match criteria disables the foo callback - signal_id, detail = GObject.signal_parse_name('my-signal', obj, True) - count = GObject.signal_handlers_block_matched(obj, - GObject.SignalMatchType.ID | GObject.SignalMatchType.CLOSURE, - signal_id=signal_id, detail=detail, - closure=foo, func=dummy, data=dummy) - self.assertEqual(count, 1) - obj.emit('my-signal') - self.assertEqual(obj.status, 1) - - # Unblocking by the same match criteria allows callback to work again - count = GObject.signal_handlers_unblock_matched(obj, - GObject.SignalMatchType.ID | GObject.SignalMatchType.CLOSURE, - signal_id=signal_id, detail=detail, - closure=foo, func=dummy, data=dummy) - self.assertEqual(count, 1) - obj.emit('my-signal') - self.assertEqual(obj.status, 2) - - # Disconnecting by match criteria completely removes the handler - count = GObject.signal_handlers_disconnect_matched(obj, - GObject.SignalMatchType.ID | GObject.SignalMatchType.CLOSURE, - signal_id=signal_id, detail=detail, - closure=foo, func=dummy, data=dummy) - self.assertEqual(count, 1) - obj.emit('my-signal') - self.assertEqual(obj.status, 2) - - def test_signal_handler_find(self): - def foo(obj): - obj.status += 1 - - obj = self.Object() - handler_id = GObject.signal_connect_closure(obj, 'my-signal', foo, after=False) - - signal_id, detail = GObject.signal_parse_name('my-signal', obj, True) - found_id = GObject.signal_handler_find(obj, - GObject.SignalMatchType.ID, - signal_id=signal_id, detail=detail, - closure=None, func=0, data=0) - self.assertEqual(handler_id, found_id) - - class TestClosures(unittest.TestCase): def setUp(self): self.count = 0 - self.emission_stopped = False - self.emission_error = False - self.handler_pending = False - - def _callback_handler_pending(self, e): - signal_id, detail = GObject.signal_parse_name('signal', e, True) - self.handler_pending = GObject.signal_has_handler_pending(e, signal_id, detail, - may_be_blocked=False) def _callback(self, e): self.count += 1 - def _callback_stop_emission(self, obj, prop, stop_it): - if stop_it: - obj.stop_emission_by_name('notify::prop') - self.emission_stopped = True - else: - self.count += 1 - - def _callback_invalid_stop_emission_name(self, obj, prop): - with capture_glib_warnings(allow_warnings=True) as warn: - obj.stop_emission_by_name('notasignal::baddetail') - self.emission_error = True - self.assertTrue(warn) - - def test_disconnect_by_func(self): + def testDisconnect(self): e = E() e.connect('signal', self._callback) e.disconnect_by_func(self._callback) e.emit('signal') self.assertEqual(self.count, 0) - def test_disconnect(self): - e = E() - handler_id = e.connect('signal', self._callback) - self.assertTrue(e.handler_is_connected(handler_id)) - e.disconnect(handler_id) - e.emit('signal') - self.assertEqual(self.count, 0) - self.assertFalse(e.handler_is_connected(handler_id)) - - def test_stop_emission_by_name(self): - e = E() - - # Sandwich a callback that stops emission in between a callback that increments - e.connect('notify::prop', self._callback_stop_emission, False) - e.connect('notify::prop', self._callback_stop_emission, True) - e.connect('notify::prop', self._callback_stop_emission, False) - - e.set_property('prop', 1234) - self.assertEqual(e.get_property('prop'), 1234) - self.assertEqual(self.count, 1) - self.assertTrue(self.emission_stopped) - - def test_stop_emission_by_name_error(self): - e = E() - - e.connect('notify::prop', self._callback_invalid_stop_emission_name) - with capture_glib_warnings(): - e.set_property('prop', 1234) - self.assertTrue(self.emission_error) - - def test_handler_block(self): + def testHandlerBlock(self): e = E() e.connect('signal', self._callback) e.handler_block_by_func(self._callback) e.emit('signal') self.assertEqual(self.count, 0) - def test_handler_unblock(self): + def testHandlerUnBlock(self): e = E() - handler_id = e.connect('signal', self._callback) - e.handler_block(handler_id) + signal_id = e.connect('signal', self._callback) + e.handler_block(signal_id) e.handler_unblock_by_func(self._callback) e.emit('signal') self.assertEqual(self.count, 1) - def test_handler_block_method(self): + def testHandlerBlockMethod(self): # Filed as #375589 class A: def __init__(self): @@ -436,7 +293,7 @@ class TestClosures(unittest.TestCase): self.assertEqual(inst.a, 1) gc.collect() - def test_gstring(self): + def testGString(self): class C(GObject.GObject): __gsignals__ = {'my_signal': (GObject.SignalFlags.RUN_LAST, GObject.TYPE_GSTRING, (GObject.TYPE_GSTRING,))} @@ -453,40 +310,13 @@ class TestClosures(unittest.TestCase): data = c.emit("my_signal", "\01\00\02") self.assertEqual(data, "\02\00\01") - def test_handler_pending(self): - obj = F() - obj.connect('signal', self._callback_handler_pending) - obj.connect('signal', self._callback) - - self.assertEqual(self.count, 0) - self.assertEqual(self.handler_pending, False) - - obj.emit('signal') - self.assertEqual(self.count, 1) - self.assertEqual(self.handler_pending, True) - - def test_signal_handlers_destroy(self): - obj = F() - obj.connect('signal', self._callback) - obj.connect('signal', self._callback) - obj.connect('signal', self._callback) - - obj.emit('signal') - self.assertEqual(self.count, 3) - - # count should remain at 3 after all handlers are destroyed - GObject.signal_handlers_destroy(obj) - obj.emit('signal') - self.assertEqual(self.count, 3) - class SigPropClass(GObject.GObject): __gsignals__ = {'my_signal': (GObject.SignalFlags.RUN_FIRST, None, (GObject.TYPE_INT,))} __gproperties__ = { - 'foo': (str, None, None, '', - GObject.ParamFlags.WRITABLE | GObject.ParamFlags.CONSTRUCT), + 'foo': (str, None, None, '', GObject.PARAM_WRITABLE | GObject.PARAM_CONSTRUCT), } signal_emission_failed = False @@ -506,152 +336,65 @@ class SigPropClass(GObject.GObject): class TestSigProp(unittest.TestCase): - def test_emit_in_property_setter(self): + def testEmitInPropertySetter(self): obj = SigPropClass() self.assertFalse(obj.signal_emission_failed) +f = GObject.SignalFlags.RUN_FIRST +l = GObject.SignalFlags.RUN_LAST +float = GObject.TYPE_FLOAT +double = GObject.TYPE_DOUBLE +uint = GObject.TYPE_UINT +ulong = GObject.TYPE_ULONG + class CM(GObject.GObject): __gsignals__ = dict( - test1=(GObject.SignalFlags.RUN_FIRST, None, ()), - test2=(GObject.SignalFlags.RUN_LAST, None, (str,)), - test3=(GObject.SignalFlags.RUN_LAST, int, (GObject.TYPE_DOUBLE,)), - test4=(GObject.SignalFlags.RUN_FIRST, None, - (bool, _long, GObject.TYPE_FLOAT, GObject.TYPE_DOUBLE, int, - GObject.TYPE_UINT, GObject.TYPE_ULONG)), - test_float=(GObject.SignalFlags.RUN_LAST, GObject.TYPE_FLOAT, (GObject.TYPE_FLOAT,)), - test_double=(GObject.SignalFlags.RUN_LAST, GObject.TYPE_DOUBLE, (GObject.TYPE_DOUBLE,)), - test_int64=(GObject.SignalFlags.RUN_LAST, GObject.TYPE_INT64, (GObject.TYPE_INT64,)), - test_string=(GObject.SignalFlags.RUN_LAST, str, (str,)), - test_object=(GObject.SignalFlags.RUN_LAST, object, (object,)), - test_paramspec=(GObject.SignalFlags.RUN_LAST, GObject.ParamSpec, ()), - test_paramspec_in=(GObject.SignalFlags.RUN_LAST, GObject.ParamSpec, (GObject.ParamSpec, )), - test_gvalue=(GObject.SignalFlags.RUN_LAST, GObject.Value, (GObject.Value,)), - test_gvalue_ret=(GObject.SignalFlags.RUN_LAST, GObject.Value, (GObject.TYPE_GTYPE,)), + test1=(f, None, ()), + test2=(l, None, (str,)), + test3=(l, int, (double,)), + test4=(f, None, (bool, _long, float, double, int, uint, ulong)), + test_float=(l, float, (float,)), + test_double=(l, double, (double, )), + test_string=(l, str, (str, )), + test_object=(l, object, (object, )), ) - testprop = GObject.Property(type=int) - class _TestCMarshaller: def setUp(self): self.obj = CM() testhelper.connectcallbacks(self.obj) - def test_test1(self): + def testTest1(self): self.obj.emit("test1") - def test_test2(self): + def testTest2(self): self.obj.emit("test2", "string") - def test_test3(self): + def testTest3(self): rv = self.obj.emit("test3", 42.0) self.assertEqual(rv, 20) - def test_test4(self): + def testTest4(self): self.obj.emit("test4", True, _long(10), 3.14, 1.78, 20, _long(30), _long(31)) - def test_float(self): + def testTestReturnFloat(self): rv = self.obj.emit("test-float", 1.234) self.assertTrue(rv >= 1.233999 and rv <= 1.2400001, rv) - def test_double(self): + def testTestReturnDouble(self): rv = self.obj.emit("test-double", 1.234) self.assertEqual(rv, 1.234) - def test_int64(self): - rv = self.obj.emit("test-int64", 102030405) - self.assertEqual(rv, 102030405) - - rv = self.obj.emit("test-int64", GLib.MAXINT64) - self.assertEqual(rv, GLib.MAXINT64 - 1) - - rv = self.obj.emit("test-int64", GLib.MININT64) - self.assertEqual(rv, GLib.MININT64) - - def test_string(self): + def testTestReturnString(self): rv = self.obj.emit("test-string", "str") self.assertEqual(rv, "str") - def test_object(self): + def testTestReturnObject(self): rv = self.obj.emit("test-object", self) self.assertEqual(rv, self) - def test_paramspec(self): - rv = self.obj.emit("test-paramspec") - self.assertEqual(rv.name, "test-param") - self.assertEqual(rv.nick, "test") - - @unittest.skipUnless(hasattr(GObject, 'param_spec_boolean'), - 'too old gobject-introspection') - def test_paramspec_in(self): - rv = GObject.param_spec_boolean('mybool', 'test-bool', 'do something', - True, GObject.ParamFlags.READABLE) - - rv2 = self.obj.emit("test-paramspec-in", rv) - self.assertEqual(type(rv), type(rv2)) - self.assertEqual(rv2.name, "mybool") - self.assertEqual(rv2.nick, "test-bool") - - def test_C_paramspec(self): - self.notify_called = False - - def cb_notify(obj, prop): - self.notify_called = True - self.assertEqual(obj, self.obj) - self.assertEqual(prop.name, "testprop") - - self.obj.connect("notify", cb_notify) - self.obj.set_property("testprop", 42) - self.assertTrue(self.notify_called) - - def test_gvalue(self): - # implicit int - rv = self.obj.emit("test-gvalue", 42) - self.assertEqual(rv, 42) - - # explicit float - v = GObject.Value(GObject.TYPE_FLOAT, 1.234) - rv = self.obj.emit("test-gvalue", v) - self.assertAlmostEqual(rv, 1.234, places=4) - - # implicit float - rv = self.obj.emit("test-gvalue", 1.234) - self.assertAlmostEqual(rv, 1.234, places=4) - - # explicit int64 - v = GObject.Value(GObject.TYPE_INT64, GLib.MAXINT64) - rv = self.obj.emit("test-gvalue", v) - self.assertEqual(rv, GLib.MAXINT64) - - # explicit uint64 - v = GObject.Value(GObject.TYPE_UINT64, GLib.MAXUINT64) - rv = self.obj.emit("test-gvalue", v) - self.assertEqual(rv, GLib.MAXUINT64) - - @unittest.expectedFailure # https://bugzilla.gnome.org/show_bug.cgi?id=705291 - def test_gvalue_implicit_int64(self): - # implicit int64 - rv = self.obj.emit("test-gvalue", GLib.MAXINT64) - self.assertEqual(rv, GLib.MAXINT64) - - # implicit uint64 - rv = self.obj.emit("test-gvalue", GLib.MAXUINT64) - self.assertEqual(rv, GLib.MAXUINT64) - - def test_gvalue_ret(self): - self.assertEqual(self.obj.emit("test-gvalue-ret", GObject.TYPE_INT), - GLib.MAXINT) - self.assertEqual(self.obj.emit("test-gvalue-ret", GObject.TYPE_UINT), - GLib.MAXUINT) - self.assertEqual(self.obj.emit("test-gvalue-ret", GObject.TYPE_INT64), - GLib.MAXINT64) - self.assertEqual(self.obj.emit("test-gvalue-ret", GObject.TYPE_UINT64), - GLib.MAXUINT64) - self.assertEqual(self.obj.emit("test-gvalue-ret", GObject.TYPE_STRING), - "hello") - - if 'generic-c-marshaller' in GObject.features: class TestCMarshaller(_TestCMarshaller, unittest.TestCase): pass @@ -664,11 +407,11 @@ else: class TestPyGValue(unittest.TestCase): - def test_none_null_boxed_conversion(self): + def testNoneNULLBoxedConversion(self): class C(GObject.GObject): __gsignals__ = dict(my_boxed_signal=( GObject.SignalFlags.RUN_LAST, - GObject.TYPE_STRV, ())) + GObject.type_from_name('GStrv'), ())) obj = C() obj.connect('my-boxed-signal', lambda obj: None) @@ -676,795 +419,5 @@ class TestPyGValue(unittest.TestCase): obj.emit('my-boxed-signal') assert not sys.last_type - -class TestSignalDecorator(unittest.TestCase): - class Decorated(GObject.GObject): - value = 0 - - @GObject.Signal - def pushed(self): - """this will push""" - self.value += 1 - - @GObject.Signal(flags=GObject.SignalFlags.RUN_LAST) - def pulled(self): - self.value -= 1 - - stomped = GObject.Signal('stomped', arg_types=(int,), doc='this will stomp') - unnamed = GObject.Signal() - - class DecoratedOverride(GObject.GObject): - overridden_closure_called = False - notify_called = False - value = GObject.Property(type=int, default=0) - - @GObject.SignalOverride - def notify(self, *args, **kargs): - self.overridden_closure_called = True - - def on_notify(self, obj, prop): - self.notify_called = True - - def setUp(self): - self.unnamedCalled = False - - def onUnnamed(self, obj): - self.unnamedCalled = True - - def test_get_signal_args(self): - self.assertEqual(self.Decorated.pushed.get_signal_args(), - (GObject.SignalFlags.RUN_FIRST, None, tuple(), None, None)) - self.assertEqual(self.Decorated.pulled.get_signal_args(), - (GObject.SignalFlags.RUN_LAST, None, tuple(), None, None)) - self.assertEqual(self.Decorated.stomped.get_signal_args(), - (GObject.SignalFlags.RUN_FIRST, None, (int,), None, None)) - - def test_closures_called(self): - decorated = self.Decorated() - self.assertEqual(decorated.value, 0) - decorated.pushed.emit() - self.assertEqual(decorated.value, 1) - decorated.pulled.emit() - self.assertEqual(decorated.value, 0) - - def test_signal_copy(self): - blah = self.Decorated.stomped.copy('blah') - self.assertEqual(str(blah), blah) - self.assertEqual(blah.func, self.Decorated.stomped.func) - self.assertEqual(blah.flags, self.Decorated.stomped.flags) - self.assertEqual(blah.return_type, self.Decorated.stomped.return_type) - self.assertEqual(blah.arg_types, self.Decorated.stomped.arg_types) - self.assertEqual(blah.__doc__, self.Decorated.stomped.__doc__) - - def test_doc_string(self): - # Test the two techniques for setting doc strings on the signals - # class variables, through the "doc" keyword or as the getter doc string. - self.assertEqual(self.Decorated.stomped.__doc__, 'this will stomp') - self.assertEqual(self.Decorated.pushed.__doc__, 'this will push') - - def test_unnamed_signal_gets_named(self): - self.assertEqual(str(self.Decorated.unnamed), 'unnamed') - - def test_unnamed_signal_gets_called(self): - obj = self.Decorated() - obj.connect('unnamed', self.onUnnamed) - self.assertEqual(self.unnamedCalled, False) - obj.emit('unnamed') - self.assertEqual(self.unnamedCalled, True) - - def test_overridden_signal(self): - # Test that the pushed signal is called in with super and the override - # which should both increment the "value" to 3 - obj = self.DecoratedOverride() - obj.connect("notify", obj.on_notify) - self.assertEqual(obj.value, 0) - obj.value = 1 - self.assertEqual(obj.value, 1) - self.assertTrue(obj.overridden_closure_called) - self.assertTrue(obj.notify_called) - - -class TestSignalConnectors(unittest.TestCase): - class CustomButton(GObject.GObject): - on_notify_called = False - value = GObject.Property(type=int) - - @GObject.Signal(arg_types=(int,)) - def clicked(self, value): - self.value = value - - def setUp(self): - self.obj = None - self.value = None - - def on_clicked(self, obj, value): - self.obj = obj - self.value = value - - def test_signal_notify(self): - def on_notify(obj, param): - obj.on_notify_called = True - - obj = self.CustomButton() - obj.connect('notify', on_notify) - self.assertFalse(obj.on_notify_called) - obj.notify('value') - self.assertTrue(obj.on_notify_called) - - def test_signal_emit(self): - # standard callback connection with different forms of emit. - obj = self.CustomButton() - obj.connect('clicked', self.on_clicked) - - # vanilla - obj.emit('clicked', 1) - self.assertEqual(obj.value, 1) - self.assertEqual(obj, self.obj) - self.assertEqual(self.value, 1) - - # using class signal as param - self.obj = None - self.value = None - obj.emit(self.CustomButton.clicked, 1) - self.assertEqual(obj, self.obj) - self.assertEqual(self.value, 1) - - # using bound signal as param - self.obj = None - self.value = None - obj.emit(obj.clicked, 1) - self.assertEqual(obj, self.obj) - self.assertEqual(self.value, 1) - - # using bound signal with emit - self.obj = None - self.value = None - obj.clicked.emit(1) - self.assertEqual(obj, self.obj) - self.assertEqual(self.value, 1) - - def test_signal_class_connect(self): - obj = self.CustomButton() - obj.connect(self.CustomButton.clicked, self.on_clicked) - obj.emit('clicked', 2) - self.assertEqual(obj, self.obj) - self.assertEqual(self.value, 2) - - def test_signal_bound_connect(self): - obj = self.CustomButton() - obj.clicked.connect(self.on_clicked) - obj.emit('clicked', 3) - self.assertEqual(obj, self.obj) - self.assertEqual(self.value, 3) - - -class _ConnectDataTestBase(object): - # Notes: - # - self.Object is overridden in sub-classes. - # - Numeric suffixes indicate the number of user data args passed in. - Object = None - - def run_connect_test(self, emit_args, user_data, flags=0): - obj = self.Object() - callback_args = [] - - def callback(*args): - callback_args.append(args) - return 0 - - obj.connect_data('sig-with-int64-prop', callback, connect_flags=flags, *user_data) - obj.emit('sig-with-int64-prop', *emit_args) - self.assertEqual(len(callback_args), 1) - return callback_args[0] - - def test_0(self): - obj, value = self.run_connect_test([GLib.MAXINT64], user_data=[]) - self.assertIsInstance(obj, self.Object) - self.assertEqual(value, GLib.MAXINT64) - - def test_1(self): - obj, value, data = self.run_connect_test([GLib.MAXINT64], - user_data=['mydata']) - self.assertIsInstance(obj, self.Object) - self.assertEqual(value, GLib.MAXINT64) - self.assertEqual(data, 'mydata') - - def test_after_0(self): - obj, value = self.run_connect_test([GLib.MAXINT64], - user_data=[], - flags=GObject.ConnectFlags.AFTER) - self.assertIsInstance(obj, self.Object) - self.assertEqual(value, GLib.MAXINT64) - - def test_after_1(self): - obj, value, data = self.run_connect_test([GLib.MAXINT64], - user_data=['mydata'], - flags=GObject.ConnectFlags.AFTER) - self.assertIsInstance(obj, self.Object) - self.assertEqual(value, GLib.MAXINT64) - self.assertEqual(data, 'mydata') - - def test_swaped_0(self): - # Swapped only works with a single user data argument. - with self.assertRaises(ValueError): - self.run_connect_test([GLib.MAXINT64], - user_data=[], - flags=GObject.ConnectFlags.SWAPPED) - - def test_swaped_1(self): - # Notice obj and data are reversed in the return. - data, value, obj = self.run_connect_test([GLib.MAXINT64], - user_data=['mydata'], - flags=GObject.ConnectFlags.SWAPPED) - self.assertIsInstance(obj, self.Object) - self.assertEqual(value, GLib.MAXINT64) - self.assertEqual(data, 'mydata') - - def test_swaped_2(self): - # Swapped only works with a single user data argument. - with self.assertRaises(ValueError): - self.run_connect_test([GLib.MAXINT64], - user_data=[1, 2], - flags=GObject.ConnectFlags.SWAPPED) - - def test_after_and_swapped_0(self): - # Swapped only works with a single user data argument. - with self.assertRaises(ValueError): - self.run_connect_test([GLib.MAXINT64], - user_data=[], - flags=GObject.ConnectFlags.AFTER | GObject.ConnectFlags.SWAPPED) - - def test_after_and_swapped_1(self): - # Notice obj and data are reversed in the return. - data, value, obj = self.run_connect_test([GLib.MAXINT64], - user_data=['mydata'], - flags=GObject.ConnectFlags.AFTER | GObject.ConnectFlags.SWAPPED) - self.assertIsInstance(obj, self.Object) - self.assertEqual(value, GLib.MAXINT64) - self.assertEqual(data, 'mydata') - - def test_after_and_swapped_2(self): - # Swapped only works with a single user data argument. - with self.assertRaises(ValueError): - self.run_connect_test([GLib.MAXINT64], - user_data=[], - flags=GObject.ConnectFlags.AFTER | GObject.ConnectFlags.SWAPPED) - - -class TestConnectDataNonIntrospected(unittest.TestCase, _ConnectDataTestBase): - # This tests connect_data with non-introspected signals - # (created in Python in this case). - class Object(GObject.Object): - test = GObject.Signal() - sig_with_int64_prop = GObject.Signal(return_type=GObject.TYPE_INT64, - arg_types=[GObject.TYPE_INT64], - flags=GObject.SignalFlags.RUN_LAST) - - -class TestConnectDataIntrospected(unittest.TestCase, _ConnectDataTestBase): - # This tests connect_data with introspected signals brought in from Regress. - Object = Regress.TestObj - - -class TestInstallSignals(unittest.TestCase): - # These tests only test how signalhelper.install_signals works - # with the __gsignals__ dict and therefore does not need to use - # GObject as a base class because that would automatically call - # install_signals within the meta-class. - class Base(object): - __gsignals__ = {'test': (0, None, tuple())} - - class Sub1(Base): - pass - - class Sub2(Base): - @GObject.Signal - def sub2test(self): - pass - - def setUp(self): - self.assertEqual(len(self.Base.__gsignals__), 1) - signalhelper.install_signals(self.Base) - self.assertEqual(len(self.Base.__gsignals__), 1) - - def test_subclass_gets_empty_gsignals_dict(self): - # Installing signals will add the __gsignals__ dict to a class - # if it doesn't already exists. - self.assertFalse('__gsignals__' in self.Sub1.__dict__) - signalhelper.install_signals(self.Sub1) - self.assertTrue('__gsignals__' in self.Sub1.__dict__) - # Sub1 should only contain an empty signals dict, this tests: - # https://bugzilla.gnome.org/show_bug.cgi?id=686496 - self.assertEqual(self.Sub1.__dict__['__gsignals__'], {}) - - def test_subclass_with_decorator_gets_gsignals_dict(self): - self.assertFalse('__gsignals__' in self.Sub2.__dict__) - signalhelper.install_signals(self.Sub2) - self.assertTrue('__gsignals__' in self.Sub2.__dict__) - self.assertEqual(len(self.Base.__gsignals__), 1) - self.assertEqual(len(self.Sub2.__gsignals__), 1) - self.assertTrue('sub2test' in self.Sub2.__gsignals__) - - # Make sure the vfunc was added - self.assertTrue(hasattr(self.Sub2, 'do_sub2test')) - - -# For this test to work with both python2 and 3 we need to dynamically -# exec the given code due to the new syntax causing an error in python 2. -annotated_class_code = """ -class AnnotatedSignalClass(GObject.GObject): - @GObject.Signal - def sig1(self, a:int, b:float): - pass - - @GObject.Signal(flags=GObject.SignalFlags.RUN_LAST) - def sig2_with_return(self, a:int, b:float) -> str: - return "test" -""" - - -@unittest.skipUnless(sys.version_info >= (3, 0), - 'Argument annotations require Python 3') -class TestPython3Signals(unittest.TestCase): - AnnotatedClass = None - - def setUp(self): - exec(annotated_class_code, globals(), globals()) - self.assertTrue('AnnotatedSignalClass' in globals()) - self.AnnotatedClass = globals()['AnnotatedSignalClass'] - - def test_annotations(self): - self.assertEqual(signalhelper.get_signal_annotations(self.AnnotatedClass.sig1.func), - (None, (int, float))) - self.assertEqual(signalhelper.get_signal_annotations(self.AnnotatedClass.sig2_with_return.func), - (str, (int, float))) - - self.assertEqual(self.AnnotatedClass.sig2_with_return.get_signal_args(), - (GObject.SignalFlags.RUN_LAST, str, (int, float), None, None)) - self.assertEqual(self.AnnotatedClass.sig2_with_return.arg_types, - (int, float)) - self.assertEqual(self.AnnotatedClass.sig2_with_return.return_type, - str) - - def test_emit_return(self): - obj = self.AnnotatedClass() - self.assertEqual(obj.sig2_with_return.emit(1, 2.0), - 'test') - - -class TestSignalModuleLevelFunctions(unittest.TestCase): - def test_signal_list_ids_with_invalid_type(self): - with self.assertRaisesRegex(TypeError, 'type must be instantiable or an interface.*'): - GObject.signal_list_ids(GObject.TYPE_INVALID) - - def test_signal_list_ids(self): - with self.assertRaisesRegex(TypeError, 'type must be instantiable or an interface.*'): - GObject.signal_list_ids(GObject.TYPE_INT) - - ids = GObject.signal_list_ids(C) - self.assertEqual(len(ids), 1) - # Note canonicalized names - self.assertEqual(GObject.signal_name(ids[0]), 'my-signal') - # There is no signal 0 in gobject - self.assertEqual(GObject.signal_name(0), None) - - def test_signal_lookup_with_invalid_type(self): - with self.assertRaisesRegex(TypeError, 'type must be instantiable or an interface.*'): - GObject.signal_lookup('NOT_A_SIGNAL_NAME', GObject.TYPE_INVALID) - - def test_signal_lookup(self): - ids = GObject.signal_list_ids(C) - self.assertEqual(ids[0], GObject.signal_lookup('my_signal', C)) - self.assertEqual(ids[0], GObject.signal_lookup('my-signal', C)) - - with self.assertRaisesRegex(TypeError, 'type must be instantiable or an interface.*'): - GObject.signal_lookup('NOT_A_SIGNAL_NAME', GObject.TYPE_INT) - - # Invalid signal names return 0 instead of raising - self.assertEqual(GObject.signal_lookup('NOT_A_SIGNAL_NAME', C), - 0) - - def test_signal_query(self): - my_signal_id, = GObject.signal_list_ids(C) - - # Form is: (id, name, gtype, arg_count, return_type, (arg_type1, ...)) - my_signal_expected_query_result = [my_signal_id, 'my-signal', C.__gtype__, - 1, GObject.TYPE_NONE, (GObject.TYPE_INT,)] - # signal_query(name, type) - self.assertEqual(list(GObject.signal_query('my-signal', C)), my_signal_expected_query_result) - # signal_query(signal_id) - self.assertEqual(list(GObject.signal_query(my_signal_id)), my_signal_expected_query_result) - # invalid query returns None instead of raising - self.assertEqual(GObject.signal_query(0), None) - self.assertEqual(GObject.signal_query('NOT_A_SIGNAL', C), - None) - - -class TestIntrospectedSignals(unittest.TestCase): - def test_object_param_signal(self): - obj = Regress.TestObj() - - def callback(obj, obj_param): - self.assertEqual(obj_param.props.int, 3) - self.assertGreater(obj_param.__grefcount__, 1) - obj.called = True - - obj.called = False - obj.connect('sig-with-obj', callback) - obj.emit_sig_with_obj() - self.assertTrue(obj.called) - - def test_connect_after(self): - obj = Regress.TestObj() - - def callback(obj, obj_param): - obj.called = True - - obj.called = False - obj.connect_after('sig-with-obj', callback) - obj.emit_sig_with_obj() - self.assertTrue(obj.called) - - def test_int64_param_from_py(self): - obj = Regress.TestObj() - - def callback(obj, i): - obj.callback_i = i - return i - - obj.callback_i = None - obj.connect('sig-with-int64-prop', callback) - rv = obj.emit('sig-with-int64-prop', GLib.MAXINT64) - self.assertEqual(rv, GLib.MAXINT64) - self.assertEqual(obj.callback_i, GLib.MAXINT64) - - def test_uint64_param_from_py(self): - obj = Regress.TestObj() - - def callback(obj, i): - obj.callback_i = i - return i - - obj.callback_i = None - obj.connect('sig-with-uint64-prop', callback) - rv = obj.emit('sig-with-uint64-prop', GLib.MAXUINT64) - self.assertEqual(rv, GLib.MAXUINT64) - self.assertEqual(obj.callback_i, GLib.MAXUINT64) - - def test_int64_param_from_c(self): - obj = Regress.TestObj() - - def callback(obj, i): - obj.callback_i = i - return i - - obj.callback_i = None - - obj.connect('sig-with-int64-prop', callback) - obj.emit_sig_with_int64() - self.assertEqual(obj.callback_i, GLib.MAXINT64) - - def test_uint64_param_from_c(self): - obj = Regress.TestObj() - - def callback(obj, i): - obj.callback_i = i - return i - - obj.callback_i = None - - obj.connect('sig-with-uint64-prop', callback) - obj.emit_sig_with_uint64() - self.assertEqual(obj.callback_i, GLib.MAXUINT64) - - def test_intarray_ret(self): - obj = Regress.TestObj() - - def callback(obj, i): - obj.callback_i = i - return [i, i + 1] - - obj.callback_i = None - - try: - obj.connect('sig-with-intarray-ret', callback) - except TypeError as e: - # compat with g-i 1.34.x - if 'unknown signal' in str(e): - return - raise - - rv = obj.emit('sig-with-intarray-ret', 42) - self.assertEqual(obj.callback_i, 42) - self.assertEqual(type(rv), GLib.Array) - self.assertEqual(rv.len, 2) - - @unittest.skip('https://bugzilla.gnome.org/show_bug.cgi?id=669496') - def test_array_parm(self): - obj = Regress.TestObj() - - def callback(obj, arr): - obj.callback_arr = arr - - obj.connect('sig-with-array-prop', callback) - obj.callback_arr = None - self.assertEqual(obj.emit('sig-with-array-prop', [1, 2, GLib.MAXUINT]), None) - self.assertEqual(obj.callback_arr, [1, 2, GLib.MAXUINT]) - - def test_held_struct_ref(self): - held_structs = [] - - def callback(obj, struct): - # The struct held by Python will become a copy after this callback exits. - struct.some_int = 42 - struct.some_int8 = 42 - held_structs.append(struct) - - struct = Regress.TestSimpleBoxedA() - obj = Regress.TestObj() - - self.assertEqual(struct.some_int, 0) - self.assertEqual(struct.some_int8, 0) - - obj.connect('test-with-static-scope-arg', callback) - obj.emit('test-with-static-scope-arg', struct) - - # The held struct will be a copy of the modified struct. - self.assertEqual(len(held_structs), 1) - held_struct = held_structs[0] - self.assertEqual(held_struct.some_int, 42) - self.assertEqual(held_struct.some_int8, 42) - - # Boxed equality checks pointers by default. - self.assertNotEqual(struct, held_struct) - - -class _ConnectObjectTestBase(object): - # Notes: - # - self.Object is overridden in sub-classes. - # - Numeric suffixes indicate the number of user data args passed in. - Object = None - SwapObject = None - - def run_connect_test(self, emit_args, user_data, flags=0): - obj = self.Object() - callback_args = [] - swap_obj = self.SwapObject() - - def callback(*args): - callback_args.append(args) - return 0 - - if flags & GObject.ConnectFlags.AFTER: - connect_func = obj.connect_object_after - else: - connect_func = obj.connect_object - - with capture_gi_deprecation_warnings(): - connect_func('sig-with-int64-prop', callback, swap_obj, *user_data) - obj.emit('sig-with-int64-prop', *emit_args) - self.assertEqual(len(callback_args), 1) - return callback_args[0] - - def test_0(self): - obj, value = self.run_connect_test([GLib.MAXINT64], user_data=[]) - self.assertIsInstance(obj, self.SwapObject) - self.assertEqual(value, GLib.MAXINT64) - - def test_1(self): - obj, value, data = self.run_connect_test([GLib.MAXINT64], - user_data=['mydata']) - self.assertIsInstance(obj, self.SwapObject) - self.assertEqual(value, GLib.MAXINT64) - self.assertEqual(data, 'mydata') - - def test_2(self): - obj, value, data1, data2 = self.run_connect_test([GLib.MAXINT64], - user_data=['mydata1', 'mydata2']) - self.assertIsInstance(obj, self.SwapObject) - self.assertEqual(value, GLib.MAXINT64) - self.assertEqual(data1, 'mydata1') - self.assertEqual(data2, 'mydata2') - - def test_after_0(self): - obj, value = self.run_connect_test([GLib.MAXINT64], - user_data=[], - flags=GObject.ConnectFlags.AFTER) - self.assertIsInstance(obj, self.SwapObject) - self.assertEqual(value, GLib.MAXINT64) - - def test_after_1(self): - obj, value, data = self.run_connect_test([GLib.MAXINT64], - user_data=['mydata'], - flags=GObject.ConnectFlags.AFTER) - self.assertIsInstance(obj, self.SwapObject) - self.assertEqual(value, GLib.MAXINT64) - self.assertEqual(data, 'mydata') - - def test_after_2(self): - obj, value, data1, data2 = self.run_connect_test([GLib.MAXINT64], - user_data=['mydata1', 'mydata2'], - flags=GObject.ConnectFlags.AFTER) - self.assertIsInstance(obj, self.SwapObject) - self.assertEqual(value, GLib.MAXINT64) - self.assertEqual(data1, 'mydata1') - self.assertEqual(data2, 'mydata2') - - -class TestConnectGObjectNonIntrospected(unittest.TestCase, _ConnectObjectTestBase): - # This tests connect_object with non-introspected signals - # (created in Python in this case). - class Object(GObject.Object): - test = GObject.Signal() - sig_with_int64_prop = GObject.Signal(return_type=GObject.TYPE_INT64, - arg_types=[GObject.TYPE_INT64], - flags=GObject.SignalFlags.RUN_LAST) - - # Object passed for swapping is GObject based. - class SwapObject(GObject.Object): - pass - - -class TestConnectGObjectIntrospected(unittest.TestCase, _ConnectObjectTestBase): - # This tests connect_object with introspected signals brought in from Regress. - Object = Regress.TestObj - - # Object passed for swapping is GObject based. - class SwapObject(GObject.Object): - pass - - -class TestConnectPyObjectNonIntrospected(unittest.TestCase, _ConnectObjectTestBase): - # This tests connect_object with non-introspected signals - # (created in Python in this case). - class Object(GObject.Object): - test = GObject.Signal() - sig_with_int64_prop = GObject.Signal(return_type=GObject.TYPE_INT64, - arg_types=[GObject.TYPE_INT64], - flags=GObject.SignalFlags.RUN_LAST) - - # Object passed for swapping is pure Python - SwapObject = object - - -class TestConnectPyObjectIntrospected(unittest.TestCase, _ConnectObjectTestBase): - # This tests connect_object with introspected signals brought in from Regress. - Object = Regress.TestObj - - # Object passed for swapping is pure Python - SwapObject = object - - -class _RefCountTestBase(object): - # NOTE: ref counts are always one more than expected because the getrefcount() - # function adds a ref for the input argument. - - # Sub-classes set this - Object = None - - class PyData(object): - pass - - def test_callback_ref_count_del(self): - def callback(obj, value): - return value // 2 - - callback_ref = weakref.ref(callback) - self.assertEqual(sys.getrefcount(callback), 2) - - obj = self.Object() - obj.connect('sig-with-int64-prop', callback) - self.assertEqual(sys.getrefcount(callback), 3) - - del callback - self.assertEqual(sys.getrefcount(callback_ref()), 2) - - res = obj.emit('sig-with-int64-prop', 42) - self.assertEqual(res, 21) - self.assertEqual(sys.getrefcount(callback_ref), 2) - - del obj - self.assertIsNone(callback_ref()) - - def test_callback_ref_count_disconnect(self): - def callback(obj, value): - return value // 2 - - callback_ref = weakref.ref(callback) - self.assertEqual(sys.getrefcount(callback), 2) - - obj = self.Object() - handler_id = obj.connect('sig-with-int64-prop', callback) - self.assertEqual(sys.getrefcount(callback), 3) - - del callback - self.assertEqual(sys.getrefcount(callback_ref()), 2) - - res = obj.emit('sig-with-int64-prop', 42) - self.assertEqual(res, 21) - self.assertEqual(sys.getrefcount(callback_ref), 2) - - obj.disconnect(handler_id) - self.assertIsNone(callback_ref()) - - def test_callback_ref_count_disconnect_by_func(self): - def callback(obj, value): - return value // 2 - - callback_ref = weakref.ref(callback) - self.assertEqual(sys.getrefcount(callback), 2) - - obj = self.Object() - obj.connect('sig-with-int64-prop', callback) - self.assertEqual(sys.getrefcount(callback), 3) - - del callback - self.assertEqual(sys.getrefcount(callback_ref()), 2) - - res = obj.emit('sig-with-int64-prop', 42) - self.assertEqual(res, 21) - self.assertEqual(sys.getrefcount(callback_ref), 2) - - obj.disconnect_by_func(callback_ref()) - self.assertIsNone(callback_ref()) - - def test_user_data_ref_count(self): - def callback(obj, value, data): - return value // 2 - - data = self.PyData() - data_ref = weakref.ref(data) - self.assertEqual(sys.getrefcount(data), 2) - - obj = self.Object() - obj.connect('sig-with-int64-prop', callback, data) - self.assertEqual(sys.getrefcount(data), 3) - - del data - self.assertEqual(sys.getrefcount(data_ref()), 2) - - res = obj.emit('sig-with-int64-prop', 42) - self.assertEqual(res, 21) - self.assertEqual(sys.getrefcount(data_ref()), 2) - - del obj - self.assertIsNone(data_ref()) - - @unittest.expectedFailure # https://bugzilla.gnome.org/show_bug.cgi?id=688064 - def test_object_ref_count(self): - # connect_object() should only weakly reference the object passed in - # and auto-disconnect the signal when the object is destroyed. - def callback(data, value): - return value // 2 - - data = GObject.Object() - data_ref = weakref.ref(data) - self.assertEqual(sys.getrefcount(data), 2) - - obj = self.Object() - handler_id = obj.connect_object('sig-with-int64-prop', callback, data) - self.assertEqual(sys.getrefcount(data), 2) - - res = obj.emit('sig-with-int64-prop', 42) - self.assertEqual(res, 21) - self.assertEqual(sys.getrefcount(data), 2) - - del data - - self.assertIsNone(data_ref()) - self.assertFalse(obj.handler_is_connected(handler_id)) - - -class TestRefCountsNonIntrospected(unittest.TestCase, _RefCountTestBase): - class Object(GObject.Object): - sig_with_int64_prop = GObject.Signal(return_type=GObject.TYPE_INT64, - arg_types=[GObject.TYPE_INT64], - flags=GObject.SignalFlags.RUN_LAST) - - -class TestRefCountsIntrospected(unittest.TestCase, _RefCountTestBase): - Object = Regress.TestObj - - if __name__ == '__main__': unittest.main() diff --git a/tests/test_source.py b/tests/test_source.py index 866826e..fe674cd 100644 --- a/tests/test_source.py +++ b/tests/test_source.py @@ -1,14 +1,8 @@ # -*- Mode: Python -*- -import sys -import gc import unittest -import warnings from gi.repository import GLib -from gi import PyGIDeprecationWarning - -from helper import capture_glib_warnings class Idle(GLib.Idle): @@ -49,35 +43,25 @@ class TestSource(unittest.TestCase): timeout.set_callback(self.timeout_callback, loop) timeout.attach() - def test_sources(self): + def testSources(self): loop = GLib.MainLoop() self.setup_timeout(loop) idle = Idle(loop) - self.assertEqual(idle.get_context(), None) idle.attach() - self.assertEqual(idle.get_context(), GLib.main_context_default()) self.pos = 0 m = MySource() - self.assertEqual(m.get_context(), None) m.set_callback(self.my_callback, loop) m.attach() - self.assertEqual(m.get_context(), GLib.main_context_default()) loop.run() - m.destroy() - idle.destroy() - - self.assertGreater(self.pos, 0) - self.assertGreaterEqual(idle.count, 0) - self.assertTrue(m.is_destroyed()) - self.assertTrue(idle.is_destroyed()) + assert self.pos >= 0 and idle.count >= 0 - def test_source_prepare(self): + def testSourcePrepare(self): # this test may not terminate if prepare() is wrapped incorrectly dispatched = [False] loop = GLib.MainLoop() @@ -105,7 +89,7 @@ class TestSource(unittest.TestCase): assert dispatched[0] - def test_is_destroyed_simple(self): + def testIsDestroyedSimple(self): s = GLib.Source() self.assertFalse(s.is_destroyed()) @@ -119,7 +103,7 @@ class TestSource(unittest.TestCase): s.destroy() self.assertTrue(s.is_destroyed()) - def test_is_destroyed_context(self): + def testIsDestroyedContext(self): def f(): c = GLib.MainContext() s = GLib.Source() @@ -127,305 +111,14 @@ class TestSource(unittest.TestCase): return s s = f() - gc.collect() self.assertTrue(s.is_destroyed()) - def test_remove(self): - s = GLib.idle_add(dir) - self.assertEqual(GLib.source_remove(s), True) - - # Removing sources not found cause critical - with capture_glib_warnings(allow_criticals=True): - - # s is now removed, should fail now - self.assertEqual(GLib.source_remove(s), False) - - # accepts large source IDs (they are unsigned) - self.assertEqual(GLib.source_remove(GLib.MAXINT32), False) - self.assertEqual(GLib.source_remove(GLib.MAXINT32 + 1), False) - self.assertEqual(GLib.source_remove(GLib.MAXUINT32), False) - def test_recurse_property(self): - s = GLib.Idle() - self.assertTrue(s.can_recurse in [False, True]) - s.can_recurse = False - self.assertFalse(s.can_recurse) - - def test_priority(self): - s = GLib.Idle() - self.assertEqual(s.priority, GLib.PRIORITY_DEFAULT_IDLE) - s.priority = GLib.PRIORITY_HIGH - self.assertEqual(s.priority, GLib.PRIORITY_HIGH) - - s = GLib.Idle(GLib.PRIORITY_LOW) - self.assertEqual(s.priority, GLib.PRIORITY_LOW) - - s = GLib.Timeout(1, GLib.PRIORITY_LOW) - self.assertEqual(s.priority, GLib.PRIORITY_LOW) - - s = GLib.Source() - self.assertEqual(s.priority, GLib.PRIORITY_DEFAULT) - - def test_get_current_time(self): - # Note, deprecated API - s = GLib.Idle() - with warnings.catch_warnings(record=True) as w: - warnings.simplefilter('always') - time = s.get_current_time() - self.assertTrue(issubclass(w[0].category, PyGIDeprecationWarning)) - - self.assertTrue(isinstance(time, float)) - # plausibility check, and check magnitude of result - self.assertGreater(time, 1300000000.0) - self.assertLess(time, 2000000000.0) - - def test_add_remove_poll(self): - # FIXME: very shallow test, only verifies the API signature - pollfd = GLib.PollFD(99, GLib.IOCondition.IN | GLib.IOCondition.HUP) - self.assertEqual(pollfd.fd, 99) - source = GLib.Source() - source.add_poll(pollfd) - source.remove_poll(pollfd) - - def test_out_of_scope_before_dispatch(self): - # https://bugzilla.gnome.org/show_bug.cgi?id=504337 +class TestTimeout(unittest.TestCase): + def test504337(self): GLib.Timeout(20) GLib.Idle() - @unittest.skipIf(sys.platform == "darwin", "hangs") - def test_finalize(self): - self.dispatched = False - self.finalized = False - - class S(GLib.Source): - def prepare(s): - return (True, 1) - - def dispatch(s, callback, args): - self.dispatched = True - return False - - def finalize(s): - self.finalized = True - - source = S() - self.assertEqual(source.ref_count, 1) - source.attach() - self.assertEqual(source.ref_count, 2) - self.assertFalse(self.finalized) - self.assertFalse(source.is_destroyed()) - - while source.get_context().iteration(False): - pass - - source.destroy() - self.assertEqual(source.ref_count, 1) - self.assertTrue(self.dispatched) - self.assertFalse(self.finalized) - self.assertTrue(source.is_destroyed()) - del source - self.assertTrue(self.finalized) - - @unittest.skip('https://bugzilla.gnome.org/show_bug.cgi?id=722387') - def test_python_unref_with_active_source(self): - # Tests a Python derived Source which is free'd in the context of - # Python, but remains active in the MainContext (via source.attach()) - self.dispatched = False - self.finalized = False - - class S(GLib.Source): - def prepare(s): - return (True, 1) - - def check(s): - pass - - def dispatch(s, callback, args): - self.dispatched = True - return False - - def finalize(s): - self.finalized = True - - source = S() - id = source.attach() - self.assertFalse(self.finalized) - self.assertFalse(source.is_destroyed()) - - # Delete the source from Python but should still remain - # active in the main context. - del source - - context = GLib.MainContext.default() - while context.iteration(may_block=False): - pass - - self.assertTrue(self.dispatched) - self.assertFalse(self.finalized) - - source = context.find_source_by_id(id) - source.destroy() # Remove from main context. - self.assertTrue(source.is_destroyed()) - - # Source should be finalized called after del - del source - self.assertTrue(self.finalized) - - def test_extra_init_args(self): - class SourceWithInitArgs(GLib.Source): - def __init__(self, arg, kwarg=None): - super(SourceWithInitArgs, self).__init__() - self.arg = arg - self.kwarg = kwarg - - source = SourceWithInitArgs(1, kwarg=2) - self.assertEqual(source.arg, 1) - self.assertEqual(source.kwarg, 2) - - -@unittest.skipIf(sys.platform == "darwin", "hangs") -class TestUserData(unittest.TestCase): - def test_idle_no_data(self): - ml = GLib.MainLoop() - - def cb(): - ml.quit() - id = GLib.idle_add(cb) - self.assertEqual(ml.get_context().find_source_by_id(id).priority, - GLib.PRIORITY_DEFAULT_IDLE) - ml.run() - - def test_timeout_no_data(self): - ml = GLib.MainLoop() - - def cb(): - ml.quit() - id = GLib.timeout_add(1, cb) - self.assertEqual(ml.get_context().find_source_by_id(id).priority, - GLib.PRIORITY_DEFAULT) - ml.run() - - def test_idle_data(self): - ml = GLib.MainLoop() - - def cb(data): - data['called'] = True - ml.quit() - data = {} - id = GLib.idle_add(cb, data) - self.assertEqual(ml.get_context().find_source_by_id(id).priority, - GLib.PRIORITY_DEFAULT_IDLE) - ml.run() - self.assertTrue(data['called']) - - def test_idle_multidata(self): - ml = GLib.MainLoop() - - def cb(data, data2): - data['called'] = True - data['data2'] = data2 - ml.quit() - data = {} - id = GLib.idle_add(cb, data, 'hello') - self.assertEqual(ml.get_context().find_source_by_id(id).priority, - GLib.PRIORITY_DEFAULT_IDLE) - ml.run() - self.assertTrue(data['called']) - self.assertEqual(data['data2'], 'hello') - - def test_timeout_data(self): - ml = GLib.MainLoop() - - def cb(data): - data['called'] = True - ml.quit() - data = {} - id = GLib.timeout_add(1, cb, data) - self.assertEqual(ml.get_context().find_source_by_id(id).priority, - GLib.PRIORITY_DEFAULT) - ml.run() - self.assertTrue(data['called']) - - def test_timeout_multidata(self): - ml = GLib.MainLoop() - - def cb(data, data2): - data['called'] = True - data['data2'] = data2 - ml.quit() - data = {} - id = GLib.timeout_add(1, cb, data, 'hello') - self.assertEqual(ml.get_context().find_source_by_id(id).priority, - GLib.PRIORITY_DEFAULT) - ml.run() - self.assertTrue(data['called']) - self.assertEqual(data['data2'], 'hello') - - def test_idle_no_data_priority(self): - ml = GLib.MainLoop() - - def cb(): - ml.quit() - id = GLib.idle_add(cb, priority=GLib.PRIORITY_HIGH) - self.assertEqual(ml.get_context().find_source_by_id(id).priority, - GLib.PRIORITY_HIGH) - ml.run() - - def test_timeout_no_data_priority(self): - ml = GLib.MainLoop() - - def cb(): - ml.quit() - id = GLib.timeout_add(1, cb, priority=GLib.PRIORITY_HIGH) - self.assertEqual(ml.get_context().find_source_by_id(id).priority, - GLib.PRIORITY_HIGH) - ml.run() - - def test_idle_data_priority(self): - ml = GLib.MainLoop() - - def cb(data): - data['called'] = True - ml.quit() - data = {} - id = GLib.idle_add(cb, data, priority=GLib.PRIORITY_HIGH) - self.assertEqual(ml.get_context().find_source_by_id(id).priority, - GLib.PRIORITY_HIGH) - ml.run() - self.assertTrue(data['called']) - - def test_timeout_data_priority(self): - ml = GLib.MainLoop() - - def cb(data): - data['called'] = True - ml.quit() - data = {} - id = GLib.timeout_add(1, cb, data, priority=GLib.PRIORITY_HIGH) - self.assertEqual(ml.get_context().find_source_by_id(id).priority, - GLib.PRIORITY_HIGH) - ml.run() - self.assertTrue(data['called']) - - def cb_no_data(self): - self.loop.quit() - - def test_idle_method_callback_no_data(self): - self.loop = GLib.MainLoop() - GLib.idle_add(self.cb_no_data) - self.loop.run() - - def cb_with_data(self, data): - data['called'] = True - self.loop.quit() - - def test_idle_method_callback_with_data(self): - self.loop = GLib.MainLoop() - data = {} - GLib.idle_add(self.cb_with_data, data) - self.loop.run() - self.assertTrue(data['called']) - if __name__ == '__main__': unittest.main() diff --git a/tests/test_subprocess.py b/tests/test_subprocess.py index deea58f..69f5f4c 100644 --- a/tests/test_subprocess.py +++ b/tests/test_subprocess.py @@ -1,157 +1,24 @@ # -*- Mode: Python -*- import sys -import os import unittest -import warnings from gi.repository import GLib -from gi import PyGIDeprecationWarning -@unittest.skipIf(os.name == "nt", "not on Windows") class TestProcess(unittest.TestCase): - def test_deprecated_child_watch_no_data(self): - cb = lambda pid, status: None - pid = object() - with warnings.catch_warnings(record=True) as w: - warnings.simplefilter('always') - res = GLib._child_watch_add_get_args(pid, cb) - self.assertTrue(issubclass(w[0].category, PyGIDeprecationWarning)) - - self.assertEqual(len(res), 4) - self.assertEqual(res[0], GLib.PRIORITY_DEFAULT) - self.assertEqual(res[1], pid) - self.assertTrue(callable(cb)) - self.assertSequenceEqual(res[3], []) - - def test_deprecated_child_watch_data_priority(self): - cb = lambda pid, status: None - pid = object() - with warnings.catch_warnings(record=True) as w: - warnings.simplefilter('always') - res = GLib._child_watch_add_get_args(pid, cb, 12345, GLib.PRIORITY_HIGH) - self.assertTrue(issubclass(w[0].category, PyGIDeprecationWarning)) - - self.assertEqual(len(res), 4) - self.assertEqual(res[0], GLib.PRIORITY_HIGH) - self.assertEqual(res[1], pid) - self.assertEqual(res[2], cb) - self.assertSequenceEqual(res[3], [12345]) - - def test_deprecated_child_watch_data_priority_kwargs(self): - cb = lambda pid, status: None - pid = object() - with warnings.catch_warnings(record=True) as w: - warnings.simplefilter('always') - res = GLib._child_watch_add_get_args(pid, cb, priority=GLib.PRIORITY_HIGH, data=12345) - self.assertTrue(issubclass(w[0].category, PyGIDeprecationWarning)) - - self.assertEqual(len(res), 4) - self.assertEqual(res[0], GLib.PRIORITY_HIGH) - self.assertEqual(res[1], pid) - self.assertEqual(res[2], cb) - self.assertSequenceEqual(res[3], [12345]) - - @unittest.expectedFailure # using keyword args is fully supported by PyGObject machinery - def test_child_watch_all_kwargs(self): - cb = lambda pid, status: None - pid = object() - - res = GLib._child_watch_add_get_args(priority=GLib.PRIORITY_HIGH, pid=pid, function=cb, data=12345) - self.assertEqual(len(res), 4) - self.assertEqual(res[0], GLib.PRIORITY_HIGH) - self.assertEqual(res[1], pid) - self.assertEqual(res[2], cb) - self.assertSequenceEqual(res[3], [12345]) - - def test_child_watch_no_data(self): - def cb(pid, status): - self.status = status - self.loop.quit() - - self.status = None - self.loop = GLib.MainLoop() - argv = [sys.executable, '-c', 'import sys'] - pid, stdin, stdout, stderr = GLib.spawn_async( - argv, flags=GLib.SpawnFlags.DO_NOT_REAP_CHILD) - pid.close() - id = GLib.child_watch_add(GLib.PRIORITY_HIGH, pid, cb) - self.assertEqual(self.loop.get_context().find_source_by_id(id).priority, - GLib.PRIORITY_HIGH) - self.loop.run() - self.assertEqual(self.status, 0) - - def test_child_watch_with_data(self): - def cb(pid, status, data): - self.status = status - self.data = data - self.loop.quit() + def _child_watch_cb(self, pid, condition, data): + self.data = data + self.loop.quit() + def testChildWatch(self): self.data = None - self.status = None self.loop = GLib.MainLoop() argv = [sys.executable, '-c', 'import sys'] pid, stdin, stdout, stderr = GLib.spawn_async( - argv, flags=GLib.SpawnFlags.DO_NOT_REAP_CHILD) - self.assertEqual(stdin, None) - self.assertEqual(stdout, None) - self.assertEqual(stderr, None) - self.assertNotEqual(pid, 0) + argv, flags=GLib.SPAWN_DO_NOT_REAP_CHILD) pid.close() - id = GLib.child_watch_add(GLib.PRIORITY_HIGH, pid, cb, 12345) - self.assertEqual(self.loop.get_context().find_source_by_id(id).priority, - GLib.PRIORITY_HIGH) + GLib.child_watch_add(pid, self._child_watch_cb, 12345) self.loop.run() self.assertEqual(self.data, 12345) - self.assertEqual(self.status, 0) - - def test_spawn_async_fds(self): - pid, stdin, stdout, stderr = GLib.spawn_async( - ['cat'], flags=GLib.SpawnFlags.SEARCH_PATH, standard_input=True, - standard_output=True, standard_error=True) - os.write(stdin, b'hello world!\n') - os.close(stdin) - out = os.read(stdout, 50) - os.close(stdout) - err = os.read(stderr, 50) - os.close(stderr) - pid.close() - self.assertEqual(out, b'hello world!\n') - self.assertEqual(err, b'') - - def test_spawn_async_with_pipes(self): - res, pid, stdin, stdout, stderr = GLib.spawn_async_with_pipes( - working_directory=None, - argv=['cat'], - envp=None, - flags=GLib.SpawnFlags.SEARCH_PATH) - - os.write(stdin, b'hello world!\n') - os.close(stdin) - out = os.read(stdout, 50) - os.close(stdout) - err = os.read(stderr, 50) - os.close(stderr) - GLib.spawn_close_pid(pid) - self.assertEqual(out, b'hello world!\n') - self.assertEqual(err, b'') - - def test_spawn_async_envp(self): - pid, stdin, stdout, stderr = GLib.spawn_async( - ['sh', '-c', 'echo $TEST_VAR'], ['TEST_VAR=moo!'], - flags=GLib.SpawnFlags.SEARCH_PATH, standard_output=True) - self.assertEqual(stdin, None) - self.assertEqual(stderr, None) - out = os.read(stdout, 50) - os.close(stdout) - pid.close() - self.assertEqual(out, b'moo!\n') - - def test_backwards_compat_flags(self): - with warnings.catch_warnings(): - warnings.simplefilter('ignore', PyGIDeprecationWarning) - - self.assertEqual(GLib.SpawnFlags.DO_NOT_REAP_CHILD, - GLib.SPAWN_DO_NOT_REAP_CHILD) diff --git a/tests/test_thread.py b/tests/test_thread.py index 3da3310..b707bc4 100644 --- a/tests/test_thread.py +++ b/tests/test_thread.py @@ -9,25 +9,21 @@ from gi.repository import GLib class TestThread(unittest.TestCase): def setUp(self): self.main = GLib.MainLoop() - self.called = False def from_thread_cb(self, test, enum): assert test == self.obj assert int(enum) == 0 assert type(enum) != int - self.called = True - GLib.idle_add(self.timeout_cb) def idle_cb(self): self.obj = testhelper.get_test_thread() self.obj.connect('from-thread', self.from_thread_cb) self.obj.emit('emit-signal') - def test_extension_module(self): + def testExtensionModule(self): GLib.idle_add(self.idle_cb) - GLib.timeout_add(2000, self.timeout_cb) + GLib.timeout_add(50, self.timeout_cb) self.main.run() - self.assertTrue(self.called) def timeout_cb(self): self.main.quit() diff --git a/tests/test_typeclass.py b/tests/test_typeclass.py deleted file mode 100644 index 3ece684..0000000 --- a/tests/test_typeclass.py +++ /dev/null @@ -1,80 +0,0 @@ -# -*- Mode: Python; py-indent-offset: 4 -*- -# vim: tabstop=4 shiftwidth=4 expandtab -# -# test_typeclass.py: Tests for GTypeClass related methods and marshalling. -# -# Copyright (C) 2014 Simon Feltman <sfeltman@gnome.org> -# -# This library is free software; you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public -# License as published by the Free Software Foundation; either -# version 2.1 of the License, or (at your option) any later version. -# -# This library is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 -# USA - -import unittest - -from gi.repository import GObject -from gi.repository import GIMarshallingTests - - -class TestCoercion(unittest.TestCase): - def test_coerce_from_class(self): - prop = GObject.ObjectClass.find_property(GIMarshallingTests.PropertiesObject, - 'some-int') - - self.assertIsInstance(prop, GObject.GParamSpec) - self.assertEqual(prop.name, 'some-int') - self.assertEqual(prop.value_type, GObject.TYPE_INT) - self.assertEqual(prop.owner_type, - GIMarshallingTests.PropertiesObject.__gtype__) - - def test_coerce_from_gtype(self): - gtype = GIMarshallingTests.PropertiesObject.__gtype__ - prop = GObject.ObjectClass.find_property(gtype, 'some-int') - - self.assertIsInstance(prop, GObject.GParamSpec) - self.assertEqual(prop.name, 'some-int') - self.assertEqual(prop.value_type, GObject.TYPE_INT) - self.assertEqual(prop.owner_type, gtype) - - def test_coerce_from_instance(self): - obj = GIMarshallingTests.PropertiesObject() - prop = GObject.ObjectClass.find_property(obj, 'some-int') - - self.assertIsInstance(prop, GObject.GParamSpec) - self.assertEqual(prop.name, 'some-int') - self.assertEqual(prop.value_type, GObject.TYPE_INT) - self.assertEqual(prop.owner_type, obj.__gtype__) - - def test_marshalling_error(self): - with self.assertRaises(TypeError): - GObject.ObjectClass.find_property(object, 'some-int') - - with self.assertRaises(TypeError): - GObject.ObjectClass.find_property(42, 'some-int') - - -class TestTypeClassMethodsMovedToClass(unittest.TestCase): - def test_list_child_properties(self): - pspecs = GIMarshallingTests.PropertiesObject.list_properties() - pnames = [pspec.name for pspec in pspecs] - self.assertTrue('some-int' in pnames) - self.assertTrue('some-float' in pnames) - self.assertTrue('some-char' in pnames) - - def test_find_child_property(self): - pspec = GIMarshallingTests.PropertiesObject.find_property('some-int') - self.assertEqual(pspec.name, 'some-int') - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/test_uris.py b/tests/test_uris.py new file mode 100644 index 0000000..095a9dd --- /dev/null +++ b/tests/test_uris.py @@ -0,0 +1,15 @@ +import unittest + +from gi.repository import GLib + + +class TestUris(unittest.TestCase): + def testExtractUris(self): + uri_list_text = "# urn:isbn:0-201-08372-8\n" + \ + "http://www.huh.org/books/foo.html\n" + \ + "http://www.huh.org/books/foo.pdf\n" + \ + "ftp://ftp.foo.org/books/foo.txt\n" + uri_list = GLib.uri_list_extract_uris(uri_list_text) + assert uri_list[0] == "http://www.huh.org/books/foo.html" + assert uri_list[1] == "http://www.huh.org/books/foo.pdf" + assert uri_list[2] == "ftp://ftp.foo.org/books/foo.txt" diff --git a/tests/testhelpermodule.c b/tests/testhelpermodule.c index 343b14f..592c503 100644 --- a/tests/testhelpermodule.c +++ b/tests/testhelpermodule.c @@ -7,11 +7,14 @@ #include <pyglib-python-compat.h> +static PyTypeObject *_PyGObject_Type; +#define PyGObject_Type (*_PyGObject_Type) + static PyObject * _wrap_TestInterface__do_iface_method(PyObject *cls, PyObject *args, PyObject *kwargs); -static GType +GType test_type_get_type(void) { static GType gtype = 0; @@ -147,12 +150,12 @@ _wrap_TestInterface__proxy_do_iface_method(TestInterface *self) PyObject *py_args; PyObject *py_method; - __py_state = PyGILState_Ensure(); + __py_state = pyg_gil_state_ensure(); py_self = pygobject_new((GObject *) self); if (!py_self) { if (PyErr_Occurred()) PyErr_Print(); - PyGILState_Release(__py_state); + pyg_gil_state_release(__py_state); return; } py_args = PyTuple_New(0); @@ -162,7 +165,7 @@ _wrap_TestInterface__proxy_do_iface_method(TestInterface *self) PyErr_Print(); Py_DECREF(py_args); Py_DECREF(py_self); - PyGILState_Release(__py_state); + pyg_gil_state_release(__py_state); return; } py_retval = PyObject_CallObject(py_method, py_args); @@ -172,7 +175,7 @@ _wrap_TestInterface__proxy_do_iface_method(TestInterface *self) Py_DECREF(py_method); Py_DECREF(py_args); Py_DECREF(py_self); - PyGILState_Release(__py_state); + pyg_gil_state_release(__py_state); return; } if (py_retval != Py_None) { @@ -183,7 +186,7 @@ _wrap_TestInterface__proxy_do_iface_method(TestInterface *self) Py_DECREF(py_method); Py_DECREF(py_args); Py_DECREF(py_self); - PyGILState_Release(__py_state); + pyg_gil_state_release(__py_state); return; } @@ -191,7 +194,7 @@ _wrap_TestInterface__proxy_do_iface_method(TestInterface *self) Py_DECREF(py_method); Py_DECREF(py_args); Py_DECREF(py_self); - PyGILState_Release(__py_state); + pyg_gil_state_release(__py_state); } static void @@ -319,16 +322,6 @@ test_double_callback (GObject *object, double d) return d; } -static gint64 -test_int64_callback (GObject *object, gint64 i) -{ - g_return_val_if_fail (G_IS_OBJECT (object), -1); - - if (i == G_MAXINT64) - return i-1; - return i; -} - static char * test_string_callback (GObject *object, char *s) { @@ -346,69 +339,7 @@ test_object_callback (GObject *object, GObject *o) return o; } -static GParamSpec * -test_paramspec_callback (GObject *object) -{ - g_return_val_if_fail (G_IS_OBJECT (object), NULL); - - return g_param_spec_boolean ("test-param", "test", "test boolean", TRUE, G_PARAM_READABLE); -} - -static GValue * -test_gvalue_callback (GObject *object, const GValue *v) -{ - GValue *ret = g_malloc0 (sizeof (GValue)); - - g_return_val_if_fail (G_IS_OBJECT (object), NULL); - g_return_val_if_fail (G_IS_VALUE (v), NULL); - - g_value_init (ret, G_VALUE_TYPE (v)); - g_value_copy (v, ret); - return ret; -} - -static GValue * -test_gvalue_ret_callback (GObject *object, GType type) -{ - GValue *ret = g_malloc0 (sizeof (GValue)); - - g_return_val_if_fail (G_IS_OBJECT (object), NULL); - - g_value_init (ret, type); - - switch (type) { - case G_TYPE_INT: - g_value_set_int(ret, G_MAXINT); - break; - case G_TYPE_INT64: - g_value_set_int64(ret, G_MAXINT64); - break; - case G_TYPE_UINT: - g_value_set_uint(ret, G_MAXUINT); - break; - case G_TYPE_UINT64: - g_value_set_uint64(ret, G_MAXUINT64); - break; - case G_TYPE_STRING: - g_value_set_string(ret, "hello"); - break; - default: - g_critical ("test_gvalue_ret_callback() does not support type %s", g_type_name (type)); - } - - return ret; -} - -static GParamSpec * -test_paramspec_in_callback (GObject *object, GParamSpec *p) -{ - g_return_val_if_fail (G_IS_OBJECT (object), NULL); - g_return_val_if_fail (G_IS_PARAM_SPEC (p), NULL); - - return p; -} - -static void +void connectcallbacks (GObject *object) { @@ -443,10 +374,6 @@ connectcallbacks (GObject *object) G_CALLBACK (test_double_callback), NULL); g_signal_connect (G_OBJECT (object), - "test_int64", - G_CALLBACK (test_int64_callback), - NULL); - g_signal_connect (G_OBJECT (object), "test_string", G_CALLBACK (test_string_callback), NULL); @@ -454,22 +381,6 @@ connectcallbacks (GObject *object) "test_object", G_CALLBACK (test_object_callback), NULL); - g_signal_connect (G_OBJECT (object), - "test_paramspec", - G_CALLBACK (test_paramspec_callback), - NULL); - g_signal_connect (G_OBJECT (object), - "test_gvalue", - G_CALLBACK (test_gvalue_callback), - NULL); - g_signal_connect (G_OBJECT (object), - "test_gvalue_ret", - G_CALLBACK (test_gvalue_ret_callback), - NULL); - g_signal_connect (G_OBJECT (object), - "test_paramspec_in", - G_CALLBACK (test_paramspec_in_callback), - NULL); } static PyObject * @@ -513,10 +424,7 @@ _wrap_test_value_array(PyObject *self, PyObject *args) if (!PyArg_ParseTuple(args, "O", &obj)) return NULL; - G_GNUC_BEGIN_IGNORE_DEPRECATIONS g_value_init(value, G_TYPE_VALUE_ARRAY); - G_GNUC_END_IGNORE_DEPRECATIONS - if (pyg_value_from_pyobject(value, obj)) { PyErr_SetString(PyExc_TypeError, "Could not convert to GValueArray"); return NULL; @@ -543,6 +451,7 @@ _wrap_test_gerror_exception(PyObject *self, PyObject *args) return NULL; } + Py_DECREF(py_method); Py_DECREF(py_args); Py_DECREF(py_ret); @@ -612,17 +521,23 @@ static PyMethodDef testhelper_functions[] = { PYGLIB_MODULE_START(testhelper, "testhelper") { - PyObject *gobject_module; PyObject *m, *d; - - - if ((gobject_module = pygobject_init(-1, -1, -1)) == NULL) - return NULL; - Py_DECREF (gobject_module); + + g_thread_init(NULL); + pygobject_init(-1, -1, -1); d = PyModule_GetDict(module); - if ((m = PyImport_ImportModule("gi.repository.GObject")) == NULL) { + if ((m = PyImport_ImportModule("gi._gobject")) != NULL) { + PyObject *moddict = PyModule_GetDict(m); + + _PyGObject_Type = (PyTypeObject *)PyDict_GetItemString(moddict, "GObject"); + if (_PyGObject_Type == NULL) { + PyErr_SetString(PyExc_ImportError, + "cannot import name GObject from gobject"); + return PYGLIB_MODULE_ERROR_RETURN; + } + } else { PyErr_SetString(PyExc_ImportError, "could not import gobject"); return PYGLIB_MODULE_ERROR_RETURN; diff --git a/tests/testmodule.py b/tests/testmodule.py index c083f62..3da8ed5 100644 --- a/tests/testmodule.py +++ b/tests/testmodule.py @@ -7,8 +7,7 @@ class PyGObject(GObject.GObject): 'label': (GObject.TYPE_STRING, 'label property', 'the label of the object', - 'default', - GObject.ParamFlags.READABLE | GObject.ParamFlags.WRITABLE), + 'default', GObject.PARAM_READWRITE), } def __init__(self): |