# Test case demonstrating why it's important to be able to pickle
# GLib.Error instances.
#
# See: https://bugzilla.gnome.org/show_bug.cgi?id=791265
#
# Currently this test case will output:
#
#    Got exception in child process: g-file-error-quark: Failed to open file “/non-existant-file”: No such file or directory (4)
#    Subprocess died without raising an exception!
#
# If pickling of GLib.Error was possible, I would expect to see a
# proper traceback from the main process.


from gi.repository import GLib

import multiprocessing
import queue
import sys


# Example subprocess that reads the content of a file and returns
# either:
#
#   (True, contents) -> if the read succeeds
#   (False, exception) -> if something goes wrong.
#
def child_process(queue, filename):
    try:
        # This can return a GLib.Error if it fails to read the file.
        contents = GLib.file_get_contents(filename)
        queue.put((True, contents))
    except Exception as e:
        print("Got exception in child process: %s" % e)
        queue.put((False, e))


def run_test():
    q = multiprocessing.Queue()

    invalid_filename = '/non-existant-file'

    p = multiprocessing.Process(target=child_process, args=(q, invalid_filename))

    p.start()

    while True:
        try:
            result = q.get(timeout=1)
            break
        except queue.Empty as e:
            if len(multiprocessing.active_children()) == 0:
                raise RuntimeError("Subprocess died without raising an exception!")

    if result[0] == True:
        print("Got file contents: %s" % result[1])
    else:
        raise result[1]


try:
    run_test()
except RuntimeError as e:
    sys.stderr.write("%s\n" % e)
    sys.exit(1)
