Commit eab9051d authored by David Hendriks's avatar David Hendriks
Browse files

added tests for grid_options_defaults and blacked formatted

parent 5349929a
Loading
Loading
Loading
Loading
+2 −1
Original line number Diff line number Diff line
@@ -11,6 +11,7 @@ from binarycpython.tests.test_plot_functions import *
from binarycpython.tests.test_run_system_wrapper import *
from binarycpython.tests.test_spacing_functions import *
from binarycpython.tests.test_useful_funcs import *
from binarycpython.tests.test_grid_options_defaults import *

if __name__ == '__main__':
if __name__ == "__main__":
    unittest.main()
+62 −25
Original line number Diff line number Diff line
@@ -61,6 +61,7 @@ ensemble_filters_off {8} ensemble_filter_{9} 1 probability 0.1"
### General run_system test
#######################################################################################################################################################


class test_run_system(unittest.TestCase):
    """
    Unit test for run_system
@@ -86,12 +87,18 @@ class test_run_system(unittest.TestCase):

        output = _binary_c_bindings.run_system(argstring=argstring)

        self.assertIn("SINGLE_STAR_LIFETIME", output, msg="Output didn't contain SINGLE_STAR_LIFETIME")
        self.assertIn(
            "SINGLE_STAR_LIFETIME",
            output,
            msg="Output didn't contain SINGLE_STAR_LIFETIME",
        )


#######################################################################################################################################################
### memaddr test
#######################################################################################################################################################


class test_return_store_memaddr(unittest.TestCase):
    """
    Unit test for return_store_memaddr
@@ -114,8 +121,8 @@ class test_return_store_memaddr(unittest.TestCase):
### ensemble tests
#######################################################################################################################################################

class TestEnsemble(unittest.TestCase):

class TestEnsemble(unittest.TestCase):
    def test_minimal_ensemble_output(self):
        """
        Tase case to check if the ensemble output is correctly written to the buffer instead of printed
@@ -146,7 +153,10 @@ class TestEnsemble(unittest.TestCase):
        # print(test_json.keys())
        # print(test_json)

        self.assertIsNotNone(test_json, msg="Ensemble output not correctly written passed to the buffer in _binary_c_bindings")
        self.assertIsNotNone(
            test_json,
            msg="Ensemble output not correctly written passed to the buffer in _binary_c_bindings",
        )
        self.assertIn("number_counts", test_json.keys())

    def test_return_persistent_data_memaddr(self):
@@ -161,8 +171,9 @@ class TestEnsemble(unittest.TestCase):
        print(textwrap.indent(str(output), "\t"))

        self.assertIsInstance(output, int, msg="memory adress has to be an integer")
        self.assertNotEqual(output, 0, "memory adress seems not to have a correct value")

        self.assertNotEqual(
            output, 0, "memory adress seems not to have a correct value"
        )

    def test_passing_persistent_data_to_run_system(self):
        # Function to test the passing of the persistent data memoery adress, and having ensemble_defer = True
@@ -186,7 +197,8 @@ class TestEnsemble(unittest.TestCase):

        # Doing 2 systems in a row.
        output_1_deferred = _binary_c_bindings.run_system(
            argstring=argstring_1_deferred, persistent_data_memaddr=persistent_data_memaddr
            argstring=argstring_1_deferred,
            persistent_data_memaddr=persistent_data_memaddr,
        )
        output_2 = _binary_c_bindings.run_system(
            argstring=argstring_2, persistent_data_memaddr=persistent_data_memaddr
@@ -201,14 +213,24 @@ class TestEnsemble(unittest.TestCase):
        # Doing system one again.
        output_1_again = _binary_c_bindings.run_system(argstring=argstring_1)
        ensemble_jsons_1 = [
            line for line in output_1_again.splitlines() if line.startswith("ENSEMBLE_JSON")
            line
            for line in output_1_again.splitlines()
            if line.startswith("ENSEMBLE_JSON")
        ]
        json_1_again = handle_ensemble_string_to_json(
            ensemble_jsons_1[0][len("ENSEMBLE_JSON ") :]
        )

        self.assertEqual(json_1, json_1_again, msg="The system with the same initial settings did not give the same output")
        self.assertNotEqual(json_1, json_2, msg="The output of the deferred two systems should not be the same as the first undeferred output")
        self.assertEqual(
            json_1,
            json_1_again,
            msg="The system with the same initial settings did not give the same output",
        )
        self.assertNotEqual(
            json_1,
            json_2,
            msg="The output of the deferred two systems should not be the same as the first undeferred output",
        )

    def test_adding_ensemble_output(self):
        """
@@ -258,7 +280,9 @@ class TestEnsemble(unittest.TestCase):
            file.write(json.dumps(test_1_json_1, indent=4))
        with open(os.path.join(TMP_DIR, "test", "adding_json_2.json"), "w") as file:
            file.write(json.dumps(test_1_json_2, indent=4))
        with open(os.path.join(TMP_DIR, "test", "adding_json_merged.json"), "w") as file:
        with open(
            os.path.join(TMP_DIR, "test", "adding_json_merged.json"), "w"
        ) as file:
            file.write(json.dumps(test_1_json_2, indent=4))

        print("Single runs done\n")
@@ -280,7 +304,9 @@ class TestEnsemble(unittest.TestCase):
        )

        # Get a memory location
        test_2_persistent_data_memaddr = _binary_c_bindings.return_persistent_data_memaddr()
        test_2_persistent_data_memaddr = (
            _binary_c_bindings.return_persistent_data_memaddr()
        )

        # Run the systems and defer the output each time
        _ = _binary_c_bindings.run_system(
@@ -299,13 +325,17 @@ class TestEnsemble(unittest.TestCase):
            )
        )
        test_2_ensemble_json = [
            line for line in test_2_output.splitlines() if line.startswith("ENSEMBLE_JSON")
            line
            for line in test_2_output.splitlines()
            if line.startswith("ENSEMBLE_JSON")
        ]
        test_2_json = handle_ensemble_string_to_json(
            test_2_ensemble_json[0][len("ENSEMBLE_JSON ") :]
        )

        with open(os.path.join(TMP_DIR, "test", "adding_json_deferred.json"), "w") as file:
        with open(
            os.path.join(TMP_DIR, "test", "adding_json_deferred.json"), "w"
        ) as file:
            file.write(json.dumps(test_2_json, indent=4))

        print("Double deferred done\n")
@@ -315,7 +345,9 @@ class TestEnsemble(unittest.TestCase):
        # Then the second one uses that memory to combine its results with, but doesn't defer the
        # data after that, so it will print it after the second run is done

        test_3_persistent_data_memaddr = _binary_c_bindings.return_persistent_data_memaddr()
        test_3_persistent_data_memaddr = (
            _binary_c_bindings.return_persistent_data_memaddr()
        )

        # Run the systems and defer the output once and the second time not, so that the second run
        # automatically prints out the results
@@ -324,7 +356,8 @@ class TestEnsemble(unittest.TestCase):
            persistent_data_memaddr=test_3_persistent_data_memaddr,
        )
        test_3_output_2 = _binary_c_bindings.run_system(
            argstring=argstring_2, persistent_data_memaddr=test_3_persistent_data_memaddr
            argstring=argstring_2,
            persistent_data_memaddr=test_3_persistent_data_memaddr,
        )
        test_3_ensemble_jsons = [
            line
@@ -357,10 +390,13 @@ class TestEnsemble(unittest.TestCase):

        # TODO: add more asserts.
        #
        self.assertEqual(inspect_dict(test_1_merged_dict, print_structure=False), inspect_dict(test_2_json, print_structure=False), msg=assert_message_1)
        self.assertEqual(
            inspect_dict(test_1_merged_dict, print_structure=False),
            inspect_dict(test_2_json, print_structure=False),
            msg=assert_message_1,
        )
        # assert inspect_dict(test_1_merged_dict, print_structure=False) == inspect_dict(test_3_json, print_structure=False), assert_message_2


    def test_free_and_json_output(self):
        """
        Function that tests the freeing of the memory adress and the output of the json
@@ -394,7 +430,11 @@ class TestEnsemble(unittest.TestCase):
            json_output_by_freeing.splitlines()[0][len("ENSEMBLE_JSON ") :],
        )

        self.assertIn("number_counts", parsed_json.keys(), msg="Output not correct. 'number_counts' not part of the keys")
        self.assertIn(
            "number_counts",
            parsed_json.keys(),
            msg="Output not correct. 'number_counts' not part of the keys",
        )

    def test_combine_with_empty_json(self):
        """
@@ -410,9 +450,7 @@ class TestEnsemble(unittest.TestCase):
            ensemble_jsons_1[0][len("ENSEMBLE_JSON ") :]
        )

        assert_message = (
            "combining output json with empty dict should give same result as initial json"
        )
        assert_message = "combining output json with empty dict should give same result as initial json"

        self.assertEqual(merge_dicts(json_1, {}), json_1, assert_message)

@@ -434,7 +472,6 @@ class TestEnsemble(unittest.TestCase):
            ensemble_jsons_1[0][len("ENSEMBLE_JSON ") :]
        )

        
        keys = json_1.keys()

        # assert statements:
@@ -471,5 +508,5 @@ def all():
#     all()
#     print("Done")

if __name__ == '__main__':
if __name__ == "__main__":
    unittest.main()
+55 −24
Original line number Diff line number Diff line
@@ -4,6 +4,7 @@ from binarycpython.utils.custom_logging_functions import *

binary_c_temp_dir = temp_dir()


class test_custom_logging(unittest.TestCase):
    """
    Unit test for the custom_logging module
@@ -12,39 +13,62 @@ class test_custom_logging(unittest.TestCase):
    def test_autogen_C_logging_code(self):

        input_dict_1 = None
        output_1 = autogen_C_logging_code(input_dict_1)
        output_1 = autogen_C_logging_code(input_dict_1, verbose=1)
        self.assertEqual(output_1, None, msg="Error. return value should be None")

        input_dict_2 = {'MY_STELLAR_DATA': ['model.time','star[0].mass', 'model.probability', 'model.dt']}
        output_2 = autogen_C_logging_code(input_dict_2)
        input_dict_2 = {
            "MY_STELLAR_DATA": [
                "model.time",
                "star[0].mass",
                "model.probability",
                "model.dt",
            ]
        }
        output_2 = autogen_C_logging_code(input_dict_2, verbose=1)

        test_output_2 = 'Printf("MY_STELLAR_DATA %g %g %g %g\\n",((double)stardata->model.time),((double)stardata->star[0].mass),((double)stardata->model.probability),((double)stardata->model.dt));'
        self.assertEqual(output_2, test_output_2, msg="Output doesnt match the test_output_2")
        self.assertEqual(
            output_2, test_output_2, msg="Output doesnt match the test_output_2"
        )

        input_dict_3 = {'MY_STELLAR_DATA': 2}
        output_3 = autogen_C_logging_code(input_dict_3)
        input_dict_3 = {"MY_STELLAR_DATA": 2}
        output_3 = autogen_C_logging_code(input_dict_3, verbose=1)
        self.assertEqual(output_3, None, msg="Output should be None")

    def test_binary_c_log_code(self):
        input_1 = "None"
        output_1 = binary_c_log_code(input_1)
        output_1 = binary_c_log_code(input_1, verbose=1)
        self.assertEqual(output_1, None, msg="Output should be None")

        input_2 = 'Printf("MY_STELLAR_DATA %g %g %g %g\\n",((double)stardata->model.time),((double)stardata->star[0].mass),((double)stardata->model.probability),((double)stardata->model.dt));'
        output_2 = binary_c_log_code(input_2)
        output_2 = binary_c_log_code(input_2, verbose=1)
        test_value_2 = '#pragma push_macro("MAX")\n#pragma push_macro("MIN")\n#undef MAX\n#undef MIN\n#include "binary_c.h"\n#include "RLOF/RLOF_prototypes.h"\n\n// add visibility __attribute__ ((visibility ("default"))) to it \nvoid binary_c_API_function custom_output_function(struct stardata_t * stardata);\nvoid binary_c_API_function custom_output_function(struct stardata_t * stardata)\n{\n    // struct stardata_t * stardata = (struct stardata_t *)x;\n    Printf("MY_STELLAR_DATA %g %g %g %g\\n",((double)stardata->model.time),((double)stardata->star[0].mass),((double)stardata->model.probability),((double)stardata->model.dt));;\n}\n\n#undef MAX \n#undef MIN\n#pragma pop_macro("MIN")\n#pragma pop_macro("MAX")    '
        self.assertEqual(output_2, test_value_2, msg="Output does not match what it should be: {}".format(test_value_2))
        self.assertEqual(
            output_2,
            test_value_2,
            msg="Output does not match what it should be: {}".format(test_value_2),
        )

    def test_binary_c_write_log_code(self):
        input_1 = '#pragma push_macro("MAX")\n#pragma push_macro("MIN")\n#undef MAX\n#undef MIN\n#include "binary_c.h"\n#include "RLOF/RLOF_prototypes.h"\n\n// add visibility __attribute__ ((visibility ("default"))) to it \nvoid binary_c_API_function custom_output_function(struct stardata_t * stardata);\nvoid binary_c_API_function custom_output_function(struct stardata_t * stardata)\n{\n    // struct stardata_t * stardata = (struct stardata_t *)x;\n    Printf("MY_STELLAR_DATA %g %g %g %g\\n",((double)stardata->model.time),((double)stardata->star[0].mass),((double)stardata->model.probability),((double)stardata->model.dt));;\n}\n\n#undef MAX \n#undef MIN\n#pragma pop_macro("MIN")\n#pragma pop_macro("MAX")    '
        binary_c_write_log_code(input_1, os.path.join(binary_c_temp_dir, 'test_binary_c_write_log_code.txt'))

        self.assertTrue(os.path.isfile(os.path.join(binary_c_temp_dir, 'test_binary_c_write_log_code.txt')), msg="File not created")
        with open(os.path.join(binary_c_temp_dir, 'test_binary_c_write_log_code.txt')) as f:
        binary_c_write_log_code(
            input_1,
            os.path.join(binary_c_temp_dir, "test_binary_c_write_log_code.txt"),
            verbose=1,
        )

        self.assertTrue(
            os.path.isfile(
                os.path.join(binary_c_temp_dir, "test_binary_c_write_log_code.txt")
            ),
            msg="File not created",
        )
        with open(
            os.path.join(binary_c_temp_dir, "test_binary_c_write_log_code.txt")
        ) as f:
            content_file = repr(f.read())
        self.assertEqual(repr(input_1), content_file, msg="Contents are not similar")


    def test_from_binary_c_config(self):
        # not going to test everything here, just the version and any output at all

@@ -52,11 +76,14 @@ class test_custom_logging(unittest.TestCase):
        if BINARY_C_DIR:
            BINARY_C_CONFIG = os.path.join(BINARY_C_DIR, "binary_c-config")

        self.assertTrue(os.path.isfile(BINARY_C_CONFIG), msg="{} doesn't exist".format(BINARY_C_CONFIG))
        self.assertTrue(
            os.path.isfile(BINARY_C_CONFIG),
            msg="{} doesn't exist".format(BINARY_C_CONFIG),
        )

        input_1 = 'aa'
        input_1 = "aa"
        output_1 = from_binary_c_config(BINARY_C_CONFIG, input_1)
        self.assertTrue(output_1.startswith('Usage'))
        self.assertTrue(output_1.startswith("Usage"))

        input_2 = "version"
        output_2 = from_binary_c_config(BINARY_C_CONFIG, input_2)
@@ -66,7 +93,7 @@ class test_custom_logging(unittest.TestCase):
        # Just going to check whether the dictionary has the components it needs
        # TODO: check whether we need to make this better

        output = return_compilation_dict(verbose=-1)
        output = return_compilation_dict(verbose=1)

        self.assertTrue("cc" in output)
        self.assertTrue("ld" in output)
@@ -77,11 +104,15 @@ class test_custom_logging(unittest.TestCase):
    def test_create_and_load_logging_function(self):
        #
        input_1 = '#pragma push_macro("MAX")\n#pragma push_macro("MIN")\n#undef MAX\n#undef MIN\n#include "binary_c.h"\n#include "RLOF/RLOF_prototypes.h"\n\n// add visibility __attribute__ ((visibility ("default"))) to it \nvoid binary_c_API_function custom_output_function(struct stardata_t * stardata);\nvoid binary_c_API_function custom_output_function(struct stardata_t * stardata)\n{\n    // struct stardata_t * stardata = (struct stardata_t *)x;\n    Printf("MY_STELLAR_DATA %g %g %g %g\\n",((double)stardata->model.time),((double)stardata->star[0].mass),((double)stardata->model.probability),((double)stardata->model.dt));;\n}\n\n#undef MAX \n#undef MIN\n#pragma pop_macro("MIN")\n#pragma pop_macro("MAX")    '
        output_1 = create_and_load_logging_function(input_1, verbose=-1)
        output_1 = create_and_load_logging_function(input_1, verbose=1)

        self.assertTrue(isinstance(output_1[0], int), msg="memaddr is not an int")
        self.assertTrue(output_1[0] > 0, msg="memaddr is an int but not set correctly")
        self.assertTrue(
            "libcustom_logging" in output_1[1],
            msg="Name of the libcustom_logging not correct",
        )

        self.assertTrue(isinstance(output_1[0], int), msg='memaddr is not an int')
        self.assertTrue(output_1[0] > 0, msg='memaddr is an int but not set correctly')
        self.assertTrue('libcustom_logging' in output_1[1], msg='Name of the libcustom_logging not correct')

if __name__ == "__main__":
    unittest.main()
+339 −29

File changed.

Preview size limit exceeded, changes collapsed.

+7 −21
Original line number Diff line number Diff line
@@ -26,6 +26,7 @@ class test_get_help_super(unittest.TestCase):
        self.assertIn("algorithms", get_help_super_keys, "missing section")
        self.assertIn("misc", get_help_super_keys, "missing section")


class test_get_help_all(unittest.TestCase):
    """
    Unit test for get_help_all
@@ -39,7 +40,6 @@ class test_get_help_all(unittest.TestCase):
        get_help_all_output = get_help_all(print_help=False)
        get_help_all_keys = get_help_all_output.keys()


        self.assertIn("stars", get_help_all_keys, "missing section")
        self.assertIn("binary", get_help_all_keys, "missing section")
        self.assertIn("nucsyn", get_help_all_keys, "missing section")
@@ -55,25 +55,11 @@ class test_get_help(unittest.TestCase):
        Function to test the get_help function
        """

        self.assertEqual(get_help("M_1", print_help=False)["parameter_name"], "M_1", msg="get_help('M_1') should return the correct parameter name")


















        self.assertEqual(
            get_help("M_1", print_help=False)["parameter_name"],
            "M_1",
            msg="get_help('M_1') should return the correct parameter name",
        )


def all():
@@ -82,5 +68,5 @@ def all():
    test_get_help_super()


if __name__ == '__main__':
if __name__ == "__main__":
    unittest.main()
Loading