<commit_before>#! /usr/bin/env python

import os
import sys
import tempfile
from glob import glob
from optparse import OptionParser
from difflib import unified_diff

PY_OUT_FILE_NAME = os.path.join(tempfile.gettempdir(), "py.out")
JS_OUT_FILE_NAME = os.path.join(tempfile.gettempdir(), "js.out")
JS_ERR_FILE_NAME = os.path.join(tempfile.gettempdir(), "js.err")
JS_SRC_FILE_NAME = os.path.join(tempfile.gettempdir(), "js.src")
JS_DIFF_FILE_NAME = os.path.join(tempfile.gettempdir(), "js.diff")
PY2JS_ERR_FILE_NAME = os.path.join(tempfile.gettempdir(), "py2js.err")

def test1(in_file):
    w = Writer()
    w.write("Testing the file: %s" % in_file)
    r = os.system('js -f py-builtins.js -f \"%s\"' % in_file)
    w.check(r)

def test2(in_file):
    w = Writer()
    w.write("Testing the file: %s" % in_file)
    command = ""
    if sys.platform == "win32":
        command = "set "
    r = os.system("%sPYTHONPATH=.:$PYTHONPATH python \"%s\"" % (command,in_file))
    w.check(r)

def test3(name, in_file=None, known_to_fail=False):

    in_file = in_file or name

    PYTHON_COMMAND = "python \"%s\" > \"%s\""
    PY2JS_COMMAND = "python pyjs.py --include-builtins \"%s\" > \"%s\" 2> \"%s\""
    JS_COMMAND = "js -f \"%s\" > \"%s\" 2> \"%s\""
    DIFF_COMMAND = "diff \"%s\" \"%s\" > \"%s\""
    w = Writer()
    w.write("%s [4]: " % name)
    r = os.system(PYTHON_COMMAND % (in_file, PY_OUT_FILE_NAME))
    w.write(".")
    if r == 0:
        r = os.system( PY2JS_COMMAND % (in_file, JS_SRC_FILE_NAME, PY2JS_ERR_FILE_NAME ))
        w.write(".")
        if r == 0:
            r = os.system( JS_COMMAND%(JS_SRC_FILE_NAME, JS_OUT_FILE_NAME, JS_ERR_FILE_NAME))
            w.write(".")
            if r == 0:
                r = os.system(DIFF_COMMAND%(JS_OUT_FILE_NAME, PY_OUT_FILE_NAME, JS_DIFF_FILE_NAME))
                w.write(".")
    w.check(r, known_to_fail)

def main():
    if not os.path.exists("py-builtins.js"):
        print "py-builtins.js not found. Run 'make' to generate it"
        sys.exit(1)

    parser = OptionParser(usage="%prog [options] filename",
        description="py2js tests.")
    parser.add_option("-a", "--run-all",
            action="store_true", dest="run_all",
            default=False, help="run all tests (including the known-to-fail)")
    options, args = parser.parse_args()
    if len(args) == 1:
        test3(args[0])
    else:
        test1("tests/test_builtins.js")
        files = glob("tests/test_*.py")
        for file in files:
            test2(file)
        dirs = [
            "tests/basic/*.py",
            "tests/errors/*.py",
            "tests/functions/*.py",
            "tests/lists/*.py",
            "tests/strings/*.py",
            "tests/algorithms/*.py",
                ]
        files = []
        for dir in dirs:
            files.extend((path,os.path.abspath(path)) for path in glob(dir))
        known_to_fail = [
                "tests/basic/nestedclass.py",
                "tests/basic/super.py",
                "tests/basic/kwargs.py",
                "tests/basic/float2int.py",
                "tests/basic/oo_inherit.py",
                "tests/basic/listcomp2.py",
                "tests/basic/del_dict.py",
                "tests/basic/del_local.py",
                "tests/basic/sumcomp.py",
                "tests/basic/del_array.py",
                "tests/basic/valueerror.py",
                "tests/basic/lambda.py",
                "tests/basic/try.py",
                "tests/basic/vargs.py",
                "tests/basic/del_attr.py",
                "tests/basic/del_global.py",
                "tests/basic/del_slice.py",
                "tests/basic/generator.py",
                "tests/basic/raise.py",

                "tests/functions/sort_cmp.py",
                "tests/functions/ne.py",
                "tests/functions/aug.py",
                "tests/functions/floatdiv.py",
                "tests/functions/sort23.py",

                "tests/errors/decorator.py",

                "tests/lists/filter.py",
                "tests/lists/reduce.py",
                "tests/lists/sum.py",
                "tests/lists/subclass.py",

                "tests/strings/string_format_d.py",
                "tests/strings/string_format_efg.py",
                "tests/strings/string_format_i.py",
                "tests/strings/string_format_o.py",
                "tests/strings/string_format_u.py",
                "tests/strings/string_format_x.py",
                "tests/strings/ulcase.py",
                ]
        known_to_fail = [os.path.abspath(path) for path in known_to_fail]
        files.sort()
        for name,file in files:
            if options.run_all:
                test3(name, file, file in known_to_fail)
            elif file not in known_to_fail:
                test3(name, file)

class Writer(object):

    def __init__(self):
        self._line_wrap = False
        self._write_pos = 0

    def write(self, text, color="", align="left", width=80):
        """
        Prints a text on the screen.

        It uses sys.stdout.write(), so no readline library is necessary.

        color ... choose from the colors below, "" means default color
        align ... left/right, left is a normal print, right is aligned on the
                  right hand side of the screen, filled with " " if necessary
        width ... the screen width
        """
        color_templates = (
            ("Black"       , "0;30"),
            ("Red"         , "0;31"),
            ("Green"       , "0;32"),
            ("Brown"       , "0;33"),
            ("Blue"        , "0;34"),
            ("Purple"      , "0;35"),
            ("Cyan"        , "0;36"),
            ("LightGray"   , "0;37"),
            ("DarkGray"    , "1;30"),
            ("LightRed"    , "1;31"),
            ("LightGreen"  , "1;32"),
            ("Yellow"      , "1;33"),
            ("LightBlue"   , "1;34"),
            ("LightPurple" , "1;35"),
            ("LightCyan"   , "1;36"),
            ("White"       , "1;37"),  )

        colors = {}

        for name, value in color_templates:
            colors[name] = value
        c_normal = '\033[0m'
        c_color = '\033[%sm'

        if align == "right":
            if self._write_pos+len(text) > width:
                # we don't fit on the current line, create a new line
                self.write("\n")
            self.write(" "*(width-self._write_pos-len(text)))

        if hasattr(sys.stdout, 'isatty') and not sys.stdout.isatty():
            # the stdout is not a terminal, this for example happens if the
            # output is piped to less, e.g. "bin/test | less". In this case,
            # the terminal control sequences would be printed verbatim, so
            # don't use any colors.
            color = ""
        if sys.platform == "win32":
            # Windows consoles don't support ANSI escape sequences
            color = ""

        if self._line_wrap:
            if text[0] != "\n":
                sys.stdout.write("\n")

        if color == "":
            sys.stdout.write(text)
        else:
            sys.stdout.write("%s%s%s" % (c_color % colors[color], text, c_normal))
        sys.stdout.flush()
        l = text.rfind("\n")
        if l == -1:
            self._write_pos += len(text)
        else:
            self._write_pos = len(text)-l-1
        self._line_wrap = self._write_pos >= width
        self._write_pos %= width

    def check(self, r, known_to_fail=False, exit_on_failure=True):
        if r == 0:
            if known_to_fail:
                self.write("should fail but [OK]", align="right", color="Green")
            else:
                self.write("[OK]", align="right", color="Green")
        else:
            if known_to_fail:
                self.write("known to [FAIL]", align="right", color="Purple")
            else:
                self.write("[FAIL]", align="right", color="Red")
                if exit_on_failure:
                    print
                    print
                    sys.exit(1)
        self.write("\n")

if __name__ == '__main__':
    main()
<commit_msg> * Changed sys.exit(1) to return False, to better integrate with applications and libraries that might use run_tests.py<commit_after>#! /usr/bin/env python

import os
import sys
import tempfile
from glob import glob
from optparse import OptionParser
from difflib import unified_diff

PY_OUT_FILE_NAME = os.path.join(tempfile.gettempdir(), "py.out")
JS_OUT_FILE_NAME = os.path.join(tempfile.gettempdir(), "js.out")
JS_ERR_FILE_NAME = os.path.join(tempfile.gettempdir(), "js.err")
JS_SRC_FILE_NAME = os.path.join(tempfile.gettempdir(), "js.src")
JS_DIFF_FILE_NAME = os.path.join(tempfile.gettempdir(), "js.diff")
PY2JS_ERR_FILE_NAME = os.path.join(tempfile.gettempdir(), "py2js.err")

def test1(in_file):
    w = Writer()
    w.write("Testing the file: %s" % in_file)
    r = os.system('js -f py-builtins.js -f \"%s\"' % in_file)
    w.check(r)

def test2(in_file):
    w = Writer()
    w.write("Testing the file: %s" % in_file)
    command = ""
    if sys.platform == "win32":
        command = "set "
    r = os.system("%sPYTHONPATH=.:$PYTHONPATH python \"%s\"" % (command,in_file))
    w.check(r)

def test3(name, in_file=None, known_to_fail=False):

    in_file = in_file or name

    PYTHON_COMMAND = "python \"%s\" > \"%s\""
    PY2JS_COMMAND = "python pyjs.py --include-builtins \"%s\" > \"%s\" 2> \"%s\""
    JS_COMMAND = "js -f \"%s\" > \"%s\" 2> \"%s\""
    DIFF_COMMAND = "diff \"%s\" \"%s\" > \"%s\""
    w = Writer()
    w.write("%s [4]: " % name)
    r = os.system(PYTHON_COMMAND % (in_file, PY_OUT_FILE_NAME))
    w.write(".")
    if r == 0:
        r = os.system( PY2JS_COMMAND % (in_file, JS_SRC_FILE_NAME, PY2JS_ERR_FILE_NAME ))
        w.write(".")
        if r == 0:
            r = os.system( JS_COMMAND%(JS_SRC_FILE_NAME, JS_OUT_FILE_NAME, JS_ERR_FILE_NAME))
            w.write(".")
            if r == 0:
                r = os.system(DIFF_COMMAND%(JS_OUT_FILE_NAME, PY_OUT_FILE_NAME, JS_DIFF_FILE_NAME))
                w.write(".")
    w.check(r, known_to_fail)

def main():
    if not os.path.exists("py-builtins.js"):
        print "py-builtins.js not found. Run 'make' to generate it"
        return False

    parser = OptionParser(usage="%prog [options] filename",
        description="py2js tests.")
    parser.add_option("-a", "--run-all",
            action="store_true", dest="run_all",
            default=False, help="run all tests (including the known-to-fail)")
    options, args = parser.parse_args()
    if len(args) == 1:
        test3(args[0])
    else:
        test1("tests/test_builtins.js")
        files = glob("tests/test_*.py")
        for file in files:
            test2(file)
        dirs = [
            "tests/basic/*.py",
            "tests/errors/*.py",
            "tests/functions/*.py",
            "tests/lists/*.py",
            "tests/strings/*.py",
            "tests/algorithms/*.py",
                ]
        files = []
        for dir in dirs:
            files.extend((path,os.path.abspath(path)) for path in glob(dir))
        known_to_fail = [
                "tests/basic/nestedclass.py",
                "tests/basic/super.py",
                "tests/basic/kwargs.py",
                "tests/basic/float2int.py",
                "tests/basic/oo_inherit.py",
                "tests/basic/listcomp2.py",
                "tests/basic/del_dict.py",
                "tests/basic/del_local.py",
                "tests/basic/sumcomp.py",
                "tests/basic/del_array.py",
                "tests/basic/valueerror.py",
                "tests/basic/lambda.py",
                "tests/basic/try.py",
                "tests/basic/vargs.py",
                "tests/basic/del_attr.py",
                "tests/basic/del_global.py",
                "tests/basic/del_slice.py",
                "tests/basic/generator.py",
                "tests/basic/raise.py",

                "tests/functions/sort_cmp.py",
                "tests/functions/ne.py",
                "tests/functions/aug.py",
                "tests/functions/floatdiv.py",
                "tests/functions/sort23.py",

                "tests/errors/decorator.py",

                "tests/lists/filter.py",
                "tests/lists/reduce.py",
                "tests/lists/sum.py",
                "tests/lists/subclass.py",

                "tests/strings/string_format_d.py",
                "tests/strings/string_format_efg.py",
                "tests/strings/string_format_i.py",
                "tests/strings/string_format_o.py",
                "tests/strings/string_format_u.py",
                "tests/strings/string_format_x.py",
                "tests/strings/ulcase.py",
                ]
        known_to_fail = [os.path.abspath(path) for path in known_to_fail]
        files.sort()
        for name,file in files:
            if options.run_all:
                test3(name, file, file in known_to_fail)
            elif file not in known_to_fail:
                test3(name, file)

class Writer(object):

    def __init__(self):
        self._line_wrap = False
        self._write_pos = 0

    def write(self, text, color="", align="left", width=80):
        """
        Prints a text on the screen.

        It uses sys.stdout.write(), so no readline library is necessary.

        color ... choose from the colors below, "" means default color
        align ... left/right, left is a normal print, right is aligned on the
                  right hand side of the screen, filled with " " if necessary
        width ... the screen width
        """
        color_templates = (
            ("Black"       , "0;30"),
            ("Red"         , "0;31"),
            ("Green"       , "0;32"),
            ("Brown"       , "0;33"),
            ("Blue"        , "0;34"),
            ("Purple"      , "0;35"),
            ("Cyan"        , "0;36"),
            ("LightGray"   , "0;37"),
            ("DarkGray"    , "1;30"),
            ("LightRed"    , "1;31"),
            ("LightGreen"  , "1;32"),
            ("Yellow"      , "1;33"),
            ("LightBlue"   , "1;34"),
            ("LightPurple" , "1;35"),
            ("LightCyan"   , "1;36"),
            ("White"       , "1;37"),  )

        colors = {}

        for name, value in color_templates:
            colors[name] = value
        c_normal = '\033[0m'
        c_color = '\033[%sm'

        if align == "right":
            if self._write_pos+len(text) > width:
                # we don't fit on the current line, create a new line
                self.write("\n")
            self.write(" "*(width-self._write_pos-len(text)))

        if hasattr(sys.stdout, 'isatty') and not sys.stdout.isatty():
            # the stdout is not a terminal, this for example happens if the
            # output is piped to less, e.g. "bin/test | less". In this case,
            # the terminal control sequences would be printed verbatim, so
            # don't use any colors.
            color = ""
        if sys.platform == "win32":
            # Windows consoles don't support ANSI escape sequences
            color = ""

        if self._line_wrap:
            if text[0] != "\n":
                sys.stdout.write("\n")

        if color == "":
            sys.stdout.write(text)
        else:
            sys.stdout.write("%s%s%s" % (c_color % colors[color], text, c_normal))
        sys.stdout.flush()
        l = text.rfind("\n")
        if l == -1:
            self._write_pos += len(text)
        else:
            self._write_pos = len(text)-l-1
        self._line_wrap = self._write_pos >= width
        self._write_pos %= width

    def check(self, r, known_to_fail=False, exit_on_failure=True):
        if r == 0:
            if known_to_fail:
                self.write("should fail but [OK]", align="right", color="Green")
            else:
                self.write("[OK]", align="right", color="Green")
        else:
            if known_to_fail:
                self.write("known to [FAIL]", align="right", color="Purple")
            else:
                self.write("[FAIL]", align="right", color="Red")
                if exit_on_failure:
                    print
                    print
                    sys.exit(1)
        self.write("\n")

if __name__ == '__main__':
    main()
<|endoftext|>


<commit_before>from __future__ import division
from libtbx import test_utils
import libtbx.load_env

tst_list = (
    "$D/test/command_line/tst_find_spots_server_client.py",
    ["$D/test/command_line/tst_dials_process.py", "1"],
    ["$D/test/command_line/tst_dials_process.py", "2"],
    "$D/test/tst_phil.py",
    "$D/test/framework/tst_interface.py",
    "$D/test/framework/tst_nexus.py",
    "$D/test/framework/tst_nexus_multi_experiment.py",
    "$D/test/command_line/tst_reindex.py",
    "$D/test/command_line/tst_import.py",
    "$D/test/command_line/tst_dials_show_isig_rmsd.py",
    "$D/test/command_line/tst_integrate.py",
    "$D/test/command_line/tst_detector_max_resolution.py",
    "$D/test/command_line/tst_predict.py",
    "$D/test/command_line/tst_import_xds.py",
    "$D/test/command_line/tst_merge_reflection_lists.py",
    "$D/test/command_line/tst_spotfinder.py",
    "$D/test/command_line/tst_export.py",
    "$D/test/command_line/tst_export_mosflm.py",
    "$D/test/command_line/tst_export_xds.py",
    "$D/test/command_line/tst_refine.py",
    "$D/test/command_line/tst_check_indexing_symmetry.py",
    "$D/test/command_line/tst_create_profile_model.py",
    "$D/test/command_line/tst_sort_reflections.py",
    "$D/test/command_line/tst_plot_scan_varying_crystal.py",
    "$D/test/command_line/tst_generate_mask.py",
    "$D/test/command_line/tst_show_extensions.py",
    "$D/test/command_line/tst_combine_experiments.py",
    "$D/test/command_line/tst_spot_counts_per_image.py",
    "$D/test/command_line/tst_stereographic_projections.py",
    "$D/test/command_line/tst_compare_orientation_matrices.py",
    "$D/test/command_line/tst_show_models.py",
    "$D/test/command_line/tst_slice_sweep.py",
    "$D/test/command_line/tst_rs_mapper.py",
    "$D/test/array_family/tst_flex_shoebox.py",
    "$D/test/array_family/tst_reflection_table.py",
    "$D/test/model/data/tst_prediction.py",
    "$D/test/model/data/tst_observation.py",
    "$D/test/model/data/tst_shoebox.py",
    "$D/test/algorithms/spot_prediction/tst_index_generator.py",
    "$D/test/algorithms/spot_prediction/tst_ray_predictor.py",
    "$D/test/algorithms/spot_prediction/tst_rotation_angles.py",
    "$D/test/algorithms/spot_prediction/tst_spot_prediction.py",
    "$D/test/algorithms/spot_prediction/tst_scan_varying_predictor.py",
    "$D/test/algorithms/spot_prediction/tst_reeke.py",
    "$D/test/algorithms/spot_prediction/tst_reeke_index_generator.py",
    "$B/test/algorithms/spot_prediction/tst_reeke_model",
    "$D/test/algorithms/spot_prediction/tst_scan_static_reflection_predictor.py",
    "$D/test/algorithms/spot_prediction/tst_scan_varying_reflection_predictor.py",
    "$D/test/algorithms/spot_prediction/tst_stills_reflection_predictor.py",
    "$D/test/algorithms/profile_model/tst_profile_model.py",
    "$D/test/algorithms/background/tst_modeller.py",
    "$D/test/algorithms/background/tst_outlier_rejector.py",
    "$D/test/algorithms/background/tst_mosflm_outlier_rejector.py",
    "$D/test/algorithms/background/tst_creator.py",
    "$D/test/algorithms/integration/profile/tst_grid_sampler.py",
    "$D/test/algorithms/integration/profile/tst_grid_sampler_2d.py",
    "$D/test/algorithms/integration/profile/tst_xds_circle_sampler.py",
    "$D/test/algorithms/integration/profile/tst_reference_locator.py",
    "$D/test/algorithms/integration/profile/tst_reference_learner.py",
    "$D/test/algorithms/integration/profile/tst_reference_learner2d.py",
    "$D/test/algorithms/integration/profile/tst_profile_fitting.py",
    "$D/test/algorithms/integration/tst_interface.py",
    "$D/test/algorithms/integration/tst_summation.py",
    "$D/test/algorithms/integration/tst_profile_fitting_rs.py",
    "$D/test/algorithms/integration/tst_corrections.py",
    "$B/test/algorithms/spatial_indexing/tst_quadtree",
    "$B/test/algorithms/spatial_indexing/tst_octree",
    "$B/test/algorithms/spatial_indexing/tst_collision_detection",
    "$D/test/algorithms/spatial_indexing/tst_spatial_index.py",
    "$D/test/algorithms/refinement/tst_refinement_regression.py",
    "$D/test/algorithms/refinement/tst_ref_passage_categorisation.py",
    "$D/test/algorithms/refinement/tst_prediction_parameters.py",
    "$D/test/algorithms/refinement/tst_finite_diffs.py",
    "$D/test/algorithms/refinement/tst_scan_varying_prediction_parameters.py",
    "$D/test/algorithms/refinement/tst_beam_parameters.py",
    "$D/test/algorithms/refinement/tst_crystal_parameters.py",
    "$D/test/algorithms/refinement/tst_detector_parameters.py",
    "$D/test/algorithms/refinement/tst_hierarchical_detector_refinement.py",
    "$D/test/algorithms/refinement/tst_multi_experiment_refinement.py",
    "$D/test/algorithms/refinement/tst_multi_panel_detector_parameterisation.py",
    "$D/test/algorithms/refinement/tst_refine_multi_wedges.py",
    "$D/test/algorithms/refinement/tst_stills_refinement.py",
    "$D/test/algorithms/refinement/tst_refine_multi_stills.py",
    "$D/test/algorithms/image/tst_centroid.py",
    "$D/test/algorithms/image/filter/tst_summed_area.py",
    "$D/test/algorithms/image/filter/tst_mean_and_variance.py",
    "$D/test/algorithms/image/filter/tst_median.py",
    "$D/test/algorithms/image/filter/tst_fano.py",
    "$D/test/algorithms/image/threshold/tst_local.py",
    "$D/test/algorithms/image/connected_components/tst_connected_components.py",
    "$D/test/algorithms/polygon/clip/tst_clipping.py",
    "$D/test/algorithms/polygon/tst_spatial_interpolation.py",
    "$D/test/algorithms/reflection_basis/tst_coordinate_system.py",
    "$D/test/algorithms/reflection_basis/tst_map_frames.py",
    "$D/test/algorithms/reflection_basis/tst_beam_vector_map.py",
    "$D/test/algorithms/reflection_basis/tst_grid_index_generator.py",
    "$D/test/algorithms/reflection_basis/tst_transform.py",
    "$D/test/algorithms/shoebox/tst_bbox_calculator.py",
    "$D/test/algorithms/shoebox/tst_partiality_calculator.py",
    "$D/test/algorithms/shoebox/tst_mask_foreground.py",
    "$D/test/algorithms/shoebox/tst_mask_overlapping.py",
    "$D/test/algorithms/shoebox/tst_find_overlapping.py",
    "$D/test/algorithms/generate_test_reflections/tst_generate_test_refl.py",
    "$D/test/tst_plot_reflections.py",
    ["$D/test/algorithms/indexing/tst_index.py", "1"],
    ["$D/test/algorithms/indexing/tst_index.py", "2"],
    ["$D/test/algorithms/indexing/tst_index.py", "3"],
    ["$D/test/algorithms/indexing/tst_index.py", "4"],
    ["$D/test/algorithms/indexing/tst_index.py", "7"],
    ["$D/test/algorithms/indexing/tst_index.py", "8"],
    ["$D/test/algorithms/indexing/tst_index.py", "9"],
    ["$D/test/algorithms/indexing/tst_index.py", "10"],
    ["$D/test/algorithms/indexing/tst_index.py", "11"],
    ["$D/test/algorithms/indexing/tst_index.py", "12"],
    ["$D/test/algorithms/indexing/tst_index.py", "13"],
    ["$D/test/algorithms/indexing/tst_index.py", "14"],
    ["$D/test/algorithms/indexing/tst_index.py", "15"],
    "$D/test/algorithms/indexing/tst_assign_indices.py",
    "$D/test/command_line/tst_refine_bravais_settings.py",
    "$D/test/command_line/tst_discover_better_experimental_model.py",
    "$D/test/algorithms/indexing/tst_compare_orientation_matrices.py",
    "$D/test/algorithms/indexing/tst_symmetry.py",
    "$D/scratch/rjg/unit_cell_refinement.py",
    )

def run () :
  build_dir = libtbx.env.under_build("dials")
  dist_dir = libtbx.env.dist_path("dials")
  test_utils.run_tests(build_dir, dist_dir, tst_list)

if (__name__ == "__main__"):
  run()
<commit_msg>Fixed test path<commit_after>from __future__ import division
from libtbx import test_utils
import libtbx.load_env

tst_list = (
    "$D/test/command_line/tst_find_spots_server_client.py",
    ["$D/test/command_line/tst_dials_process.py", "1"],
    ["$D/test/command_line/tst_dials_process.py", "2"],
    "$D/test/tst_phil.py",
    "$D/test/framework/tst_interface.py",
    "$D/test/util/tst_nexus.py",
    "$D/test/util/tst_nexus_multi_experiment.py",
    "$D/test/command_line/tst_reindex.py",
    "$D/test/command_line/tst_import.py",
    "$D/test/command_line/tst_dials_show_isig_rmsd.py",
    "$D/test/command_line/tst_integrate.py",
    "$D/test/command_line/tst_detector_max_resolution.py",
    "$D/test/command_line/tst_predict.py",
    "$D/test/command_line/tst_import_xds.py",
    "$D/test/command_line/tst_merge_reflection_lists.py",
    "$D/test/command_line/tst_spotfinder.py",
    "$D/test/command_line/tst_export.py",
    "$D/test/command_line/tst_export_mosflm.py",
    "$D/test/command_line/tst_export_xds.py",
    "$D/test/command_line/tst_refine.py",
    "$D/test/command_line/tst_check_indexing_symmetry.py",
    "$D/test/command_line/tst_create_profile_model.py",
    "$D/test/command_line/tst_sort_reflections.py",
    "$D/test/command_line/tst_plot_scan_varying_crystal.py",
    "$D/test/command_line/tst_generate_mask.py",
    "$D/test/command_line/tst_show_extensions.py",
    "$D/test/command_line/tst_combine_experiments.py",
    "$D/test/command_line/tst_spot_counts_per_image.py",
    "$D/test/command_line/tst_stereographic_projections.py",
    "$D/test/command_line/tst_compare_orientation_matrices.py",
    "$D/test/command_line/tst_show_models.py",
    "$D/test/command_line/tst_slice_sweep.py",
    "$D/test/command_line/tst_rs_mapper.py",
    "$D/test/array_family/tst_flex_shoebox.py",
    "$D/test/array_family/tst_reflection_table.py",
    "$D/test/model/data/tst_prediction.py",
    "$D/test/model/data/tst_observation.py",
    "$D/test/model/data/tst_shoebox.py",
    "$D/test/algorithms/spot_prediction/tst_index_generator.py",
    "$D/test/algorithms/spot_prediction/tst_ray_predictor.py",
    "$D/test/algorithms/spot_prediction/tst_rotation_angles.py",
    "$D/test/algorithms/spot_prediction/tst_spot_prediction.py",
    "$D/test/algorithms/spot_prediction/tst_scan_varying_predictor.py",
    "$D/test/algorithms/spot_prediction/tst_reeke.py",
    "$D/test/algorithms/spot_prediction/tst_reeke_index_generator.py",
    "$B/test/algorithms/spot_prediction/tst_reeke_model",
    "$D/test/algorithms/spot_prediction/tst_scan_static_reflection_predictor.py",
    "$D/test/algorithms/spot_prediction/tst_scan_varying_reflection_predictor.py",
    "$D/test/algorithms/spot_prediction/tst_stills_reflection_predictor.py",
    "$D/test/algorithms/profile_model/tst_profile_model.py",
    "$D/test/algorithms/background/tst_modeller.py",
    "$D/test/algorithms/background/tst_outlier_rejector.py",
    "$D/test/algorithms/background/tst_mosflm_outlier_rejector.py",
    "$D/test/algorithms/background/tst_creator.py",
    "$D/test/algorithms/integration/profile/tst_grid_sampler.py",
    "$D/test/algorithms/integration/profile/tst_grid_sampler_2d.py",
    "$D/test/algorithms/integration/profile/tst_xds_circle_sampler.py",
    "$D/test/algorithms/integration/profile/tst_reference_locator.py",
    "$D/test/algorithms/integration/profile/tst_reference_learner.py",
    "$D/test/algorithms/integration/profile/tst_reference_learner2d.py",
    "$D/test/algorithms/integration/profile/tst_profile_fitting.py",
    "$D/test/algorithms/integration/tst_interface.py",
    "$D/test/algorithms/integration/tst_summation.py",
    "$D/test/algorithms/integration/tst_profile_fitting_rs.py",
    "$D/test/algorithms/integration/tst_corrections.py",
    "$B/test/algorithms/spatial_indexing/tst_quadtree",
    "$B/test/algorithms/spatial_indexing/tst_octree",
    "$B/test/algorithms/spatial_indexing/tst_collision_detection",
    "$D/test/algorithms/spatial_indexing/tst_spatial_index.py",
    "$D/test/algorithms/refinement/tst_refinement_regression.py",
    "$D/test/algorithms/refinement/tst_ref_passage_categorisation.py",
    "$D/test/algorithms/refinement/tst_prediction_parameters.py",
    "$D/test/algorithms/refinement/tst_finite_diffs.py",
    "$D/test/algorithms/refinement/tst_scan_varying_prediction_parameters.py",
    "$D/test/algorithms/refinement/tst_beam_parameters.py",
    "$D/test/algorithms/refinement/tst_crystal_parameters.py",
    "$D/test/algorithms/refinement/tst_detector_parameters.py",
    "$D/test/algorithms/refinement/tst_hierarchical_detector_refinement.py",
    "$D/test/algorithms/refinement/tst_multi_experiment_refinement.py",
    "$D/test/algorithms/refinement/tst_multi_panel_detector_parameterisation.py",
    "$D/test/algorithms/refinement/tst_refine_multi_wedges.py",
    "$D/test/algorithms/refinement/tst_stills_refinement.py",
    "$D/test/algorithms/refinement/tst_refine_multi_stills.py",
    "$D/test/algorithms/image/tst_centroid.py",
    "$D/test/algorithms/image/filter/tst_summed_area.py",
    "$D/test/algorithms/image/filter/tst_mean_and_variance.py",
    "$D/test/algorithms/image/filter/tst_median.py",
    "$D/test/algorithms/image/filter/tst_fano.py",
    "$D/test/algorithms/image/threshold/tst_local.py",
    "$D/test/algorithms/image/connected_components/tst_connected_components.py",
    "$D/test/algorithms/polygon/clip/tst_clipping.py",
    "$D/test/algorithms/polygon/tst_spatial_interpolation.py",
    "$D/test/algorithms/reflection_basis/tst_coordinate_system.py",
    "$D/test/algorithms/reflection_basis/tst_map_frames.py",
    "$D/test/algorithms/reflection_basis/tst_beam_vector_map.py",
    "$D/test/algorithms/reflection_basis/tst_grid_index_generator.py",
    "$D/test/algorithms/reflection_basis/tst_transform.py",
    "$D/test/algorithms/shoebox/tst_bbox_calculator.py",
    "$D/test/algorithms/shoebox/tst_partiality_calculator.py",
    "$D/test/algorithms/shoebox/tst_mask_foreground.py",
    "$D/test/algorithms/shoebox/tst_mask_overlapping.py",
    "$D/test/algorithms/shoebox/tst_find_overlapping.py",
    "$D/test/algorithms/generate_test_reflections/tst_generate_test_refl.py",
    "$D/test/tst_plot_reflections.py",
    ["$D/test/algorithms/indexing/tst_index.py", "1"],
    ["$D/test/algorithms/indexing/tst_index.py", "2"],
    ["$D/test/algorithms/indexing/tst_index.py", "3"],
    ["$D/test/algorithms/indexing/tst_index.py", "4"],
    ["$D/test/algorithms/indexing/tst_index.py", "7"],
    ["$D/test/algorithms/indexing/tst_index.py", "8"],
    ["$D/test/algorithms/indexing/tst_index.py", "9"],
    ["$D/test/algorithms/indexing/tst_index.py", "10"],
    ["$D/test/algorithms/indexing/tst_index.py", "11"],
    ["$D/test/algorithms/indexing/tst_index.py", "12"],
    ["$D/test/algorithms/indexing/tst_index.py", "13"],
    ["$D/test/algorithms/indexing/tst_index.py", "14"],
    ["$D/test/algorithms/indexing/tst_index.py", "15"],
    "$D/test/algorithms/indexing/tst_assign_indices.py",
    "$D/test/command_line/tst_refine_bravais_settings.py",
    "$D/test/command_line/tst_discover_better_experimental_model.py",
    "$D/test/algorithms/indexing/tst_compare_orientation_matrices.py",
    "$D/test/algorithms/indexing/tst_symmetry.py",
    "$D/scratch/rjg/unit_cell_refinement.py",
    )

def run () :
  build_dir = libtbx.env.under_build("dials")
  dist_dir = libtbx.env.dist_path("dials")
  test_utils.run_tests(build_dir, dist_dir, tst_list)

if (__name__ == "__main__"):
  run()
<|endoftext|>


<commit_before>#!/usr/bin/env python
# encoding: utf-8
import sys
import os
from django.core.management import call_command, execute_manager, execute_from_command_line
from django.conf import settings

def use_exec(pdir):
    """
    instead, employ the technique used by django.core.management.execute_manager()
    """
    #import settings
    print "Installing media"
    # RUNNING MANAGEMENT COMMANDS CAUSES WIERD SETTINGS STUFF IN TESTS
    # ALL these cause subsequent manage.py test commands to fail:
    #
    # command.execute()
    # execute_manager(settings,['manage.py','install_media'])
    # execute_from_command_line(['manage.py','install_media'])
    # call_command('install_media')
    #
    # So we have to call install_media from the shell
    manage_path = os.path.join(pdir,'manage.py')
    res = os.popen("python %s install_media" % manage_path).read()
    print res

    print "Executing tests from command line"
    #execute_from_command_line(['manage.py','test','array','--failfast','-v','2'])
    execute_from_command_line(['manage.py','test'])

hdir = os.path.dirname(os.path.abspath(__file__))
pdir = os.path.join(hdir,'example_projects/test_project')
spdir = os.path.join(hdir,'example_projects')
sys.path.insert(0, pdir)
sys.path.insert(0, spdir)
#os.chdir(pdir)
os.environ['DJANGO_SETTINGS_MODULE'] = 'test_project.settings'

settings.TEST_RUNNER='xmlrunner.extra.djangotestrunner.run_tests'
settings.TEST_OUTPUT_DESCRIPTIONS=True
settings.DEBUG=True
settings.POSTGIS_TEMPLATE='template1'

use_exec(pdir)
<commit_msg>Backed out changeset 14756d0c88e5<commit_after>#!/usr/bin/env python
# encoding: utf-8
import sys
import os
from django.core.management import call_command, execute_manager, execute_from_command_line
from django.conf import settings

def use_exec(pdir):
    """
    instead, employ the technique used by django.core.management.execute_manager()
    """
    #import settings
    print "Installing media"
    from lingcod.common.management.commands.install_media import Command as InstallMediaCommand
    command = InstallMediaCommand()
    # RUNNING COMMANDS CAUSES WIERD SETTINGS STUFF
    # The solution is a horrible, horrible hack
    # We're forced to reimplement the install_media command
    # ALL these cause subsequent management commands to fail:
    #
    # command.execute()
    # execute_manager(settings,['manage.py','install_media'])
    # execute_from_command_line(['manage.py','install_media'])
    # call_command('install_media')
    #
    command.dry_run = False
    command.media_root = settings.MEDIA_ROOT
    command.force_compress = True

    lingcod_media_dir = command.get_lingcod_dir()
    project_media_dir = command.get_project_dir()

    if os.path.abspath(os.path.realpath(lingcod_media_dir)) == os.path.abspath(os.path.realpath(command.media_root)) or \
        os.path.abspath(os.path.realpath(project_media_dir)) == os.path.abspath(os.path.realpath(command.media_root)):
        raise Exception("Your MEDIA_ROOT setting has to be a directory other than your lingcod or project media folder!")

    command.copy_media_to_root(lingcod_media_dir)
    command.copy_media_to_root(project_media_dir)
    # Cant call synccompress so can't do command.compile_media()
    manage_path = os.path.join(pdir,'manage.py')
    res = os.popen("python %s synccompress" % manage_path).read()
    print res

    print "Executing from command line"
    #execute_from_command_line(['manage.py','test','array','--failfast','-v','2'])
    execute_from_command_line(['manage.py','test'])

hdir = os.path.dirname(os.path.abspath(__file__))
pdir = os.path.join(hdir,'example_projects/test_project')
spdir = os.path.join(hdir,'example_projects')
sys.path.insert(0, pdir)
sys.path.insert(0, spdir)
#os.chdir(pdir)
os.environ['DJANGO_SETTINGS_MODULE'] = 'test_project.settings'

settings.TEST_RUNNER='xmlrunner.extra.djangotestrunner.run_tests'
settings.TEST_OUTPUT_DESCRIPTIONS=True
settings.DEBUG=True
settings.POSTGIS_TEMPLATE='template1'

use_exec(pdir)
<|endoftext|>


<commit_before># vim: tabstop=4 shiftwidth=4 softtabstop=4

# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

"""
This is our basic test running framework based on Twisted's Trial.

Usage Examples:

    # to run all the tests
    python run_tests.py

    # to run a specific test suite imported here
    python run_tests.py NodeConnectionTestCase

    # to run a specific test imported here
    python run_tests.py NodeConnectionTestCase.test_reboot

    # to run some test suites elsewhere
    python run_tests.py nova.tests.node_unittest
    python run_tests.py nova.tests.node_unittest.NodeConnectionTestCase

Due to our use of multiprocessing it we frequently get some ignorable
'Interrupted system call' exceptions after test completion.

"""

import __main__
import os
import sys

from twisted.scripts import trial as trial_script

from nova import datastore
from nova import flags
from nova import twistd

from nova.tests.access_unittest import *
from nova.tests.auth_unittest import *
from nova.tests.api_unittest import *
from nova.tests.cloud_unittest import *
from nova.tests.compute_unittest import *
from nova.tests.flags_unittest import *
from nova.tests.model_unittest import *
from nova.tests.network_unittest import *
from nova.tests.objectstore_unittest import *
from nova.tests.process_unittest import *
from nova.tests.rpc_unittest import *
from nova.tests.validator_unittest import *
from nova.tests.volume_unittest import *

FLAGS = flags.FLAGS
flags.DEFINE_bool('flush_db', True,
                  'Flush the database before running fake tests')
flags.DEFINE_string('tests_stderr', 'run_tests.err.log',
                    'Path to where to pipe STDERR during test runs.'
                    ' Default = "run_tests.err.log"')

if __name__ == '__main__':
    OptionsClass = twistd.WrapTwistedOptions(trial_script.Options)
    config = OptionsClass()
    argv = config.parseOptions()

    FLAGS.verbose = True

    # TODO(termie): these should make a call instead of doing work on import
    if FLAGS.fake_tests:
        from nova.tests.fake_flags import *
        # use db 8 for fake tests
        FLAGS.redis_db = 8
        if FLAGS.flush_db:
            logging.info("Flushing redis datastore")
            r = datastore.Redis.instance()
            r.flushdb()
    else:
        from nova.tests.real_flags import *

    # Establish redirect for STDERR
    sys.stderr.flush()
    err = open(FLAGS.tests_stderr, 'w+', 0)
    os.dup2(err.fileno(), sys.stderr.fileno())

    if len(argv) == 1 and len(config['tests']) == 0:
        # If no tests were specified run the ones imported in this file
        # NOTE(termie): "tests" is not a flag, just some Trial related stuff
        config['tests'].update(['__main__'])
    elif len(config['tests']):
        # If we specified tests check first whether they are in __main__
        for arg in config['tests']:
            key = arg.split('.')[0]
            if hasattr(__main__, key):
                config['tests'].remove(arg)
                config['tests'].add('__main__.%s' % arg)

    trial_script._initialDebugSetup(config)
    trialRunner = trial_script._makeRunner(config)
    suite = trial_script._getSuite(config)
    if config['until-failure']:
        test_result = trialRunner.runUntilFailure(suite)
    else:
        test_result = trialRunner.run(suite)
    if config.tracer:
        sys.settrace(None)
        results = config.tracer.results()
        results.write_results(show_missing=1, summary=False,
                              coverdir=config.coverdir)
    sys.exit(not test_result.wasSuccessful())
<commit_msg>Support querying version list<commit_after># vim: tabstop=4 shiftwidth=4 softtabstop=4

# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

"""
This is our basic test running framework based on Twisted's Trial.

Usage Examples:

    # to run all the tests
    python run_tests.py

    # to run a specific test suite imported here
    python run_tests.py NodeConnectionTestCase

    # to run a specific test imported here
    python run_tests.py NodeConnectionTestCase.test_reboot

    # to run some test suites elsewhere
    python run_tests.py nova.tests.node_unittest
    python run_tests.py nova.tests.node_unittest.NodeConnectionTestCase

Due to our use of multiprocessing it we frequently get some ignorable
'Interrupted system call' exceptions after test completion.

"""

import __main__
import os
import sys

from twisted.scripts import trial as trial_script

from nova import datastore
from nova import flags
from nova import twistd

from nova.tests.access_unittest import *
from nova.tests.api_unittest import *
from nova.tests.api import *
from nova.tests.api.rackspace import *
from nova.tests.auth_unittest import *
from nova.tests.cloud_unittest import *
from nova.tests.compute_unittest import *
from nova.tests.flags_unittest import *
from nova.tests.model_unittest import *
from nova.tests.network_unittest import *
from nova.tests.objectstore_unittest import *
from nova.tests.process_unittest import *
from nova.tests.rpc_unittest import *
from nova.tests.validator_unittest import *
from nova.tests.volume_unittest import *

FLAGS = flags.FLAGS
flags.DEFINE_bool('flush_db', True,
                  'Flush the database before running fake tests')
flags.DEFINE_string('tests_stderr', 'run_tests.err.log',
                    'Path to where to pipe STDERR during test runs.'
                    ' Default = "run_tests.err.log"')

if __name__ == '__main__':
    OptionsClass = twistd.WrapTwistedOptions(trial_script.Options)
    config = OptionsClass()
    argv = config.parseOptions()

    FLAGS.verbose = True

    # TODO(termie): these should make a call instead of doing work on import
    if FLAGS.fake_tests:
        from nova.tests.fake_flags import *
        # use db 8 for fake tests
        FLAGS.redis_db = 8
        if FLAGS.flush_db:
            logging.info("Flushing redis datastore")
            r = datastore.Redis.instance()
            r.flushdb()
    else:
        from nova.tests.real_flags import *

    # Establish redirect for STDERR
    sys.stderr.flush()
    err = open(FLAGS.tests_stderr, 'w+', 0)
    os.dup2(err.fileno(), sys.stderr.fileno())

    if len(argv) == 1 and len(config['tests']) == 0:
        # If no tests were specified run the ones imported in this file
        # NOTE(termie): "tests" is not a flag, just some Trial related stuff
        config['tests'].update(['__main__'])
    elif len(config['tests']):
        # If we specified tests check first whether they are in __main__
        for arg in config['tests']:
            key = arg.split('.')[0]
            if hasattr(__main__, key):
                config['tests'].remove(arg)
                config['tests'].add('__main__.%s' % arg)

    trial_script._initialDebugSetup(config)
    trialRunner = trial_script._makeRunner(config)
    suite = trial_script._getSuite(config)
    if config['until-failure']:
        test_result = trialRunner.runUntilFailure(suite)
    else:
        test_result = trialRunner.run(suite)
    if config.tracer:
        sys.settrace(None)
        results = config.tracer.results()
        results.write_results(show_missing=1, summary=False,
                              coverdir=config.coverdir)
    sys.exit(not test_result.wasSuccessful())
<|endoftext|>


<commit_before>#!/usr/bin/env python
# -*- coding: utf 8 -*-
"""
Find and run tests.
"""
import unittest
import os

def run_tests():
    tests = []
    for root, dirs, files in os.walk('agilegeo'):
        if 'test' in root:
            tests.append(
                unittest.TestLoader().discover(root,
                                               pattern='*test.py'))
    suite = unittest.TestSuite(tests)
    return(suite)

if (__name__ == '__main__'):
    suite = run_tests()
    unittest.TextTestRunner(verbosity=2).run(suite)
<commit_msg>package name<commit_after>#!/usr/bin/env python
# -*- coding: utf 8 -*-
"""
Find and run tests.
"""
import unittest
import os

def run_tests():
    tests = []
    for root, dirs, files in os.walk('bruges'):
        if 'test' in root:
            tests.append(
                unittest.TestLoader().discover(root,
                                               pattern='*test.py'))
    suite = unittest.TestSuite(tests)
    return(suite)

if (__name__ == '__main__'):
    suite = run_tests()
    unittest.TextTestRunner(verbosity=2).run(suite)
<|endoftext|>


<commit_before>#!/usr/bin/env python
# vim: tabstop=4 shiftwidth=4 softtabstop=4

# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License");
#    you may not use this file except in compliance with the License.
#    You may obtain a copy of the License at
#
#        http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS,
#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#    See the License for the specific language governing permissions and
#    limitations under the License.

# Colorizer Code is borrowed from Twisted:
# Copyright (c) 2001-2010 Twisted Matrix Laboratories.
#
#    Permission is hereby granted, free of charge, to any person obtaining
#    a copy of this software and associated documentation files (the
#    "Software"), to deal in the Software without restriction, including
#    without limitation the rights to use, copy, modify, merge, publish,
#    distribute, sublicense, and/or sell copies of the Software, and to
#    permit persons to whom the Software is furnished to do so, subject to
#    the following conditions:
#
#    The above copyright notice and this permission notice shall be
#    included in all copies or substantial portions of the Software.
#
#    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
#    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
#    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
#    NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
#    LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
#    OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
#    WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""Unittest runner for Nova.

To run all tests
    python run_tests.py

To run a single test:
    python run_tests.py test_compute:ComputeTestCase.test_run_terminate

To run a single test module:
    python run_tests.py test_compute

    or

    python run_tests.py api.test_wsgi

"""

import gettext
import os
import unittest
import sys

# Workaround for bug in coverage 3.4 and below
# Fixed at https://bitbucket.org/ned/coveragepy/changeset/811ed58de8a3
try:
    sys.path[sys.path.index('')] = os.getcwd()
except ValueError:
    pass

gettext.install('nova', unicode=1)

from nose import config
from nose import core
from nose import result

from nova import log as logging
from nova.tests import fake_flags

class _AnsiColorizer(object):
    """
    A colorizer is an object that loosely wraps around a stream, allowing
    callers to write text to the stream in a particular color.

    Colorizer classes must implement C{supported()} and C{write(text, color)}.
    """
    _colors = dict(black=30, red=31, green=32, yellow=33,
                   blue=34, magenta=35, cyan=36, white=37)

    def __init__(self, stream):
        self.stream = stream

    def supported(cls, stream=sys.stdout):
        """
        A class method that returns True if the current platform supports
        coloring terminal output using this method. Returns False otherwise.
        """
        if not stream.isatty():
            return False  # auto color only on TTYs
        try:
            import curses
        except ImportError:
            return False
        else:
            try:
                try:
                    return curses.tigetnum("colors") > 2
                except curses.error:
                    curses.setupterm()
                    return curses.tigetnum("colors") > 2
            except:
                raise
                # guess false in case of error
                return False
    supported = classmethod(supported)

    def write(self, text, color):
        """
        Write the given text to the stream in the given color.

        @param text: Text to be written to the stream.

        @param color: A string label for a color. e.g. 'red', 'white'.
        """
        color = self._colors[color]
        self.stream.write('\x1b[%s;1m%s\x1b[0m' % (color, text))

class _Win32Colorizer(object):
    """
    See _AnsiColorizer docstring.
    """
    def __init__(self, stream):
        from win32console import GetStdHandle, STD_OUT_HANDLE, \
             FOREGROUND_RED, FOREGROUND_BLUE, FOREGROUND_GREEN, \
             FOREGROUND_INTENSITY
        red, green, blue, bold = (FOREGROUND_RED, FOREGROUND_GREEN,
                                  FOREGROUND_BLUE, FOREGROUND_INTENSITY)
        self.stream = stream
        self.screenBuffer = GetStdHandle(STD_OUT_HANDLE)
        self._colors = {
            'normal': red | green | blue,
            'red': red | bold,
            'green': green | bold,
            'blue': blue | bold,
            'yellow': red | green | bold,
            'magenta': red | blue | bold,
            'cyan': green | blue | bold,
            'white': red | green | blue | bold
            }

    def supported(cls, stream=sys.stdout):
        try:
            import win32console
            screenBuffer = win32console.GetStdHandle(
                win32console.STD_OUT_HANDLE)
        except ImportError:
            return False
        import pywintypes
        try:
            screenBuffer.SetConsoleTextAttribute(
                win32console.FOREGROUND_RED |
                win32console.FOREGROUND_GREEN |
                win32console.FOREGROUND_BLUE)
        except pywintypes.error:
            return False
        else:
            return True
    supported = classmethod(supported)

    def write(self, text, color):
        color = self._colors[color]
        self.screenBuffer.SetConsoleTextAttribute(color)
        self.stream.write(text)
        self.screenBuffer.SetConsoleTextAttribute(self._colors['normal'])

class _NullColorizer(object):
    """
    See _AnsiColorizer docstring.
    """
    def __init__(self, stream):
        self.stream = stream

    def supported(cls, stream=sys.stdout):
        return True
    supported = classmethod(supported)

    def write(self, text, color):
        self.stream.write(text)

class NovaTestResult(result.TextTestResult):
    def __init__(self, *args, **kw):
        result.TextTestResult.__init__(self, *args, **kw)
        self._last_case = None
        self.colorizer = None
        # NOTE(vish): reset stdout for the terminal check
        stdout = sys.stdout
        sys.stdout = sys.__stdout__
        for colorizer in [_Win32Colorizer, _AnsiColorizer, _NullColorizer]:
            if colorizer.supported():
                self.colorizer = colorizer(self.stream)
                break
        sys.stdout = stdout

    def getDescription(self, test):
        return str(test)

    # NOTE(vish): copied from unittest with edit to add color
    def addSuccess(self, test):
        unittest.TestResult.addSuccess(self, test)
        if self.showAll:
            self.colorizer.write("OK", 'green')
            self.stream.writeln()
        elif self.dots:
            self.stream.write('.')
            self.stream.flush()

    # NOTE(vish): copied from unittest with edit to add color
    def addFailure(self, test, err):
        unittest.TestResult.addFailure(self, test, err)
        if self.showAll:
            self.colorizer.write("FAIL", 'red')
            self.stream.writeln()
        elif self.dots:
            self.stream.write('F')
            self.stream.flush()

    # NOTE(vish): copied from nose with edit to add color
    def addError(self, test, err):
        """Overrides normal addError to add support for
        errorClasses. If the exception is a registered class, the
        error will be added to the list for that class, not errors.
        """
        stream = getattr(self, 'stream', None)
        ec, ev, tb = err
        try:
            exc_info = self._exc_info_to_string(err, test)
        except TypeError:
            # 2.3 compat
            exc_info = self._exc_info_to_string(err)
        for cls, (storage, label, isfail) in self.errorClasses.items():
            if result.isclass(ec) and issubclass(ec, cls):
                if isfail:
                    test.passed = False
                storage.append((test, exc_info))
                # Might get patched into a streamless result
                if stream is not None:
                    if self.showAll:
                        message = [label]
                        detail = result._exception_detail(err[1])
                        if detail:
                            message.append(detail)
                        stream.writeln(": ".join(message))
                    elif self.dots:
                        stream.write(label[:1])
                return
        self.errors.append((test, exc_info))
        test.passed = False
        if stream is not None:
            if self.showAll:
                self.colorizer.write("ERROR", 'red')
                self.stream.writeln()
            elif self.dots:
                stream.write('E')

    def startTest(self, test):
        unittest.TestResult.startTest(self, test)
        current_case = test.test.__class__.__name__

        if self.showAll:
            if current_case != self._last_case:
                self.stream.writeln(current_case)
                self._last_case = current_case

            self.stream.write(
                '    %s' % str(test.test._testMethodName).ljust(60))
            self.stream.flush()

class NovaTestRunner(core.TextTestRunner):
    def _makeResult(self):
        return NovaTestResult(self.stream,
                              self.descriptions,
                              self.verbosity,
                              self.config)

if __name__ == '__main__':
    logging.setup()
    # If any argument looks like a test name but doesn't have "nova.tests" in
    # front of it, automatically add that so we don't have to type as much
    argv = []
    for x in sys.argv:
        if x.startswith('test_'):
            argv.append('nova.tests.%s' % x)
        else:
            argv.append(x)

    testdir = os.path.abspath(os.path.join("nova", "tests"))
    c = config.Config(stream=sys.stdout,
                      env=os.environ,
                      verbosity=3,
                      workingDir=testdir,
                      plugins=core.DefaultPluginManager())

    runner = NovaTestRunner(stream=c.stream,
                            verbosity=c.verbosity,
                            config=c)
    sys.exit(not core.run(config=c, testRunner=runner, argv=argv))
<commit_msg>Fixed whitespace<commit_after>#!/usr/bin/env python
# vim: tabstop=4 shiftwidth=4 softtabstop=4

# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License");
#    you may not use this file except in compliance with the License.
#    You may obtain a copy of the License at
#
#        http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS,
#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#    See the License for the specific language governing permissions and
#    limitations under the License.

# Colorizer Code is borrowed from Twisted:
# Copyright (c) 2001-2010 Twisted Matrix Laboratories.
#
#    Permission is hereby granted, free of charge, to any person obtaining
#    a copy of this software and associated documentation files (the
#    "Software"), to deal in the Software without restriction, including
#    without limitation the rights to use, copy, modify, merge, publish,
#    distribute, sublicense, and/or sell copies of the Software, and to
#    permit persons to whom the Software is furnished to do so, subject to
#    the following conditions:
#
#    The above copyright notice and this permission notice shall be
#    included in all copies or substantial portions of the Software.
#
#    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
#    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
#    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
#    NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
#    LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
#    OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
#    WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""Unittest runner for Nova.

To run all tests
    python run_tests.py

To run a single test:
    python run_tests.py test_compute:ComputeTestCase.test_run_terminate

To run a single test module:
    python run_tests.py test_compute

    or

    python run_tests.py api.test_wsgi

"""

import gettext
import os
import unittest
import sys

# Workaround for bug in coverage 3.4 and below
# Fixed at https://bitbucket.org/ned/coveragepy/changeset/811ed58de8a3
try:
    sys.path[sys.path.index('')] = os.getcwd()
except ValueError:
    pass

gettext.install('nova', unicode=1)

from nose import config
from nose import core
from nose import result

from nova import log as logging
from nova.tests import fake_flags

class _AnsiColorizer(object):
    """
    A colorizer is an object that loosely wraps around a stream, allowing
    callers to write text to the stream in a particular color.

    Colorizer classes must implement C{supported()} and C{write(text, color)}.
    """
    _colors = dict(black=30, red=31, green=32, yellow=33,
                   blue=34, magenta=35, cyan=36, white=37)

    def __init__(self, stream):
        self.stream = stream

    def supported(cls, stream=sys.stdout):
        """
        A class method that returns True if the current platform supports
        coloring terminal output using this method. Returns False otherwise.
        """
        if not stream.isatty():
            return False  # auto color only on TTYs
        try:
            import curses
        except ImportError:
            return False
        else:
            try:
                try:
                    return curses.tigetnum("colors") > 2
                except curses.error:
                    curses.setupterm()
                    return curses.tigetnum("colors") > 2
            except:
                raise
                # guess false in case of error
                return False
    supported = classmethod(supported)

    def write(self, text, color):
        """
        Write the given text to the stream in the given color.

        @param text: Text to be written to the stream.

        @param color: A string label for a color. e.g. 'red', 'white'.
        """
        color = self._colors[color]
        self.stream.write('\x1b[%s;1m%s\x1b[0m' % (color, text))

class _Win32Colorizer(object):
    """
    See _AnsiColorizer docstring.
    """
    def __init__(self, stream):
        from win32console import GetStdHandle, STD_OUT_HANDLE, \
             FOREGROUND_RED, FOREGROUND_BLUE, FOREGROUND_GREEN, \
             FOREGROUND_INTENSITY
        red, green, blue, bold = (FOREGROUND_RED, FOREGROUND_GREEN,
                                  FOREGROUND_BLUE, FOREGROUND_INTENSITY)
        self.stream = stream
        self.screenBuffer = GetStdHandle(STD_OUT_HANDLE)
        self._colors = {
            'normal': red | green | blue,
            'red': red | bold,
            'green': green | bold,
            'blue': blue | bold,
            'yellow': red | green | bold,
            'magenta': red | blue | bold,
            'cyan': green | blue | bold,
            'white': red | green | blue | bold
            }

    def supported(cls, stream=sys.stdout):
        try:
            import win32console
            screenBuffer = win32console.GetStdHandle(
                win32console.STD_OUT_HANDLE)
        except ImportError:
            return False
        import pywintypes
        try:
            screenBuffer.SetConsoleTextAttribute(
                win32console.FOREGROUND_RED |
                win32console.FOREGROUND_GREEN |
                win32console.FOREGROUND_BLUE)
        except pywintypes.error:
            return False
        else:
            return True
    supported = classmethod(supported)

    def write(self, text, color):
        color = self._colors[color]
        self.screenBuffer.SetConsoleTextAttribute(color)
        self.stream.write(text)
        self.screenBuffer.SetConsoleTextAttribute(self._colors['normal'])

class _NullColorizer(object):
    """
    See _AnsiColorizer docstring.
    """
    def __init__(self, stream):
        self.stream = stream

    def supported(cls, stream=sys.stdout):
        return True
    supported = classmethod(supported)

    def write(self, text, color):
        self.stream.write(text)

class NovaTestResult(result.TextTestResult):
    def __init__(self, *args, **kw):
        result.TextTestResult.__init__(self, *args, **kw)
        self._last_case = None
        self.colorizer = None
        # NOTE(vish): reset stdout for the terminal check
        stdout = sys.stdout
        sys.stdout = sys.__stdout__
        for colorizer in [_Win32Colorizer, _AnsiColorizer, _NullColorizer]:
            if colorizer.supported():
                self.colorizer = colorizer(self.stream)
                break
        sys.stdout = stdout

    def getDescription(self, test):
        return str(test)

    # NOTE(vish): copied from unittest with edit to add color
    def addSuccess(self, test):
        unittest.TestResult.addSuccess(self, test)
        if self.showAll:
            self.colorizer.write("OK", 'green')
            self.stream.writeln()
        elif self.dots:
            self.stream.write('.')
            self.stream.flush()

    # NOTE(vish): copied from unittest with edit to add color
    def addFailure(self, test, err):
        unittest.TestResult.addFailure(self, test, err)
        if self.showAll:
            self.colorizer.write("FAIL", 'red')
            self.stream.writeln()
        elif self.dots:
            self.stream.write('F')
            self.stream.flush()

    # NOTE(vish): copied from nose with edit to add color
    def addError(self, test, err):
        """Overrides normal addError to add support for
        errorClasses. If the exception is a registered class, the
        error will be added to the list for that class, not errors.
        """
        stream = getattr(self, 'stream', None)
        ec, ev, tb = err
        try:
            exc_info = self._exc_info_to_string(err, test)
        except TypeError:
            # 2.3 compat
            exc_info = self._exc_info_to_string(err)
        for cls, (storage, label, isfail) in self.errorClasses.items():
            if result.isclass(ec) and issubclass(ec, cls):
                if isfail:
                    test.passed = False
                storage.append((test, exc_info))
                # Might get patched into a streamless result
                if stream is not None:
                    if self.showAll:
                        message = [label]
                        detail = result._exception_detail(err[1])
                        if detail:
                            message.append(detail)
                        stream.writeln(": ".join(message))
                    elif self.dots:
                        stream.write(label[:1])
                return
        self.errors.append((test, exc_info))
        test.passed = False
        if stream is not None:
            if self.showAll:
                self.colorizer.write("ERROR", 'red')
                self.stream.writeln()
            elif self.dots:
                stream.write('E')

    def startTest(self, test):
        unittest.TestResult.startTest(self, test)
        current_case = test.test.__class__.__name__

        if self.showAll:
            if current_case != self._last_case:
                self.stream.writeln(current_case)
                self._last_case = current_case

            self.stream.write(
                '    %s' % str(test.test._testMethodName).ljust(60))
            self.stream.flush()

class NovaTestRunner(core.TextTestRunner):
    def _makeResult(self):
        return NovaTestResult(self.stream,
                              self.descriptions,
                              self.verbosity,
                              self.config)

if __name__ == '__main__':
    logging.setup()
    # If any argument looks like a test name but doesn't have "nova.tests" in
    # front of it, automatically add that so we don't have to type as much
    argv = []
    for x in sys.argv:
        if x.startswith('test_'):
            argv.append('nova.tests.%s' % x)
        else:
            argv.append(x)

    testdir = os.path.abspath(os.path.join("nova", "tests"))
    c = config.Config(stream=sys.stdout,
                      env=os.environ,
                      verbosity=3,
                      workingDir=testdir,
                      plugins=core.DefaultPluginManager())

    runner = NovaTestRunner(stream=c.stream,
                            verbosity=c.verbosity,
                            config=c)
    sys.exit(not core.run(config=c, testRunner=runner, argv=argv))
<|endoftext|>


<commit_before>from website import app, models, init_for
init_for('dev')
models.db.create_all()
app.run('0.0.0.0', port=3000, debug=True)
<commit_msg>Optional port number in runserver (via @anandology).<commit_after>import sys
from website import app, models, init_for
init_for('dev')
models.db.create_all()

try:
    port = int(sys.argv[1])
except (IndexError, ValueError):
    port = 3000
app.run('0.0.0.0', port=port, debug=True)
<|endoftext|>


<commit_before>#!/usr/bin/env python
'''
    Copyright (C) 2014 Parrot SA

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions
    are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the
      distribution.
    * Neither the name of Parrot nor the names
      of its contributors may be used to endorse or promote products
      derived from this software without specific prior written
      permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
    FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
    COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
    OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
    AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
    OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
    OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
    SUCH DAMAGE.
'''

import sys
import os

MYDIR=os.path.abspath(os.path.dirname(sys.argv[0]))
if '' == MYDIR:
    MYDIR=os.getcwd()
sys.path.append('%(MYDIR)s/Utils/Python' % locals())

from ARFuncs import *
import xmlreader
import tempfile

uname = ARExecuteGetStdout(["uname"], printErrorMessage=False).lower()

verbose = False
if len(sys.argv) > 1:
    if sys.argv[1] == '-v':
        verbose = True
    else:
        ARPrint('Unknown options, this script only support `-v`')
        sys.exit(1)

targets = [
    {
        'name' : 'Generic',
        'platforms' : ['darwin', 'linux'],
        'mandatoryPlatform' : False,
        'bins' : ['git', 'wget', 'jar', 'automake', 'autoconf', 'libtool'],
        'libs' : [],
        'envs' : [],
        'cmds' : [],
        'CC' : None,
        },
    {
        'name' : 'iOS',
        'platforms' : ['darwin'],
        'mandatoryPlatform' : True,
        'bins' : ['xcrun', 'xcodebuild'],
        'libs' : [],
        'envs' : [],
        'cmds' : [],
        'CC' : None,
        },
    {
        'name' : 'Unix',
        'platforms' : ['darwin', 'linux'],
        'mandatoryPlatform' : False,
        'bins' : ['gcc', 'yasm', 'nasm'],
        'libs' : ['-lz', '-pthread'],
        'envs' : [],
        'cmds' : [],
        'CC' : 'gcc',
        },
    {
        'name' : 'Android',
        'platforms' : ['darwin', 'linux'],
        'mandatoryPlatform' : False,
        'bins' : ['rpl', 'javac', 'arm-linux-androideabi-gcc', 'mipsel-linux-android-gcc', 'i686-linux-android-gcc'],
        'libs' : ['-llog'],
        'envs' : ['ANDROID_NDK_PATH', 'ANDROID_SDK_PATH'],
        'cmds' : [
            {'cmd': 'android list targets | grep "API level:" | grep 19',
             'desc': 'Check if Android SDK 19 is installed',
             'fix': 'Missing Android SDK for API 19 (Android 4.4.2), please install it.'
             },
            ],
        'CC' : 'arm-linux-androideabi-gcc',
        },
]

hasColors = ARExecute('tput colors >/dev/null 2>&1', failOnError=False, printErrorMessage=False)

class logcolors:
    FAIL = '\033[31m' if hasColors else 'FA:'
    PASS = '\033[32m' if hasColors else 'OK:'
    NONE = '\033[33m' if hasColors else 'NT:'
    DEF  = '\033[39m' if hasColors else ''

def ARCEPrint(msg, noNewLine=False):
    if verbose:
        ARPrint(msg, noNewLine=noNewLine)

def ARPrintStatus(msg, status=False, unknown=False, padTo=20):
    if unknown:
        ARPrint(logcolors.NONE, noNewLine=True)
    elif status:
        ARPrint(logcolors.PASS, noNewLine=True)
    else:
        ARPrint(logcolors.FAIL, noNewLine=True)
    ARPrint(msg, noNewLine=True)
    if len(msg) < padTo:
        ARPrint(' '*(padTo-len(msg)), noNewLine=True)
    ARPrint(logcolors.DEF, noNewLine=True)

def ARAppendToMessage(orig, msg, leftPad=22):
    if len(orig) == 0:
        return msg
    return orig + '\n' + ' '*leftPad + msg

ARPrint('-- Checking if your environment will build the ARSDK for different platforms --')
ARPrint('')
ARPrint('[[ ' + logcolors.PASS + 'Should work' + logcolors.DEF + ', ' + logcolors.FAIL + 'Won\'t work' + logcolors.DEF + ', ' + logcolors.NONE + 'Not tested, may work' + logcolors.DEF + ' ]]')
ARPrint('')

for t in targets:
    status = True
    unknown = False
    msg = ''
    ARCEPrint ('Checking target %s ...' % t['name'])
    ARCEPrint ('--------------------------')
    ARCEPrint ('Checking platform ...', noNewLine=True)
    if uname in t['platforms'] or not t['mandatoryPlatform']:
        if not uname in t['platforms']:
            ARCEPrint(' Unknown (%s)' % uname)
            msg = ARAppendToMessage(msg, 'Unknown platform `%s`, the target `%s` has only been tested on %s ' % (uname, t['name'], t['platforms']))
            unknown = True
        else:
            ARCEPrint(' OK (%s)' % uname)
        for b in t['bins']:
            ARCEPrint('Checking if binary `%s` is available in PATH ...' % b, noNewLine=True)
            if not ARExistsInPath(b):
                ARCEPrint(' NO')
                msg = ARAppendToMessage(msg, 'Missing binary `%s`' % b)
                status = False
            else:
                ARCEPrint(' YES')
        for l in t['libs']:
            ARCEPrint('Checking if library `%s` is available for linking ...' % l, noNewLine=True)
            (sfHandle, sfPath) = tempfile.mkstemp(suffix='.c')
            (binHandle, binPath) = tempfile.mkstemp(suffix='.out')
            os.close(binHandle)
            os.remove(binPath)
            sfFile = os.fdopen(sfHandle, 'w')
            sfFile.write('int main(int argc, char *argv[]) { return 0; }\n')
            sfFile.close()
            compiler = t['CC']
            if not compiler or not ARExistsInPath(compiler):
                ARCEPrint(' NO COMPILER FOUND')
                status = False
            else:
                if not ARExecute('%(compiler)s -o %(binPath)s %(sfPath)s %(l)s >/dev/null 2>&1' % locals(), printErrorMessage=False, failOnError=False):
                    ARCEPrint(' NO')
                    status = False
                    msg = ARAppendToMessage(msg, 'Missing library `%s`' % l)
                else:
                    ARCEPrint(' YES')
            if os.path.exists(binPath):
                os.remove(binPath)
            os.remove(sfPath)

        for e in t['envs']:
            ARCEPrint('Checking if the environment variable `%s` is set ...' % e, noNewLine=True)
            if not e in os.environ:
                ARCEPrint(' NO')
                msg = ARAppendToMessage(msg, 'Missing environment variable `%s`' % e)
                status = False
            else:
                ARCEPrint(' YES')
        for f in t['cmds']:
            ARCEPrint('Checking if the command `%s` (%s) works ...' % (f['cmd'], f['desc']), noNewLine=True)
            if not ARExecute(f['cmd'] + ' >/dev/null 2>&1', printErrorMessage=False, failOnError=False):
                ARCEPrint(' NO')
                status = False
                msg = ARAppendToMessage(msg, f['fix'])
            else:
                ARCEPrint(' YES')

    else:
        status = False
        ARCEPrint(' Bad (%s)' % uname)
        msg = ARAppendToMessage(msg, 'Bad platform `%s`, you need to be on %s to build the target `%s`' % (uname, t['platforms'], t['name']))
    ARCEPrint('')
    ARPrintStatus (t['name'], status, unknown)
    ARPrint(': ', noNewLine=True)
    if not msg:
        msg = 'OK !'
    ARPrint(msg)
    ARCEPrint('')
    if t['name'] == 'Generic':
        globalStatus = status
        if not globalStatus:
            ARPrint('ERROR !')
            break

ARPrint('')

if not globalStatus:
    ARPrint(logcolors.FAIL + 'Basic configuration is not met' + logcolors.DEF + ', the SDK3Build.py script will probably fail even before trying to build a target. Fix errors for virtual target "Generic" before launching the script')
    ARPrint('')

<commit_msg>[INTEGRATION] Added python version check to CheckEnv<commit_after>#!/usr/bin/env python
'''
    Copyright (C) 2014 Parrot SA

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions
    are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the
      distribution.
    * Neither the name of Parrot nor the names
      of its contributors may be used to endorse or promote products
      derived from this software without specific prior written
      permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
    FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
    COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
    OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
    AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
    OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
    OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
    SUCH DAMAGE.
'''

import sys
import os

MYDIR=os.path.abspath(os.path.dirname(sys.argv[0]))
if '' == MYDIR:
    MYDIR=os.getcwd()
sys.path.append('%(MYDIR)s/Utils/Python' % locals())

from ARFuncs import *
import xmlreader
import tempfile

uname = ARExecuteGetStdout(["uname"], printErrorMessage=False).lower()

verbose = False
if len(sys.argv) > 1:
    if sys.argv[1] == '-v':
        verbose = True
    else:
        ARPrint('Unknown options, this script only support `-v`')
        sys.exit(1)

targets = [
    {
        'name' : 'Generic',
        'platforms' : ['darwin', 'linux'],
        'mandatoryPlatform' : False,
        'bins' : ['git', 'wget', 'jar', 'automake', 'autoconf', 'libtool'],
        'libs' : [],
        'envs' : [],
        'cmds' : [],
        'CC' : None,
        },
    {
        'name' : 'iOS',
        'platforms' : ['darwin'],
        'mandatoryPlatform' : True,
        'bins' : ['xcrun', 'xcodebuild'],
        'libs' : [],
        'envs' : [],
        'cmds' : [],
        'CC' : None,
        },
    {
        'name' : 'Unix',
        'platforms' : ['darwin', 'linux'],
        'mandatoryPlatform' : False,
        'bins' : ['gcc', 'yasm', 'nasm'],
        'libs' : ['-lz', '-pthread'],
        'envs' : [],
        'cmds' : [],
        'CC' : 'gcc',
        },
    {
        'name' : 'Android',
        'platforms' : ['darwin', 'linux'],
        'mandatoryPlatform' : False,
        'bins' : ['rpl', 'javac', 'arm-linux-androideabi-gcc', 'mipsel-linux-android-gcc', 'i686-linux-android-gcc'],
        'libs' : ['-llog'],
        'envs' : ['ANDROID_NDK_PATH', 'ANDROID_SDK_PATH'],
        'cmds' : [
            {'cmd': 'android list targets | grep "API level:" | grep 19',
             'desc': 'Check if Android SDK 19 is installed',
             'fix': 'Missing Android SDK for API 19 (Android 4.4.2), please install it.'
             },
            ],
        'CC' : 'arm-linux-androideabi-gcc',
        },
]

hasColors = ARExecute('tput colors >/dev/null 2>&1', failOnError=False, printErrorMessage=False)

class logcolors:
    FAIL = '\033[31m' if hasColors else 'FA:'
    PASS = '\033[32m' if hasColors else 'OK:'
    NONE = '\033[33m' if hasColors else 'NT:'
    DEF  = '\033[39m' if hasColors else ''

def ARCEPrint(msg, noNewLine=False):
    if verbose:
        ARPrint(msg, noNewLine=noNewLine)

def ARPrintStatus(msg, status=False, unknown=False, padTo=20):
    if unknown:
        ARPrint(logcolors.NONE, noNewLine=True)
    elif status:
        ARPrint(logcolors.PASS, noNewLine=True)
    else:
        ARPrint(logcolors.FAIL, noNewLine=True)
    ARPrint(msg, noNewLine=True)
    if len(msg) < padTo:
        ARPrint(' '*(padTo-len(msg)), noNewLine=True)
    ARPrint(logcolors.DEF, noNewLine=True)

def ARAppendToMessage(orig, msg, leftPad=22):
    if len(orig) == 0:
        return msg
    return orig + '\n' + ' '*leftPad + msg

ARPrint('-- Checking if your environment will build the ARSDK for different platforms --')
ARPrint('')
ARPrint('[[ ' + logcolors.PASS + 'Should work' + logcolors.DEF + ', ' + logcolors.FAIL + 'Won\'t work' + logcolors.DEF + ', ' + logcolors.NONE + 'Not tested, may work' + logcolors.DEF + ' ]]')
ARPrint('')

if sys.version_info < (2, 7):
    ARPrint(logcolors.FAIL + ' Bad python version.' + logcolors.DEF + ' The SDK requires python 2.7 or higher (python 3 versions are supported)')
    sys.exit(0)

for t in targets:
    status = True
    unknown = False
    msg = ''
    ARCEPrint ('Checking target %s ...' % t['name'])
    ARCEPrint ('--------------------------')
    ARCEPrint ('Checking platform ...', noNewLine=True)
    if uname in t['platforms'] or not t['mandatoryPlatform']:
        if not uname in t['platforms']:
            ARCEPrint(' Unknown (%s)' % uname)
            msg = ARAppendToMessage(msg, 'Unknown platform `%s`, the target `%s` has only been tested on %s ' % (uname, t['name'], t['platforms']))
            unknown = True
        else:
            ARCEPrint(' OK (%s)' % uname)
        for b in t['bins']:
            ARCEPrint('Checking if binary `%s` is available in PATH ...' % b, noNewLine=True)
            if not ARExistsInPath(b):
                ARCEPrint(' NO')
                msg = ARAppendToMessage(msg, 'Missing binary `%s`' % b)
                status = False
            else:
                ARCEPrint(' YES')
        for l in t['libs']:
            ARCEPrint('Checking if library `%s` is available for linking ...' % l, noNewLine=True)
            (sfHandle, sfPath) = tempfile.mkstemp(suffix='.c')
            (binHandle, binPath) = tempfile.mkstemp(suffix='.out')
            os.close(binHandle)
            os.remove(binPath)
            sfFile = os.fdopen(sfHandle, 'w')
            sfFile.write('int main(int argc, char *argv[]) { return 0; }\n')
            sfFile.close()
            compiler = t['CC']
            if not compiler or not ARExistsInPath(compiler):
                ARCEPrint(' NO COMPILER FOUND')
                status = False
            else:
                if not ARExecute('%(compiler)s -o %(binPath)s %(sfPath)s %(l)s >/dev/null 2>&1' % locals(), printErrorMessage=False, failOnError=False):
                    ARCEPrint(' NO')
                    status = False
                    msg = ARAppendToMessage(msg, 'Missing library `%s`' % l)
                else:
                    ARCEPrint(' YES')
            if os.path.exists(binPath):
                os.remove(binPath)
            os.remove(sfPath)

        for e in t['envs']:
            ARCEPrint('Checking if the environment variable `%s` is set ...' % e, noNewLine=True)
            if not e in os.environ:
                ARCEPrint(' NO')
                msg = ARAppendToMessage(msg, 'Missing environment variable `%s`' % e)
                status = False
            else:
                ARCEPrint(' YES')
        for f in t['cmds']:
            ARCEPrint('Checking if the command `%s` (%s) works ...' % (f['cmd'], f['desc']), noNewLine=True)
            if not ARExecute(f['cmd'] + ' >/dev/null 2>&1', printErrorMessage=False, failOnError=False):
                ARCEPrint(' NO')
                status = False
                msg = ARAppendToMessage(msg, f['fix'])
            else:
                ARCEPrint(' YES')

    else:
        status = False
        ARCEPrint(' Bad (%s)' % uname)
        msg = ARAppendToMessage(msg, 'Bad platform `%s`, you need to be on %s to build the target `%s`' % (uname, t['platforms'], t['name']))
    ARCEPrint('')
    ARPrintStatus (t['name'], status, unknown)
    ARPrint(': ', noNewLine=True)
    if not msg:
        msg = 'OK !'
    ARPrint(msg)
    ARCEPrint('')
    if t['name'] == 'Generic':
        globalStatus = status
        if not globalStatus:
            ARPrint('ERROR !')
            break

ARPrint('')

if not globalStatus:
    ARPrint(logcolors.FAIL + 'Basic configuration is not met' + logcolors.DEF + ', the SDK3Build.py script will probably fail even before trying to build a target. Fix errors for virtual target "Generic" before launching the script')
    ARPrint('')

<|endoftext|>


<commit_before>import xbmc
import xbmcvfs
import xbmcgui
import datetime
import time
import os
import resources.lib.utils as utils
from resources.lib.croniter import croniter
from resources.lib.backup import XbmcBackup

class BackupScheduler:
    monitor = None
    enabled = "false"
    next_run = 0
    restore_point = None

    def __init__(self):
        self.monitor = UpdateMonitor(update_method = self.settingsChanged)
        self.enabled = utils.getSetting("enable_scheduler")

        if(self.enabled == "true"):
            self.setup()

    def setup(self):
        #scheduler was turned on, find next run time
        utils.log("scheduler enabled, finding next run time")
        self.findNextRun(time.time())

    def start(self):

        #check if a backup should be resumed
        resumeRestore = self._resumeCheck()

        if(resumeRestore):
            restore = XbmcBackup()
            restore.selectRestore(self.restore_point)
            #skip the advanced settings check
            restore.skipAdvanced()
            restore.run(XbmcBackup.Restore)

        while(not xbmc.abortRequested):

            if(self.enabled == "true"):
                #scheduler is still on
                now = time.time()

                if(self.next_run <= now):
                    progress_mode = int(utils.getSetting('progress_mode'))
                    if(progress_mode != 2):
                        utils.showNotification(utils.getString(30053))

                    backup = XbmcBackup()

                    if(backup.remoteConfigured()):

                        if(int(utils.getSetting('progress_mode')) in [0,1]):
                            backup.run(XbmcBackup.Backup,True)
                        else:
                            backup.run(XbmcBackup.Backup,False)

                        #check if this is a "one-off"
                        if(int(utils.getSetting("schedule_interval")) == 0):
                            #disable the scheduler after this run
                            self.enabled = "false"
                            utils.setSetting('enable_scheduler','false')
                    else:
                        utils.showNotification(utils.getString(30045))

                    #check if we should shut the computer down
                    if(utils.getSetting("cron_shutdown") == 'true'):
                        #wait 10 seconds to make sure all backup processes and files are completed
                        time.sleep(10)
                        xbmc.executebuiltin('ShutDown()')
                    else:
                        #find the next run time like normal
                        self.findNextRun(now)

            xbmc.sleep(500)

        #delete monitor to free up memory
        del self.monitor

    def findNextRun(self,now):
        #find the cron expression and get the next run time
        cron_exp = self.parseSchedule()

        cron_ob = croniter(cron_exp,datetime.datetime.fromtimestamp(now))
        new_run_time = cron_ob.get_next(float)

        if(new_run_time != self.next_run):
            self.next_run = new_run_time
            utils.showNotification(utils.getString(30081) + " " + datetime.datetime.fromtimestamp(self.next_run).strftime('%m-%d-%Y %H:%M'))
            utils.log("scheduler will run again on " + datetime.datetime.fromtimestamp(self.next_run).strftime('%m-%d-%Y %H:%M'))

    def settingsChanged(self):
        current_enabled = utils.getSetting("enable_scheduler")

        if(current_enabled == "true" and self.enabled == "false"):
            #scheduler was just turned on
            self.enabled = current_enabled
            self.setup()
        elif (current_enabled == "false" and self.enabled == "true"):
            #schedule was turn off
            self.enabled = current_enabled

        if(self.enabled == "true"):
            #always recheck the next run time after an update
            self.findNextRun(time.time())

    def parseSchedule(self):
        schedule_type = int(utils.getSetting("schedule_interval"))
        cron_exp = utils.getSetting("cron_schedule")

        hour_of_day = utils.getSetting("schedule_time")
        hour_of_day = int(hour_of_day[0:2])
        if(schedule_type == 0 or schedule_type == 1):
            #every day
            cron_exp = "0 " + str(hour_of_day) + " * * *"
        elif(schedule_type == 2):
            #once a week
            day_of_week = utils.getSetting("day_of_week")
            cron_exp = "0 " + str(hour_of_day) + " * * " + day_of_week
        elif(schedule_type == 3):
            #first day of month
            cron_exp = "0 " + str(hour_of_day) + " 1 * *"

        return cron_exp

    def _resumeCheck(self):
        shouldContinue = False
        if(xbmcvfs.exists(xbmc.translatePath(utils.data_dir() + "resume.txt"))):
            rFile = xbmcvfs.File(xbmc.translatePath(utils.data_dir() + "resume.txt"),'r')
            self.restore_point = rFile.read()
            rFile.close()
            xbmcvfs.delete(xbmc.translatePath(utils.data_dir() + "resume.txt"))
            shouldContinue = xbmcgui.Dialog().yesno(utils.getString(30042),utils.getString(30043),utils.getString(30044))

        return shouldContinue

class UpdateMonitor(xbmc.Monitor):
    update_method = None

    def __init__(self,*args, **kwargs):
        xbmc.Monitor.__init__(self)
        self.update_method = kwargs['update_method']

    def onSettingsChanged(self):
        self.update_method()

BackupScheduler().start()
<commit_msg>fixes #90<commit_after>import xbmc
import xbmcvfs
import xbmcgui
import datetime
import time
import os
import resources.lib.utils as utils
from resources.lib.croniter import croniter
from resources.lib.backup import XbmcBackup

class BackupScheduler:
    monitor = None
    enabled = "false"
    next_run = 0
    restore_point = None

    def __init__(self):
        self.monitor = UpdateMonitor(update_method = self.settingsChanged)
        self.enabled = utils.getSetting("enable_scheduler")

        if(self.enabled == "true"):
            self.setup()

    def setup(self):
        #scheduler was turned on, find next run time
        utils.log("scheduler enabled, finding next run time")
        self.findNextRun(time.time())

    def start(self):

        #check if a backup should be resumed
        resumeRestore = self._resumeCheck()

        if(resumeRestore):
            restore = XbmcBackup()
            restore.selectRestore(self.restore_point)
            #skip the advanced settings check
            restore.skipAdvanced()
            restore.run(XbmcBackup.Restore)

        while(not xbmc.abortRequested):

            if(self.enabled == "true"):
                #scheduler is still on
                now = time.time()

                if(self.next_run <= now):
                    progress_mode = int(utils.getSetting('progress_mode'))
                    if(progress_mode != 2):
                        utils.showNotification(utils.getString(30053))

                    backup = XbmcBackup()

                    if(backup.remoteConfigured()):

                        if(int(utils.getSetting('progress_mode')) in [0,1]):
                            backup.run(XbmcBackup.Backup,True)
                        else:
                            backup.run(XbmcBackup.Backup,False)

                        #check if this is a "one-off"
                        if(int(utils.getSetting("schedule_interval")) == 0):
                            #disable the scheduler after this run
                            self.enabled = "false"
                            utils.setSetting('enable_scheduler','false')
                    else:
                        utils.showNotification(utils.getString(30045))

                    #check if we should shut the computer down
                    if(utils.getSetting("cron_shutdown") == 'true'):
                        #wait 10 seconds to make sure all backup processes and files are completed
                        time.sleep(10)
                        xbmc.executebuiltin('ShutDown()')
                    else:
                        #find the next run time like normal
                        self.findNextRun(now)

            xbmc.sleep(500)

        #delete monitor to free up memory
        del self.monitor

    def findNextRun(self,now):
        progress_mode = int(utils.getSetting('progress_mode'))

        #find the cron expression and get the next run time
        cron_exp = self.parseSchedule()

        cron_ob = croniter(cron_exp,datetime.datetime.fromtimestamp(now))
        new_run_time = cron_ob.get_next(float)

        if(new_run_time != self.next_run):
            self.next_run = new_run_time
            utils.log("scheduler will run again on " + datetime.datetime.fromtimestamp(self.next_run).strftime('%m-%d-%Y %H:%M'))

            #only show when not in silent mode
            if(progress_mode != 2):
                utils.showNotification(utils.getString(30081) + " " + datetime.datetime.fromtimestamp(self.next_run).strftime('%m-%d-%Y %H:%M'))

    def settingsChanged(self):
        current_enabled = utils.getSetting("enable_scheduler")

        if(current_enabled == "true" and self.enabled == "false"):
            #scheduler was just turned on
            self.enabled = current_enabled
            self.setup()
        elif (current_enabled == "false" and self.enabled == "true"):
            #schedule was turn off
            self.enabled = current_enabled

        if(self.enabled == "true"):
            #always recheck the next run time after an update
            self.findNextRun(time.time())

    def parseSchedule(self):
        schedule_type = int(utils.getSetting("schedule_interval"))
        cron_exp = utils.getSetting("cron_schedule")

        hour_of_day = utils.getSetting("schedule_time")
        hour_of_day = int(hour_of_day[0:2])
        if(schedule_type == 0 or schedule_type == 1):
            #every day
            cron_exp = "0 " + str(hour_of_day) + " * * *"
        elif(schedule_type == 2):
            #once a week
            day_of_week = utils.getSetting("day_of_week")
            cron_exp = "0 " + str(hour_of_day) + " * * " + day_of_week
        elif(schedule_type == 3):
            #first day of month
            cron_exp = "0 " + str(hour_of_day) + " 1 * *"

        return cron_exp

    def _resumeCheck(self):
        shouldContinue = False
        if(xbmcvfs.exists(xbmc.translatePath(utils.data_dir() + "resume.txt"))):
            rFile = xbmcvfs.File(xbmc.translatePath(utils.data_dir() + "resume.txt"),'r')
            self.restore_point = rFile.read()
            rFile.close()
            xbmcvfs.delete(xbmc.translatePath(utils.data_dir() + "resume.txt"))
            shouldContinue = xbmcgui.Dialog().yesno(utils.getString(30042),utils.getString(30043),utils.getString(30044))

        return shouldContinue

class UpdateMonitor(xbmc.Monitor):
    update_method = None

    def __init__(self,*args, **kwargs):
        xbmc.Monitor.__init__(self)
        self.update_method = kwargs['update_method']

    def onSettingsChanged(self):
        self.update_method()

BackupScheduler().start()
<|endoftext|>


<commit_before>from apscheduler.schedulers.blocking import BlockingScheduler
from warner import Warner
from archiver import Archiver
from announcer import Announcer
from flagger import Flagger
import os

sched = BlockingScheduler()

@sched.scheduled_job("cron", hour=4)
def destalinate_job():
    print("Destalinating")
    if "SB_TOKEN" not in os.environ or "API_TOKEN" not in os.environ:
        print "ERR: Missing at least one Slack environment variable."
        # print "1 {}".format(os.environ["SLACK_SLACKBOT_TOKEN"])
        # print "2 {}".format(os.environ["SLACK_API_TOKEN"])
    else:
        warner = Warner()
        archiver = Archiver()
        announcer = Announcer()
        flagger = Flagger()
        print("Warning")
        warner.warn()
        print("Archiving")
        archiver.archive()
        print("Announcing")
        announcer.announce()
        print("Flagging")
        flagger.flag()
        print("OK: destalinated")
    print("END: destalinate_job")

sched.start()
<commit_msg>removing outdated references to SLACK_SLACKBOT_TOKEN and SLACK_API_TOKEN<commit_after>from apscheduler.schedulers.blocking import BlockingScheduler
from warner import Warner
from archiver import Archiver
from announcer import Announcer
from flagger import Flagger
import os

sched = BlockingScheduler()

@sched.scheduled_job("cron", hour=4)
def destalinate_job():
    print("Destalinating")
    if "SB_TOKEN" not in os.environ or "API_TOKEN" not in os.environ:
        print "ERR: Missing at least one Slack environment variable."
    else:
        warner = Warner()
        archiver = Archiver()
        announcer = Announcer()
        flagger = Flagger()
        print("Warning")
        warner.warn()
        print("Archiving")
        archiver.archive()
        print("Announcing")
        announcer.announce()
        print("Flagging")
        flagger.flag()
        print("OK: destalinated")
    print("END: destalinate_job")

sched.start()
<|endoftext|>