<commit_before>#!/usr/bin/env python
#
# Usage:
#   run from shell, or
#   % python <this_file.py>
# You may need to put EXOSIMS in your $PYTHONPATH, e.g.,
#   % PYTHONPATH=/path/to/exomissionsim <this_file.py>

r"""SurveySimulation module unit tests

<NAME>, JPL, Apr. 2016
"""

import sys
import os
import unittest
import StringIO
import json
from collections import namedtuple
from EXOSIMS.Prototypes.SurveySimulation import SurveySimulation
import numpy as np
import astropy.units as u
from astropy.time import Time
from tests.TestSupport.Info import resource_path
from tests.TestSupport.Utilities import RedirectStreams

SimpleScript = resource_path('test-scripts/simplest.json')

class TestSurveySimulationMethods(unittest.TestCase):
    r"""Test SurveySimulation class."""
    dev_null = open(os.devnull, 'w')

    required_modules = [
            'BackgroundSources', 'Completeness', 'Observatory', 'OpticalSystem',
            'PlanetPhysicalModel', 'PlanetPopulation', 'PostProcessing', 
            'SimulatedUniverse', 'TargetList', 'TimeKeeping', 'ZodiacalLight' ]

    def setUp(self):
        # print '[setup] ',
        self.fixture = SurveySimulation

    def tearDown(self):
        del self.fixture


    def test_str(self):
        r"""Test __str__ method, for full coverage."""
        with RedirectStreams(stdout=self.dev_null):
            sim = self.fixture(SimpleScript)
        # replace stdout and keep a reference
        original_stdout = sys.stdout
        sys.stdout = StringIO.StringIO()
        # call __str__ method
        result = sim.__str__()
        # examine what was printed
        contents = sys.stdout.getvalue()
        self.assertEqual(type(contents), type(''))
        self.assertIn('DRM', contents)
        sys.stdout.close()
        # it also returns a string, which is not necessary
        self.assertEqual(type(result), type(''))
        # put stdout back
        sys.stdout = original_stdout


    def test_choose_next_target(self):
        r"""Test choose_next_target method.

        Approach: Ensure the next target has max completeness as required in prototype
        """
        with RedirectStreams(stdout=self.dev_null):
            sim = self.fixture(SimpleScript)
        
        #to make this non-trivial, overwrite comp0 with random values:
        comprand = np.random.rand(sim.TargetList.nStars)
        sim.TargetList.comp0 = comprand.copy()<commit_msg>adding surveysim prototype init edge case tests<commit_after>#!/usr/bin/env python
#
# Usage:
#   run from shell, or
#   % python <this_file.py>
# You may need to put EXOSIMS in your $PYTHONPATH, e.g.,
#   % PYTHONPATH=/path/to/exomissionsim <this_file.py>

r"""SurveySimulation module unit tests

<NAME>, JPL, Apr. 2016
"""

import sys
import os
import unittest
import StringIO
import json
from collections import namedtuple
from EXOSIMS.Prototypes.SurveySimulation import SurveySimulation
import numpy as np
import astropy.units as u
from astropy.time import Time
from tests.TestSupport.Info import resource_path
from tests.TestSupport.Utilities import RedirectStreams

SimpleScript = resource_path('test-scripts/simplest.json')
ErrorScript = resource_path('test-scripts/simplest-error.json')

class TestSurveySimulationMethods(unittest.TestCase):
    r"""Test SurveySimulation class."""
    dev_null = open(os.devnull, 'w')

    required_modules = [
            'BackgroundSources', 'Completeness', 'Observatory', 'OpticalSystem',
            'PlanetPhysicalModel', 'PlanetPopulation', 'PostProcessing', 
            'SimulatedUniverse', 'TargetList', 'TimeKeeping', 'ZodiacalLight' ]

    def setUp(self):
        # print '[setup] ',
        self.fixture = SurveySimulation

    def tearDown(self):
        del self.fixture


    def test_str(self):
        r"""Test __str__ method, for full coverage."""
        with RedirectStreams(stdout=self.dev_null):
            sim = self.fixture(SimpleScript)
        # replace stdout and keep a reference
        original_stdout = sys.stdout
        sys.stdout = StringIO.StringIO()
        # call __str__ method
        result = sim.__str__()
        # examine what was printed
        contents = sys.stdout.getvalue()
        self.assertEqual(type(contents), type(''))
        self.assertIn('DRM', contents)
        sys.stdout.close()
        # it also returns a string, which is not necessary
        self.assertEqual(type(result), type(''))
        # put stdout back
        sys.stdout = original_stdout

    def test_init_fail(self):
        r"""Test of initialization and __init__ -- failure.
        """
        with RedirectStreams(stdout=self.dev_null):
            with self.assertRaises(ValueError):
                sim = self.fixture(ErrorScript)
            
    def test_init_specs(self):
        r"""Test of initialization and __init__ -- specs dictionary.
        """
        script = open(SimpleScript).read()
        specs = json.loads(script)
        with RedirectStreams(stdout=self.dev_null):
            sim = self.fixture(scriptfile=None, **specs)
        
        for rmod in self.required_modules:
            self.assertIn(rmod, sim.__dict__)
            self.assertEqual(getattr(sim,rmod)._modtype,rmod)
            
    def test_init_file_no_file(self):
        r"""Test __init__ file handling -- various non-existent input files.
        """
        bad_files = ['/dev/null', '/tmp/this/file/is/not/there.json', '/tmp/this_file_is_not_there.json']
        for bad_file in bad_files:
            with self.assertRaises(AssertionError):
                sim = self.fixture(bad_file)
            
    def test_init_file_none(self):
        r"""Test __init__ file handling -- incomplete specs.
        
        Note that None is different than a non-existent file.
        """
        with self.assertRaises(KeyError):
            sim = self.fixture(None)


    def test_choose_next_target(self):
        r"""Test choose_next_target method.

        Approach: Ensure the next target has max completeness as required in prototype
        """
        with RedirectStreams(stdout=self.dev_null):
            sim = self.fixture(SimpleScript)
        
        #to make this non-trivial, overwrite comp0 with random values:
        comprand = np.random.rand(sim.TargetList.nStars)
        sim.TargetList.comp0 = comprand.copy()
{'fraction_non_alphanumeric': 0.09961989230281913, 'fraction_numerical': 0.0019005384859043396, 'mean_word_length': 2.8042168674698793, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6020915', 'n_tokens_mistral': 1857, 'n_tokens_neox': 1806, 'n_words': 463}