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

from argparse import Namespace
import os

from mock import (
    patch,
    )

from assess_multimodel import (
    check_services,
    env_token,
    hosted_environment,
    multimodel_setup,
    )
from fakejuju import fake_juju_client
from jujupy import (
    EnvJujuClient25,
    JUJU_DEV_FEATURE_FLAGS,
    SimpleEnvironment,
    )
import tests

def patch_local(target, **kwargs):
    return patch('assess_multimodel.' + target, **kwargs)

class TestMultiModel(tests.FakeHomeTestCase):

    client_class = EnvJujuClient25

    @patch_local('get_random_string', autospec=True)
    @patch('jujupy.SimpleEnvironment.from_config', autospec=True)
    def mock_client(self, from_config_func, get_random_string_func):
        from_config_func.return_value = SimpleEnvironment('baz', {})
        get_random_string_func.return_value = 'fakeran'
        client = self.client_class(
            SimpleEnvironment.from_config('baz'),
            '1.25-foobar', 'path')
        return client

    def test_env_token(self):
        with patch_local('get_random_string', return_value='fakeran'):
            self.assertEqual(env_token('env1'), 'env1fakeran')

    def test_set_jes_flag(self):
        client = self.mock_client()
        env = client._shell_environ()
        self.assertNotIn('jes', env.get(JUJU_DEV_FEATURE_FLAGS, '').split(","))

    @patch_local('print_now', autospec=True)
    @patch_local('get_random_string', autospec=True)
    @patch('jujupy.EnvJujuClient.juju', autospec=True)
    @patch_local('check_token', autospec=True)
    def test_check_services(
            self,
            check_token_func,
            juju_func,
            get_random_string_func,
            print_now_func):
        get_random_string_func.return_value = 'fakeran'

        client = self.mock_client()
        client.env.environment = 'token'
        check_services(client)

        juju_func.assert_called_once_with(
            client, 'set', ('dummy-source', 'token=tokenfakeran'))
        check_token_func.assert_called_once_with(client, 'tokenfakeran')
        print_now_func.assert_called_once_with('checking services in token')

    @patch('jujupy.EnvJujuClient.get_full_path', autospec=True)
    @patch('jujupy.EnvJujuClient.add_ssh_machines', autospec=True)
    @patch_local('boot_context', autospec=True)
    @patch_local('configure_logging', autospec=True)
    @patch_local('client_from_config', autospec=True)
    def test_multimodel_setup(
            self,
            by_version_func,
            configure_logging_func,
            boot_context_func,
            add_ssh_machines_func,
            get_full_path_func):
        # patch helper funcs
        expected_client = self.mock_client()
        by_version_func.return_value = expected_client
        configure_logging_func.return_value = None
        get_full_path_func.return_value = '/path/to/juju'

        setup_args = Namespace(
            env='baz', verbose=True, temp_env_name='jesjob',
            bootstrap_host='localhost', debug=True, machine=['0'],
            series='trusty', agent_stream='devel', agent_url='some_url',
            logs='log/dir', keep_env=True, juju_home='/path/to/juju/home',
            juju_bin='/path/to/bin/juju', region='region-foo', deadline=None)

        # setup jes with a client that has default jes.
        with patch.object(expected_client, 'enable_jes'):
            with patch.object(expected_client, 'is_jes_enabled',
                              return_value=True):
                with multimodel_setup(setup_args) as (
                        client, charm_series, base_env):
                    self.assertEqual(1, client.is_jes_enabled.call_count)
                    self.assertEqual(0, client.enable_jes.call_count)

        # assert that jes_setup provides expected values
        self.assertIs(client, expected_client)
        self.assertEqual(charm_series, 'trusty')
        self.assertEqual(base_env, 'baz')

        # assert that helper funcs were called with expected args.
        by_version_func.assert_called_once_with(
            'baz', '/path/to/bin/juju', True, soft_deadline=None)

        configure_logging_func.assert_called_once_with(True)
        boot_context_func.assert_called_once_with(
            'jesjob', expected_client, 'localhost', ['0'], 'trusty',
            'some_url', 'devel', 'log/dir', True, upload_tools=False,
            region='region-foo')

        # Setup jes with a client that requires a call to enable_jes.
        with patch.object(expected_client, 'enable_jes'):
            with patch.object(expected_client, 'is_jes_enabled',
                              return_value=False):
                with multimodel_setup(setup_args) as (
                        client, charm_previx, base_env):
                    self.assertEqual(1, client.is_jes_enabled.call_count)
                    self.assertEqual(1, client.enable_jes.call_count)

class TestHostedEnvironment(tests.FakeHomeTestCase):

    def test_hosted_environment(self):
        hosting_client = fake_juju_client()
        log_dir = os.path.join(self.home_dir, 'logs')
        os.mkdir(log_dir)
        with hosted_environment(hosting_client, log_dir, 'bar') as client:
            models = client._backend.controller_state.models
            model_state = models[client.model_name]
            self.assertEqual({'name-bar': model_state},
                             hosting_client._backend.controller_state.models)
            self.assertEqual('created', model_state.state)
        self.assertEqual('model-destroyed', model_state.state)
        self.assertTrue(os.path.isdir(os.path.join(log_dir, 'bar')))

    def test_gathers_machine_logs(self):
        hosting_client = fake_juju_client()
        log_dir = os.path.join(self.home_dir, 'logs')
        os.mkdir(log_dir)
        with patch("deploy_stack.copy_remote_logs", autospec=True) as mock_crl:
            with hosted_environment(hosting_client, log_dir, 'bar') as client:
                client.juju("deploy", ["cs:a-application"])
                status = client.get_status()
                unit_machine = status.get_unit("a-application/0")["machine"]
                addr = status.status["machines"][unit_machine]["dns-name"]
        hosted_dir = os.path.join(log_dir, "bar")
        machine_dir = os.path.join(hosted_dir, "machine-0")
        self.assertTrue(os.path.isdir(hosted_dir))
        self.assertTrue(os.path.isdir(machine_dir))
        self.assertEqual(mock_crl.call_count, 1)
        self.assertEqual(mock_crl.call_args[0][0].address, addr)
        self.assertEqual(mock_crl.call_args[0][1], machine_dir)
<commit_msg>Woops.<commit_after>#!/usr/bin/env python

from argparse import Namespace
import os

from mock import (
    patch,
    )

from assess_multimodel import (
    check_services,
    env_token,
    hosted_environment,
    multimodel_setup,
    )
from fakejuju import fake_juju_client
from jujupy import (
    EnvJujuClient25,
    JUJU_DEV_FEATURE_FLAGS,
    SimpleEnvironment,
    )
import tests

def patch_local(target, **kwargs):
    return patch('assess_multimodel.' + target, **kwargs)

class TestMultiModel(tests.FakeHomeTestCase):

    client_class = EnvJujuClient25

    @patch_local('get_random_string', autospec=True)
    @patch('jujupy.SimpleEnvironment.from_config')
    def mock_client(self, from_config_func, get_random_string_func):
        from_config_func.return_value = SimpleEnvironment('baz', {})
        get_random_string_func.return_value = 'fakeran'
        client = self.client_class(
            SimpleEnvironment.from_config('baz'),
            '1.25-foobar', 'path')
        return client

    def test_env_token(self):
        with patch_local('get_random_string', return_value='fakeran'):
            self.assertEqual(env_token('env1'), 'env1fakeran')

    def test_set_jes_flag(self):
        client = self.mock_client()
        env = client._shell_environ()
        self.assertNotIn('jes', env.get(JUJU_DEV_FEATURE_FLAGS, '').split(","))

    @patch_local('print_now', autospec=True)
    @patch_local('get_random_string', autospec=True)
    @patch('jujupy.EnvJujuClient.juju', autospec=True)
    @patch_local('check_token', autospec=True)
    def test_check_services(
            self,
            check_token_func,
            juju_func,
            get_random_string_func,
            print_now_func):
        get_random_string_func.return_value = 'fakeran'

        client = self.mock_client()
        client.env.environment = 'token'
        check_services(client)

        juju_func.assert_called_once_with(
            client, 'set', ('dummy-source', 'token=tokenfakeran'))
        check_token_func.assert_called_once_with(client, 'tokenfakeran')
        print_now_func.assert_called_once_with('checking services in token')

    @patch('jujupy.EnvJujuClient.get_full_path', autospec=True)
    @patch('jujupy.EnvJujuClient.add_ssh_machines', autospec=True)
    @patch_local('boot_context', autospec=True)
    @patch_local('configure_logging', autospec=True)
    @patch_local('client_from_config', autospec=True)
    def test_multimodel_setup(
            self,
            by_version_func,
            configure_logging_func,
            boot_context_func,
            add_ssh_machines_func,
            get_full_path_func):
        # patch helper funcs
        expected_client = self.mock_client()
        by_version_func.return_value = expected_client
        configure_logging_func.return_value = None
        get_full_path_func.return_value = '/path/to/juju'

        setup_args = Namespace(
            env='baz', verbose=True, temp_env_name='jesjob',
            bootstrap_host='localhost', debug=True, machine=['0'],
            series='trusty', agent_stream='devel', agent_url='some_url',
            logs='log/dir', keep_env=True, juju_home='/path/to/juju/home',
            juju_bin='/path/to/bin/juju', region='region-foo', deadline=None)

        # setup jes with a client that has default jes.
        with patch.object(expected_client, 'enable_jes'):
            with patch.object(expected_client, 'is_jes_enabled',
                              return_value=True):
                with multimodel_setup(setup_args) as (
                        client, charm_series, base_env):
                    self.assertEqual(1, client.is_jes_enabled.call_count)
                    self.assertEqual(0, client.enable_jes.call_count)

        # assert that jes_setup provides expected values
        self.assertIs(client, expected_client)
        self.assertEqual(charm_series, 'trusty')
        self.assertEqual(base_env, 'baz')

        # assert that helper funcs were called with expected args.
        by_version_func.assert_called_once_with(
            'baz', '/path/to/bin/juju', True, soft_deadline=None)

        configure_logging_func.assert_called_once_with(True)
        boot_context_func.assert_called_once_with(
            'jesjob', expected_client, 'localhost', ['0'], 'trusty',
            'some_url', 'devel', 'log/dir', True, upload_tools=False,
            region='region-foo')

        # Setup jes with a client that requires a call to enable_jes.
        with patch.object(expected_client, 'enable_jes'):
            with patch.object(expected_client, 'is_jes_enabled',
                              return_value=False):
                with multimodel_setup(setup_args) as (
                        client, charm_previx, base_env):
                    self.assertEqual(1, client.is_jes_enabled.call_count)
                    self.assertEqual(1, client.enable_jes.call_count)

class TestHostedEnvironment(tests.FakeHomeTestCase):

    def test_hosted_environment(self):
        hosting_client = fake_juju_client()
        log_dir = os.path.join(self.home_dir, 'logs')
        os.mkdir(log_dir)
        with hosted_environment(hosting_client, log_dir, 'bar') as client:
            models = client._backend.controller_state.models
            model_state = models[client.model_name]
            self.assertEqual({'name-bar': model_state},
                             hosting_client._backend.controller_state.models)
            self.assertEqual('created', model_state.state)
        self.assertEqual('model-destroyed', model_state.state)
        self.assertTrue(os.path.isdir(os.path.join(log_dir, 'bar')))

    def test_gathers_machine_logs(self):
        hosting_client = fake_juju_client()
        log_dir = os.path.join(self.home_dir, 'logs')
        os.mkdir(log_dir)
        with patch("deploy_stack.copy_remote_logs", autospec=True) as mock_crl:
            with hosted_environment(hosting_client, log_dir, 'bar') as client:
                client.juju("deploy", ["cs:a-application"])
                status = client.get_status()
                unit_machine = status.get_unit("a-application/0")["machine"]
                addr = status.status["machines"][unit_machine]["dns-name"]
        hosted_dir = os.path.join(log_dir, "bar")
        machine_dir = os.path.join(hosted_dir, "machine-0")
        self.assertTrue(os.path.isdir(hosted_dir))
        self.assertTrue(os.path.isdir(machine_dir))
        self.assertEqual(mock_crl.call_count, 1)
        self.assertEqual(mock_crl.call_args[0][0].address, addr)
        self.assertEqual(mock_crl.call_args[0][1], machine_dir)
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
"""
Created on Fri Jul 27 10:08:25 2018

@author: cdeline

Using pytest to create unit tests for bifacial_radiance.

to run unit tests, run pytest from the command line in the bifacial_radiance directory
to run coverage tests, run py.test --cov-report term-missing --cov=bifacial_radiance

"""

from bifacial_radiance import RadianceObj, SceneObj, AnalysisObj
import numpy as np
import pytest

# test the readepw on a dummy Boulder EPW file in the /tests/ directory
MET_FILENAME =  r'tests\USA_CO_Boulder.724699_TMY2.epw'
# also test a dummy TMY3 Denver file in /tests/
MET_FILENAME2 = r"tests\724666TYA.CSV"

def test_RadianceObj_set1axis():
    # test set1axis.  requires metdata for boulder.
    demo = RadianceObj()
    demo.readEPW(epwfile = MET_FILENAME)
    trackerdict = demo.set1axis()
    assert trackerdict[0]['count'] == 108
    assert trackerdict[45]['count'] == 823

def test_RadianceObj_fixed_tilt_end_to_end():
    # just run the demo example.  Rear irradiance fraction roughly 11.8% for 0.95m landscape panel
    # takes 12 seconds
    demo = RadianceObj()  # Create a RadianceObj 'object'
    demo.setGround(0.62) # input albedo number or material name like 'concrete'.  To see options, run this without any input.

    metdata = demo.readEPW(epwfile= MET_FILENAME) # read in the EPW weather data from above
    #metdata = demo.readTMY() # select a TMY file using graphical picker
    # Now we either choose a single time point, or use cumulativesky for the entire year.
    fullYear = False
    if fullYear:
        demo.genCumSky(demo.epwfile) # entire year.
    else:
        demo.gendaylit(metdata,4020)  # Noon, June 17th
    # create a scene using panels in landscape at 10 deg tilt, 1.5m pitch. 0.2 m ground clearance
    sceneDict = {'tilt':10,'pitch':1.5,'height':0.2,'orientation':'landscape'}
    demo.makeModule(name='simple_panel',x=0.95,y=1.59)
    scene = demo.makeScene('simple_panel',sceneDict, nMods = 10, nRows = 3) #makeScene creates a .rad file with 20 modules per row, 7 rows.
    octfile = demo.makeOct(demo.getfilelist())  # makeOct combines all of the ground, sky and object files into a .oct file.
    analysis = AnalysisObj(octfile, demo.name)  # return an analysis object including the scan dimensions for back irradiance
    analysis.analysis(octfile, demo.name, scene.frontscan, scene.backscan)  # compare the back vs front irradiance
    #assert np.round(np.mean(analysis.backRatio),decimals=2) == 0.12  # NOTE: this value is 0.11 when your module size is 1m, 0.12 when module size is 0.95m
    assert np.mean(analysis.backRatio) == pytest.approx(0.12, abs = 0.01)

def test_RadianceObj_high_azimuth_angle_end_to_end():
    # modify example for high azimuth angle to test different parts of makesceneNxR.  Rear irradiance fraction roughly 17.3% for 0.95m landscape panel
    # takes 14 seconds for sensorsy = 9, 11 seconds for sensorsy = 2
    demo = RadianceObj()  # Create a RadianceObj 'object'
    demo.setGround('white_EPDM') # input albedo number or material name like 'concrete'.  To see options, run this without any input.

    #metdata = demo.readEPW() # read in the EPW weather data from above
    metdata = demo.readTMY(MET_FILENAME2) # select a TMY file using graphical picker
    # Now we either choose a single time point, or use cumulativesky for the entire year.
    fullYear = False
    if fullYear:
        demo.genCumSky(demo.epwfile) # entire year.  # Don't know how to test this yet in pytest...
    else:
        demo.gendaylit(metdata,4020)  # Noon, June 17th
    # create a scene using panels in landscape at 10 deg tilt, 1.5m pitch. 0.2 m ground clearance
    sceneDict = {'tilt':10,'pitch':1.5,'height':0.2,'orientation':'landscape','azimuth':30}
    demo.makeModule(name='simple_panel',x=0.95,y=1.59)
    scene = demo.makeScene('simple_panel',sceneDict, nMods = 10, nRows = 3) #makeScene creates a .rad file with 20 modules per row, 7 rows.
    octfile = demo.makeOct(demo.getfilelist())  # makeOct combines all of the ground, sky and object files into a .oct file.
    analysis = AnalysisObj(octfile, demo.name)  # return an analysis object including the scan dimensions for back irradiance
    analysis.analysis(octfile, demo.name, scene.frontscan, scene.backscan)  # compare the back vs front irradiance
    #assert np.round(np.mean(analysis.backRatio),2) == 0.20  # bifi ratio was == 0.22 in v0.2.2
    assert np.mean(analysis.Wm2Front) == pytest.approx(912, rel = 0.005)
    assert np.mean(analysis.Wm2Back) == pytest.approx(182, rel = 0.01)

def test_RadianceObj_1axis_gendaylit_end_to_end():
    # 1-axis tracking end-to-end test with torque tube and gap generation.
    # Takes 20 seconds for 2-sensor scan
    module_height = 1.95 * 2 + 0.1  # module portrait dimension in meters
    gcr = 0.35   # ground cover ratio,  = module_height / pitch
    albedo = 0.3     # ground albedo
    hub_height = 2   # tracker height at 0 tilt in meters (hub height)

    demo = RadianceObj()  # Create a RadianceObj 'object'
    demo.setGround(albedo) # input albedo number or material name like 'concrete'.  To see options, run this without any input.
    metdata = demo.readEPW(MET_FILENAME) # read in the EPW weather data from above
    #metdata = demo.readTMY(MET_FILENAME2) # select a TMY file using graphical picker
    # create metdata files for each condition. keys are timestamps for gendaylit workflow
    trackerdict = demo.set1axis(cumulativesky = False)
    # create the skyfiles needed for 1-axis tracking
    demo.gendaylit1axis(metdata = metdata, enddate = '01/01')
    # test modules with gap and rear tube
    demo.makeModule(name='Longi_torquetube',x=0.984,y=1.95,torquetube = True, numpanels = 2, panelgap = 0.1)
    #demo.makeModule(name='Longi_torquetube',x=0.984,y=1.95)
    # set module type to be used and passed into makeScene1axis
    module_type = 'Longi_torquetube'

    # Create the scene for the 1-axis tracking
    sceneDict = {'pitch': module_height / gcr,'height':hub_height,'orientation':'portrait'}
    key = '01_01_11'
    demo.makeScene1axis({key:trackerdict[key]}, module_type,sceneDict, cumulativesky = False, nMods = 10, nRows = 3, modwanted = 3, rowwanted = 3, sensorsy = 2) #makeScene creates a .rad file with 20 modules per row, 7 rows.

    demo.makeOct1axis(trackerdict,key) # just run this for one timestep: Jan 1 11am
    demo.analysis1axis(trackerdict,key) # just run this for one timestep: Jan 1 11am

    assert(np.mean(demo.Wm2Front) == pytest.approx(214.0, 0.01) )
    assert(np.mean(demo.Wm2Back) == pytest.approx(40.0, 0.1) )

def test_SceneObj_makeSceneNxR_lowtilt():
    # test makeSceneNxR(tilt, height, pitch, orientation = None, azimuth = 180, nMods = 20, nRows = 7, radname = None)
    # default scene with simple_panel, 10 degree tilt, 0.2 height, 1.5 row spacing, landscape
    scene = SceneObj(moduletype = 'simple_panel')
    scene.makeSceneNxR(tilt=10,height=0.2,pitch=1.5,orientation = 'landscape')

    assert scene.frontscan.pop('orient') == '0 0 -1'
    assert scene.frontscan == pytest.approx({'Nx': 1, 'Ny': 9, 'Nz': 1,  'xinc': 0,  'yinc': 0.093556736536159757,
                              'xstart': 0,'ystart': 0.093556736536159757, 'zinc': 0, 'zstart': 1.3649657687835837})

    assert scene.backscan.pop('orient') == '0 0 1'
    assert scene.backscan == pytest.approx({'Nx': 1, 'Ny': 9, 'Nz': 1,  'xinc': 0, 'yinc': 0.093556736536159757,
                              'xstart': 0,  'ystart': 0.093556736536159757, 'zinc': 0.016496576878358378,
                              'zstart': 0.18649657687835838}) # zstart was 0.01 and zinc was 0 in v0.2.2
    assert scene.text == '!xform -rz -90 -t -0.795 0.475 0 -rx 10 -t 0 0 0.2 -a 20 -t 1.6 0 0 -a 7 -t 0 1.5 0 -i 1 -t -15.9 -4.5 0 -rz 0 objects\\simple_panel.rad'

def test_SceneObj_makeSceneNxR_hightilt():
    # test makeSceneNxR(tilt, height, pitch, orientation = None, azimuth = 180, nMods = 20, nRows = 7, radname = None)
    # default scene with simple_panel, 50 degree tilt, 0.2 height, 1.5 row spacing, landscape
    scene = SceneObj(moduletype = 'simple_panel')

    scene.makeSceneNxR(tilt=65,height=0.2,pitch=1.5,azimuth=89,orientation = 'landscape')
    temp = scene.frontscan.pop('orient')
    assert [float(x) for x in temp.split(' ')] == pytest.approx([-0.999847695156, -0.0174524064373, 0])
    assert scene.frontscan == pytest.approx({'Nx': 1, 'Ny': 1, 'Nz': 9, 'xinc': 0, 'xstart': 0, 'yinc': 0,
                                'ystart': 0, 'zinc': 0.086099239768481745,'zstart': 0.28609923976848173})

    temp2 = scene.backscan.pop('orient')
    assert [float(x) for x in temp2.split(' ')] == pytest.approx([0.999847695156, 0.0174524064373, 0])
    assert scene.backscan == pytest.approx({'Nx': 1, 'Ny': 1, 'Nz': 9, 'xinc': 0, 'xstart': -0.94985531039857163,
                            'yinc': 0, 'ystart': -0.016579786115419416, 'zinc': 0.086099239768481745, 'zstart': 0.28609923976848173})
    assert scene.text == '!xform -rz -90 -t -0.795 0.475 0 -rx 65 -t 0 0 0.2 -a 20 -t 1.6 0 0 -a 7 -t 0 1.5 0 -i 1 -t -15.9 -4.5 0 -rz 91 objects\\simple_panel.rad'

def test_AnalysisObj_linePtsMake3D():
    # test linepts = linePtsMake3D(xstart,ystart,zstart,xinc,yinc,zinc,Nx,Ny,Nz,orient):
    analysis = AnalysisObj()
    linepts = analysis.linePtsMake3D(0,0,0,1,1,1,1,2,3,'0 1 0')
    assert linepts == '0 0 0 0 1 0 \r0 1 0 0 1 0 \r0 0 1 0 1 0 \r0 1 1 0 1 0 \r0 0 2 0 1 0 \r0 1 2 0 1 0 \r'

     <commit_msg>pytest relative imports<commit_after># -*- coding: utf-8 -*-
"""
Created on Fri Jul 27 10:08:25 2018

@author: cdeline

Using pytest to create unit tests for bifacial_radiance.

to run unit tests, run pytest from the command line in the bifacial_radiance directory
to run coverage tests, run py.test --cov-report term-missing --cov=bifacial_radiance

"""

#from bifacial_radiance import RadianceObj, SceneObj, AnalysisObj
import bifacial_radiance
import numpy as np
import pytest

# test the readepw on a dummy Boulder EPW file in the /tests/ directory
MET_FILENAME =  r'tests\USA_CO_Boulder.724699_TMY2.epw'
# also test a dummy TMY3 Denver file in /tests/
MET_FILENAME2 = r"tests\724666TYA.CSV"

def test_RadianceObj_set1axis():
    # test set1axis.  requires metdata for boulder.
    demo = bifacial_radiance.RadianceObj()
    demo.readEPW(epwfile = MET_FILENAME)
    trackerdict = demo.set1axis()
    assert trackerdict[0]['count'] == 108
    assert trackerdict[45]['count'] == 823

def test_RadianceObj_fixed_tilt_end_to_end():
    # just run the demo example.  Rear irradiance fraction roughly 11.8% for 0.95m landscape panel
    # takes 12 seconds
    demo = bifacial_radiance.RadianceObj()  # Create a RadianceObj 'object'
    demo.setGround(0.62) # input albedo number or material name like 'concrete'.  To see options, run this without any input.

    metdata = demo.readEPW(epwfile= MET_FILENAME) # read in the EPW weather data from above
    #metdata = demo.readTMY() # select a TMY file using graphical picker
    # Now we either choose a single time point, or use cumulativesky for the entire year.
    fullYear = False
    if fullYear:
        demo.genCumSky(demo.epwfile) # entire year.
    else:
        demo.gendaylit(metdata,4020)  # Noon, June 17th
    # create a scene using panels in landscape at 10 deg tilt, 1.5m pitch. 0.2 m ground clearance
    sceneDict = {'tilt':10,'pitch':1.5,'height':0.2,'orientation':'landscape'}
    demo.makeModule(name='simple_panel',x=0.95,y=1.59)
    scene = demo.makeScene('simple_panel',sceneDict, nMods = 10, nRows = 3) #makeScene creates a .rad file with 20 modules per row, 7 rows.
    octfile = demo.makeOct(demo.getfilelist())  # makeOct combines all of the ground, sky and object files into a .oct file.
    analysis = bifacial_radiance.AnalysisObj(octfile, demo.name)  # return an analysis object including the scan dimensions for back irradiance
    analysis.analysis(octfile, demo.name, scene.frontscan, scene.backscan)  # compare the back vs front irradiance
    #assert np.round(np.mean(analysis.backRatio),decimals=2) == 0.12  # NOTE: this value is 0.11 when your module size is 1m, 0.12 when module size is 0.95m
    assert np.mean(analysis.backRatio) == pytest.approx(0.12, abs = 0.01)

def test_RadianceObj_high_azimuth_angle_end_to_end():
    # modify example for high azimuth angle to test different parts of makesceneNxR.  Rear irradiance fraction roughly 17.3% for 0.95m landscape panel
    # takes 14 seconds for sensorsy = 9, 11 seconds for sensorsy = 2
    demo = bifacial_radiance.RadianceObj()  # Create a RadianceObj 'object'
    demo.setGround('white_EPDM') # input albedo number or material name like 'concrete'.  To see options, run this without any input.

    #metdata = demo.readEPW() # read in the EPW weather data from above
    metdata = demo.readTMY(MET_FILENAME2) # select a TMY file using graphical picker
    # Now we either choose a single time point, or use cumulativesky for the entire year.
    fullYear = False
    if fullYear:
        demo.genCumSky(demo.epwfile) # entire year.  # Don't know how to test this yet in pytest...
    else:
        demo.gendaylit(metdata,4020)  # Noon, June 17th
    # create a scene using panels in landscape at 10 deg tilt, 1.5m pitch. 0.2 m ground clearance
    sceneDict = {'tilt':10,'pitch':1.5,'height':0.2,'orientation':'landscape','azimuth':30}
    demo.makeModule(name='simple_panel',x=0.95,y=1.59)
    scene = demo.makeScene('simple_panel',sceneDict, nMods = 10, nRows = 3) #makeScene creates a .rad file with 20 modules per row, 7 rows.
    octfile = demo.makeOct(demo.getfilelist())  # makeOct combines all of the ground, sky and object files into a .oct file.
    analysis = bifacial_radiance.AnalysisObj(octfile, demo.name)  # return an analysis object including the scan dimensions for back irradiance
    analysis.analysis(octfile, demo.name, scene.frontscan, scene.backscan)  # compare the back vs front irradiance
    #assert np.round(np.mean(analysis.backRatio),2) == 0.20  # bifi ratio was == 0.22 in v0.2.2
    assert np.mean(analysis.Wm2Front) == pytest.approx(912, rel = 0.005)
    assert np.mean(analysis.Wm2Back) == pytest.approx(182, rel = 0.01)

def test_RadianceObj_1axis_gendaylit_end_to_end():
    # 1-axis tracking end-to-end test with torque tube and gap generation.
    # Takes 20 seconds for 2-sensor scan
    module_height = 1.95 * 2 + 0.1  # module portrait dimension in meters
    gcr = 0.35   # ground cover ratio,  = module_height / pitch
    albedo = 0.3     # ground albedo
    hub_height = 2   # tracker height at 0 tilt in meters (hub height)

    demo = bifacial_radiance.RadianceObj()  # Create a RadianceObj 'object'
    demo.setGround(albedo) # input albedo number or material name like 'concrete'.  To see options, run this without any input.
    metdata = demo.readEPW(MET_FILENAME) # read in the EPW weather data from above
    #metdata = demo.readTMY(MET_FILENAME2) # select a TMY file using graphical picker
    # create metdata files for each condition. keys are timestamps for gendaylit workflow
    trackerdict = demo.set1axis(cumulativesky = False)
    # create the skyfiles needed for 1-axis tracking
    demo.gendaylit1axis(metdata = metdata, enddate = '01/01')
    # test modules with gap and rear tube
    demo.makeModule(name='Longi_torquetube',x=0.984,y=1.95,torquetube = True, numpanels = 2, panelgap = 0.1)
    #demo.makeModule(name='Longi_torquetube',x=0.984,y=1.95)
    # set module type to be used and passed into makeScene1axis
    module_type = 'Longi_torquetube'

    # Create the scene for the 1-axis tracking
    sceneDict = {'pitch': module_height / gcr,'height':hub_height,'orientation':'portrait'}
    key = '01_01_11'
    demo.makeScene1axis({key:trackerdict[key]}, module_type,sceneDict, cumulativesky = False, nMods = 10, nRows = 3, modwanted = 3, rowwanted = 3, sensorsy = 2) #makeScene creates a .rad file with 20 modules per row, 7 rows.

    demo.makeOct1axis(trackerdict,key) # just run this for one timestep: Jan 1 11am
    demo.analysis1axis(trackerdict,key) # just run this for one timestep: Jan 1 11am

    assert(np.mean(demo.Wm2Front) == pytest.approx(214.0, 0.01) )
    assert(np.mean(demo.Wm2Back) == pytest.approx(40.0, 0.1) )

def test_SceneObj_makeSceneNxR_lowtilt():
    # test makeSceneNxR(tilt, height, pitch, orientation = None, azimuth = 180, nMods = 20, nRows = 7, radname = None)
    # default scene with simple_panel, 10 degree tilt, 0.2 height, 1.5 row spacing, landscape
    scene = bifacial_radiance.SceneObj(moduletype = 'simple_panel')
    scene.makeSceneNxR(tilt=10,height=0.2,pitch=1.5,orientation = 'landscape')

    assert scene.frontscan.pop('orient') == '0 0 -1'
    assert scene.frontscan == pytest.approx({'Nx': 1, 'Ny': 9, 'Nz': 1,  'xinc': 0,  'yinc': 0.093556736536159757,
                              'xstart': 0,'ystart': 0.093556736536159757, 'zinc': 0, 'zstart': 1.3649657687835837})

    assert scene.backscan.pop('orient') == '0 0 1'
    assert scene.backscan == pytest.approx({'Nx': 1, 'Ny': 9, 'Nz': 1,  'xinc': 0, 'yinc': 0.093556736536159757,
                              'xstart': 0,  'ystart': 0.093556736536159757, 'zinc': 0.016496576878358378,
                              'zstart': 0.18649657687835838}) # zstart was 0.01 and zinc was 0 in v0.2.2
    assert scene.text == '!xform -rz -90 -t -0.795 0.475 0 -rx 10 -t 0 0 0.2 -a 20 -t 1.6 0 0 -a 7 -t 0 1.5 0 -i 1 -t -15.9 -4.5 0 -rz 0 objects\\simple_panel.rad'

def test_SceneObj_makeSceneNxR_hightilt():
    # test makeSceneNxR(tilt, height, pitch, orientation = None, azimuth = 180, nMods = 20, nRows = 7, radname = None)
    # default scene with simple_panel, 50 degree tilt, 0.2 height, 1.5 row spacing, landscape
    scene = bifacial_radiance.SceneObj(moduletype = 'simple_panel')

    scene.makeSceneNxR(tilt=65,height=0.2,pitch=1.5,azimuth=89,orientation = 'landscape')
    temp = scene.frontscan.pop('orient')
    assert [float(x) for x in temp.split(' ')] == pytest.approx([-0.999847695156, -0.0174524064373, 0])
    assert scene.frontscan == pytest.approx({'Nx': 1, 'Ny': 1, 'Nz': 9, 'xinc': 0, 'xstart': 0, 'yinc': 0,
                                'ystart': 0, 'zinc': 0.086099239768481745,'zstart': 0.28609923976848173})

    temp2 = scene.backscan.pop('orient')
    assert [float(x) for x in temp2.split(' ')] == pytest.approx([0.999847695156, 0.0174524064373, 0])
    assert scene.backscan == pytest.approx({'Nx': 1, 'Ny': 1, 'Nz': 9, 'xinc': 0, 'xstart': -0.94985531039857163,
                            'yinc': 0, 'ystart': -0.016579786115419416, 'zinc': 0.086099239768481745, 'zstart': 0.28609923976848173})
    assert scene.text == '!xform -rz -90 -t -0.795 0.475 0 -rx 65 -t 0 0 0.2 -a 20 -t 1.6 0 0 -a 7 -t 0 1.5 0 -i 1 -t -15.9 -4.5 0 -rz 91 objects\\simple_panel.rad'

def test_AnalysisObj_linePtsMake3D():
    # test linepts = linePtsMake3D(xstart,ystart,zstart,xinc,yinc,zinc,Nx,Ny,Nz,orient):
    analysis = bifacial_radiance.AnalysisObj()
    linepts = analysis.linePtsMake3D(0,0,0,1,1,1,1,2,3,'0 1 0')
    assert linepts == '0 0 0 0 1 0 \r0 1 0 0 1 0 \r0 0 1 0 1 0 \r0 1 1 0 1 0 \r0 0 2 0 1 0 \r0 1 2 0 1 0 \r'

     <|endoftext|>


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

#-----------------------------------------------------------------------------
# Copyright (c) 2013, The BiPy Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
from __future__ import division

__author__ = "Daniel McDonald"
__copyright__ = "Copyright 2013, The QCLI Project"
__credits__ = ["Greg Caporaso", "Daniel McDonald", "Doug Wendel",
               "Jai Ram Rideout"]
__license__ = "BSD"
__version__ = "0.1.0-dev"
__maintainer__ = "Daniel McDonald"
__email__ = "wasade@gmail.com"

from unittest import TestCase, main
from pyqi.core.command import Parameter, Command
from pyqi.core.exception import IncompetentDeveloperError

class CommandTests(TestCase):
    def test_init(self):
        """Jog the init"""
        self.assertRaises(NotImplementedError, Command)

    def test_subclass_init(self):
        """Exercise the subclassing"""
        class foo(Command):
            def run(self, **kwargs):
                return {}
            def _get_parameters(self):
                return [Parameter('a','b','c',True),
                        Parameter('x','y','z',False)]

        obs = foo()

        self.assertEqual(len(obs.Parameters), 3) # include default verbose
        self.assertEqual(len(obs._get_parameters()), 2)
        self.assertEqual(obs.run(bar={'a':10}), {})

class ParameterTests(TestCase):
    def test_init(self):
        """Jog the init"""
        obj = Parameter('a','b','c',False)
        self.assertEqual(obj.Type, 'a')
        self.assertEqual(obj.Help, 'b')
        self.assertEqual(obj.Name, 'c')
        self.assertEqual(obj.Required, False)
        self.assertEqual(obj.Default, None)
        self.assertEqual(obj.DefaultDescription, None)
        self.assertRaises(IncompetentDeveloperError, Parameter, 'a','b','c',
                            True,'x')
if __name__ == '__main__':
    main()

<commit_msg>Fix unit tests in test_command<commit_after>#!/usr/bin/env python

#-----------------------------------------------------------------------------
# Copyright (c) 2013, The BiPy Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
from __future__ import division

__author__ = "Daniel McDonald"
__copyright__ = "Copyright 2013, The QCLI Project"
__credits__ = ["Greg Caporaso", "Daniel McDonald", "Doug Wendel",
               "Jai Ram Rideout"]
__license__ = "BSD"
__version__ = "0.1.0-dev"
__maintainer__ = "Daniel McDonald"
__email__ = "wasade@gmail.com"

from unittest import TestCase, main
from pyqi.core.command import Parameter, ParameterCollection, Command
from pyqi.core.exception import IncompetentDeveloperError

class CommandTests(TestCase):
    def test_init(self):
        """Jog the init"""
        self.assertRaises(NotImplementedError, Command)

    def test_subclass_init(self):
        """Exercise the subclassing"""
        class foo(Command):
            Parameters = ParameterCollection([Parameter(str,'help1','a',True),
                    Parameter(str,'help2','b',False)])
            def run(self, **kwargs):
                return {}

        obs = foo()

        self.assertEqual(len(obs.Parameters), 2)
        self.assertEqual(obs.run(bar={'a':10}), {})

class ParameterTests(TestCase):
    def test_init(self):
        """Jog the init"""
        obj = Parameter(str,'help','a',False)
        self.assertEqual(obj.DataType, str)
        self.assertEqual(obj.Help, 'help')
        self.assertEqual(obj.Name, 'a')
        self.assertEqual(obj.Required, False)
        self.assertEqual(obj.Default, None)
        self.assertEqual(obj.DefaultDescription, None)
        self.assertRaises(IncompetentDeveloperError, Parameter, str, 'help',
                'a', True, 'x')

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


<commit_before>import unittest
from mock import MagicMock, ANY, call
import time

from malcolm.core.context import Context
from malcolm.core.errors import ResponseError, TimeoutError, BadValueError, \
    AbortedError
from malcolm.core.request import Put, Post, Subscribe, Unsubscribe
from malcolm.core.response import Error, Return, Update
from malcolm.core import Process
from malcolm.core.future import Future
from malcolm.compat import maybe_import_cothread

class MyWarning(Exception):
    pass

class TestContext(unittest.TestCase):
    def setUp(self):
        self.process = Process("proc")
        self.controller = MagicMock(mri="block")
        self.process.add_controller(self.controller)
        self.o = Context(self.process)
        self.cothread = maybe_import_cothread()

    def assert_handle_request_called_with(self, *requests):
        assert self.controller.handle_request.call_count == len(requests)
        for i, request in enumerate(requests):
            actual = self.controller.handle_request.call_args_list[i][0][0]
            assert request.to_dict() == actual.to_dict()

    def test_aborts_timeout_zero(self):
        self.o.ignore_stops_before_now()
        self.o.sleep(0)
        self.o.ignore_stops_before_now()
        self.o.ignore_stops_before_now()
        self.o.stop()
        with self.assertRaises(AbortedError) as cm:
            self.o.sleep(0)
        assert cm.exception.message == "Aborted waiting for []"

    def test_block_view(self):
        self.o.block_view("block")
        self.controller.make_view.assert_called_once_with(ANY)

    def test_put(self):
        self.o._q.put(Return(1, None))
        self.o.put(["block", "attr", "value"], 32)
        self.assert_handle_request_called_with(
            Put(1, ["block", "attr", "value"], 32))

    def test_put_failure(self):
        self.o._q.put(Error(1, ResponseError("Test Exception")))
        with self.assertRaises(ResponseError) as cm:
            self.o.put(["block", "attr", "value"], 32)
        assert str(cm.exception) == "Test Exception"

    def test_post(self):
        self.o._q.put(Return(1, dict(a=2)))
        result = self.o.post(["block", "method"], dict(b=32))
        self.assert_handle_request_called_with(
            Post(1, ["block", "method"], dict(b=32)))
        assert result == dict(a=2)

    def test_post_failure(self):
        self.o._q.put(Error(1, ValueError("Test Exception")))
        with self.assertRaises(ValueError) as cm:
            self.o.post(["block", "method"], dict(b=32))
        assert str(cm.exception) == "Test Exception"

    def test_subscribe(self):
        cb = MagicMock()
        f = self.o.subscribe(["block", "attr", "value"], cb, self.o, 'arg2')
        self.assert_handle_request_called_with(
            Subscribe(1, ["block", "attr", "value"]))
        self.o._q.put(Update(1, "value1"))
        with self.assertRaises(TimeoutError):
            self.o.wait_all_futures(f, 0.01)
        cb.assert_called_once_with("value1", ANY, 'arg2')
        # since args = self.o it should be a weak proxy in second argument
        param1 = cb.call_args[0][1]
        # TODO: giles cant work out how to check weakproxy equivalence??
        # self.assertEquals(param1, self.o)
        cb.reset_mock()
        self.o._q.put(Update(1, "value2"))
        self.o._q.put(Return(1))
        self.o.wait_all_futures(f, 0.01)
        cb.assert_called_once_with("value2", ANY, 'arg2')
        assert f.result(0.01) == None

    def test_subscribe_cb_failure(self):
        def cb(value):
            raise MyWarning()

        f = self.o.subscribe(["block", "attr", "value"], cb)
        self.o._q.put(Update(1, "value1"))
        with self.assertRaises(MyWarning):
            self.o.wait_all_futures(f, 0.01)
        assert not f.done()
        self.o._q.put(Update(1, "value1"))
        with self.assertRaises(MyWarning):
            self.o.wait_all_futures(f, 0.01)
        assert not f.done()
        self.o._q.put(Return(1))
        self.o.wait_all_futures(f, 0.01)
        assert f.done()

    def test_many_puts(self):
        fs = [self.o.put_async(["block", "attr", "value"], 32),
              self.o.put_async(["block", "attr2", "value"], 32)]
        with self.assertRaises(TimeoutError) as cm:
            self.o.wait_all_futures(fs, 0.01)
        assert str(cm.exception) == \
            "Timeout waiting for [block.attr.value.put_value(32), block.attr2.value.put_value(32)]"
        assert [f.done() for f in fs] == [False, False]
        self.o._q.put(Return(2, None))
        assert [f.done() for f in fs] == [False, False]
        with self.assertRaises(TimeoutError):
            self.o.wait_all_futures(fs, 0.01)
        assert [f.done() for f in fs] == [False, True]
        self.o._q.put(Return(1, None))
        self.o.wait_all_futures(fs, 0.01)
        assert [f.done() for f in fs] == [True, True]
        self.o.wait_all_futures(fs, 0.01)
        assert [f.done() for f in fs] == [True, True]

    def test_sleep(self):
        start = time.time()
        self.o.sleep(0.05)
        end = time.time()
        self.assertAlmostEqual(end - start, 0.05, delta=0.01)

    def test_when_matches(self):
        self.o._q.put(Update(1, "value1"))
        self.o._q.put(Return(1))
        self.o.when_matches(["block", "attr", "value"], "value1", timeout=0.01)
        self.assert_handle_request_called_with(
            Subscribe(1, ["block", "attr", "value"]),
            Unsubscribe(1))

    def test_when_matches_func(self):
        self.o._q.put(Update(1, "value1"))
        self.o._q.put(Return(1))

        def f(value):
            return value.startswith("v")

        self.o.when_matches(["block", "attr", "value"], f, timeout=0.01)
        self.assert_handle_request_called_with(
            Subscribe(1, ["block", "attr", "value"]),
            Unsubscribe(1))

    def test_when_not_matches(self):
        self.o._q.put(Update(1, "value2"))
        with self.assertRaises(BadValueError) as cm:
            self.o.when_matches(
                ["block", "attr", "value"], "value1", ["value2"], timeout=0.01)
        assert cm.exception.message == \
            "Waiting for 'value1', got 'value2'"

        self.assert_handle_request_called_with(
            Subscribe(1, ["block", "attr", "value"]),
            Unsubscribe(1))

    def test_ignore_stops_before_now(self):
        fs = [self.o.put_async(["block", "attr", "value"], 32)]
        self.o.stop()
        self.o.ignore_stops_before_now()

        with self.assertRaises(TimeoutError):
            self.o.wait_all_futures(fs, 0)

        if self.cothread:
            assert 0 == len(self.o._q._event_queue)
        else:
            assert 0 == self.o._q._queue.qsize()

    def test_futures_exception(self):
        fs = [self.o.put_async(["block", "attr", "value"], 32)]

        fs[0]._exception = BadValueError()
        fs[0]._state = Future.FINISHED
        with self.assertRaises(BadValueError) as cm:
            self.o.wait_all_futures(fs, 0)
        assert cm.exception is fs[0]._exception

    def test_futures_remaining_paths(self):
        fs = [self.o.put_async(["block", "attr", "value"], 32)]
        self.o.stop()
        with self.assertRaises(AbortedError) as cm:
            self.o.wait_all_futures(fs, 0)
        assert cm.exception.message == \
            "Aborted waiting for [block.attr.value.put_value(32)]"

    def test_timeout_bad(self):
        future = self.o.put_async(["block", "attr", "value"], 32)
        with self.assertRaises(TimeoutError) as cm:
            self.o.wait_all_futures(future, timeout=0.01)
        assert cm.exception.message == \
            "Timeout waiting for [block.attr.value.put_value(32)]"

    def test_timeout_good(self):
        future = self.o.put_async(["block", "attr", "value"], 32)
        self.o._q.put(Return(1))
        self.o.wait_all_futures(future, timeout=0.01)

    def test_event_timeout_bad(self):
        future = self.o.put_async(["block", "attr", "value"], 32)
        with self.assertRaises(TimeoutError) as cm:
            self.o.wait_all_futures(future, event_timeout=0.01)
        assert cm.exception.message == \
            "Timeout waiting for [block.attr.value.put_value(32)]"

    def test_event_timeout_good(self):
        future = self.o.put_async(["block", "attr", "value"], 32)
        self.o._q.put(Return(1))
        self.o.wait_all_futures(future, event_timeout=0.01)

<commit_msg>Fix python3 tests<commit_after>import unittest
from mock import MagicMock, ANY, call
import time

from malcolm.core.context import Context
from malcolm.core.errors import ResponseError, TimeoutError, BadValueError, \
    AbortedError
from malcolm.core.request import Put, Post, Subscribe, Unsubscribe
from malcolm.core.response import Error, Return, Update
from malcolm.core import Process
from malcolm.core.future import Future
from malcolm.compat import maybe_import_cothread

class MyWarning(Exception):
    pass

class TestContext(unittest.TestCase):
    def setUp(self):
        self.process = Process("proc")
        self.controller = MagicMock(mri="block")
        self.process.add_controller(self.controller)
        self.o = Context(self.process)
        self.cothread = maybe_import_cothread()

    def assert_handle_request_called_with(self, *requests):
        assert self.controller.handle_request.call_count == len(requests)
        for i, request in enumerate(requests):
            actual = self.controller.handle_request.call_args_list[i][0][0]
            assert request.to_dict() == actual.to_dict()

    def test_aborts_timeout_zero(self):
        self.o.ignore_stops_before_now()
        self.o.sleep(0)
        self.o.ignore_stops_before_now()
        self.o.ignore_stops_before_now()
        self.o.stop()
        with self.assertRaises(AbortedError) as cm:
            self.o.sleep(0)
        assert str(cm.exception) == "Aborted waiting for []"

    def test_block_view(self):
        self.o.block_view("block")
        self.controller.make_view.assert_called_once_with(ANY)

    def test_put(self):
        self.o._q.put(Return(1, None))
        self.o.put(["block", "attr", "value"], 32)
        self.assert_handle_request_called_with(
            Put(1, ["block", "attr", "value"], 32))

    def test_put_failure(self):
        self.o._q.put(Error(1, ResponseError("Test Exception")))
        with self.assertRaises(ResponseError) as cm:
            self.o.put(["block", "attr", "value"], 32)
        assert str(cm.exception) == "Test Exception"

    def test_post(self):
        self.o._q.put(Return(1, dict(a=2)))
        result = self.o.post(["block", "method"], dict(b=32))
        self.assert_handle_request_called_with(
            Post(1, ["block", "method"], dict(b=32)))
        assert result == dict(a=2)

    def test_post_failure(self):
        self.o._q.put(Error(1, ValueError("Test Exception")))
        with self.assertRaises(ValueError) as cm:
            self.o.post(["block", "method"], dict(b=32))
        assert str(cm.exception) == "Test Exception"

    def test_subscribe(self):
        cb = MagicMock()
        f = self.o.subscribe(["block", "attr", "value"], cb, self.o, 'arg2')
        self.assert_handle_request_called_with(
            Subscribe(1, ["block", "attr", "value"]))
        self.o._q.put(Update(1, "value1"))
        with self.assertRaises(TimeoutError):
            self.o.wait_all_futures(f, 0.01)
        cb.assert_called_once_with("value1", ANY, 'arg2')
        # since args = self.o it should be a weak proxy in second argument
        param1 = cb.call_args[0][1]
        # TODO: giles cant work out how to check weakproxy equivalence??
        # self.assertEquals(param1, self.o)
        cb.reset_mock()
        self.o._q.put(Update(1, "value2"))
        self.o._q.put(Return(1))
        self.o.wait_all_futures(f, 0.01)
        cb.assert_called_once_with("value2", ANY, 'arg2')
        assert f.result(0.01) == None

    def test_subscribe_cb_failure(self):
        def cb(value):
            raise MyWarning()

        f = self.o.subscribe(["block", "attr", "value"], cb)
        self.o._q.put(Update(1, "value1"))
        with self.assertRaises(MyWarning):
            self.o.wait_all_futures(f, 0.01)
        assert not f.done()
        self.o._q.put(Update(1, "value1"))
        with self.assertRaises(MyWarning):
            self.o.wait_all_futures(f, 0.01)
        assert not f.done()
        self.o._q.put(Return(1))
        self.o.wait_all_futures(f, 0.01)
        assert f.done()

    def test_many_puts(self):
        fs = [self.o.put_async(["block", "attr", "value"], 32),
              self.o.put_async(["block", "attr2", "value"], 32)]
        with self.assertRaises(TimeoutError) as cm:
            self.o.wait_all_futures(fs, 0.01)
        assert str(cm.exception) == \
            "Timeout waiting for [block.attr.value.put_value(32), block.attr2.value.put_value(32)]"
        assert [f.done() for f in fs] == [False, False]
        self.o._q.put(Return(2, None))
        assert [f.done() for f in fs] == [False, False]
        with self.assertRaises(TimeoutError):
            self.o.wait_all_futures(fs, 0.01)
        assert [f.done() for f in fs] == [False, True]
        self.o._q.put(Return(1, None))
        self.o.wait_all_futures(fs, 0.01)
        assert [f.done() for f in fs] == [True, True]
        self.o.wait_all_futures(fs, 0.01)
        assert [f.done() for f in fs] == [True, True]

    def test_sleep(self):
        start = time.time()
        self.o.sleep(0.05)
        end = time.time()
        self.assertAlmostEqual(end - start, 0.05, delta=0.01)

    def test_when_matches(self):
        self.o._q.put(Update(1, "value1"))
        self.o._q.put(Return(1))
        self.o.when_matches(["block", "attr", "value"], "value1", timeout=0.01)
        self.assert_handle_request_called_with(
            Subscribe(1, ["block", "attr", "value"]),
            Unsubscribe(1))

    def test_when_matches_func(self):
        self.o._q.put(Update(1, "value1"))
        self.o._q.put(Return(1))

        def f(value):
            return value.startswith("v")

        self.o.when_matches(["block", "attr", "value"], f, timeout=0.01)
        self.assert_handle_request_called_with(
            Subscribe(1, ["block", "attr", "value"]),
            Unsubscribe(1))

    def test_when_not_matches(self):
        self.o._q.put(Update(1, "value2"))
        with self.assertRaises(BadValueError) as cm:
            self.o.when_matches(
                ["block", "attr", "value"], "value1", ["value2"], timeout=0.01)
        assert str(cm.exception) == \
            "Waiting for 'value1', got 'value2'"

        self.assert_handle_request_called_with(
            Subscribe(1, ["block", "attr", "value"]),
            Unsubscribe(1))

    def test_ignore_stops_before_now(self):
        fs = [self.o.put_async(["block", "attr", "value"], 32)]
        self.o.stop()
        self.o.ignore_stops_before_now()

        with self.assertRaises(TimeoutError):
            self.o.wait_all_futures(fs, 0)

        if self.cothread:
            assert 0 == len(self.o._q._event_queue)
        else:
            assert 0 == self.o._q._queue.qsize()

    def test_futures_exception(self):
        fs = [self.o.put_async(["block", "attr", "value"], 32)]

        fs[0]._exception = BadValueError()
        fs[0]._state = Future.FINISHED
        with self.assertRaises(BadValueError) as cm:
            self.o.wait_all_futures(fs, 0)
        assert cm.exception is fs[0]._exception

    def test_futures_remaining_paths(self):
        fs = [self.o.put_async(["block", "attr", "value"], 32)]
        self.o.stop()
        with self.assertRaises(AbortedError) as cm:
            self.o.wait_all_futures(fs, 0)
        assert str(cm.exception) == \
            "Aborted waiting for [block.attr.value.put_value(32)]"

    def test_timeout_bad(self):
        future = self.o.put_async(["block", "attr", "value"], 32)
        with self.assertRaises(TimeoutError) as cm:
            self.o.wait_all_futures(future, timeout=0.01)
        assert str(cm.exception) == \
            "Timeout waiting for [block.attr.value.put_value(32)]"

    def test_timeout_good(self):
        future = self.o.put_async(["block", "attr", "value"], 32)
        self.o._q.put(Return(1))
        self.o.wait_all_futures(future, timeout=0.01)

    def test_event_timeout_bad(self):
        future = self.o.put_async(["block", "attr", "value"], 32)
        with self.assertRaises(TimeoutError) as cm:
            self.o.wait_all_futures(future, event_timeout=0.01)
        assert str(cm.exception) == \
            "Timeout waiting for [block.attr.value.put_value(32)]"

    def test_event_timeout_good(self):
        future = self.o.put_async(["block", "attr", "value"], 32)
        self.o._q.put(Return(1))
        self.o.wait_all_futures(future, event_timeout=0.01)

<|endoftext|>


<commit_before>#
# Evy - a concurrent networking library for Python
#
# Unless otherwise noted, the files in Evy are under the following MIT license:
#
# Copyright (c) 2012, Alvaro Saurin
# Copyright (c) 2008-2010, Eventlet Contributors (see AUTHORS)
# Copyright (c) 2007-2010, Linden Research, Inc.
# Copyright (c) 2005-2006, Bob Ippolito
#
# 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.
#

import gc
import random

from evy.green.pools import GreenPile, GreenPool
from evy.green.threads import spawn, sleep

import tests

class StressException(Exception):
    pass

r = random.Random(0)

def pressure (arg):
    while r.random() < 0.5:
        sleep(r.random() * 0.001)
    if r.random() < 0.8:
        return arg
    else:
        raise StressException(arg)

def passthru (arg):
    while r.random() < 0.5:
        sleep(r.random() * 0.001)
    return arg

class Stress(tests.LimitedTestCase):
    # tests will take extra-long
    TEST_TIMEOUT = 60

    def spawn_order_check (self, concurrency):
        # checks that piles are strictly ordered
        p = GreenPile(concurrency)

        def makework (count, unique):
            for i in xrange(count):
                token = (unique, i)
                p.spawn(pressure, token)

        iters = 1000
        spawn(makework, iters, 1)
        spawn(makework, iters, 2)
        spawn(makework, iters, 3)
        p.spawn(pressure, (0, 0))
        latest = [-1] * 4
        received = 0
        it = iter(p)
        while True:
            try:
                i = it.next()
            except StressException, exc:
                i = exc.args[0]
            except StopIteration:
                break
            received += 1
            if received % 5 == 0:
                sleep(0.0001)
            unique, order = i
            self.assert_(latest[unique] < order)
            latest[unique] = order
        for l in latest[1:]:
            self.assertEquals(l, iters - 1)

    def test_ordering_5 (self):
        self.spawn_order_check(5)

    def test_ordering_50 (self):
        self.spawn_order_check(50)

    def imap_memory_check (self, concurrency):
        # checks that imap is strictly
        # ordered and consumes a constant amount of memory
        p = GreenPool(concurrency)
        count = 1000
        it = p.imap(passthru, xrange(count))
        latest = -1
        while True:
            try:
                i = it.next()
            except StopIteration:
                break

            if latest == -1:
                gc.collect()
                initial_obj_count = len(gc.get_objects())
            self.assert_(i > latest)
            latest = i
            if latest % 5 == 0:
                sleep(0.001)
            if latest % 10 == 0:
                gc.collect()
                objs_created = len(gc.get_objects()) - initial_obj_count
                self.assert_(objs_created < 25 * concurrency, objs_created)
            # make sure we got to the end
        self.assertEquals(latest, count - 1)

    #@tests.skip_unless(os.environ.get('RUN_STRESS_TESTS') == 'YES')
    def test_imap_50 (self):
        self.imap_memory_check(50)

    def test_imap_500 (self):
        self.imap_memory_check(500)

    def test_with_intpool (self):
        from evy import pools

        class IntPool(pools.Pool):
            def create (self):
                self.current_integer = getattr(self, 'current_integer', 0) + 1
                return self.current_integer

        def subtest (intpool_size, pool_size, num_executes):
            def run (int_pool):
                token = int_pool.get()
                sleep(0.0001)
                int_pool.put(token)
                return token

            int_pool = IntPool(max_size = intpool_size)
            pool = GreenPool(pool_size)
            for ix in xrange(num_executes):
                pool.spawn(run, int_pool)
            pool.waitall()

        subtest(4, 7, 7)
        subtest(50, 75, 100)
        for isize in (10, 20, 30, 40, 50):
            for psize in (5, 25, 35, 50):
                subtest(isize, psize, psize)
<commit_msg>Use a Nose attribute for performance tests<commit_after>#
# Evy - a concurrent networking library for Python
#
# Unless otherwise noted, the files in Evy are under the following MIT license:
#
# Copyright (c) 2012, Alvaro Saurin
# Copyright (c) 2008-2010, Eventlet Contributors (see AUTHORS)
# Copyright (c) 2007-2010, Linden Research, Inc.
# Copyright (c) 2005-2006, Bob Ippolito
#
# 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.
#

import gc
import random

from evy.green.pools import GreenPile, GreenPool
from evy.green.threads import spawn, sleep

import tests

class StressException(Exception):
    pass

r = random.Random(0)

def pressure (arg):
    while r.random() < 0.5:
        sleep(r.random() * 0.001)
    if r.random() < 0.8:
        return arg
    else:
        raise StressException(arg)

def passthru (arg):
    while r.random() < 0.5:
        sleep(r.random() * 0.001)
    return arg

class Stress(tests.LimitedTestCase):
    # tests will take extra-long
    TEST_TIMEOUT = 60

    def spawn_order_check (self, concurrency):
        # checks that piles are strictly ordered
        p = GreenPile(concurrency)

        def makework (count, unique):
            for i in xrange(count):
                token = (unique, i)
                p.spawn(pressure, token)

        iters = 1000
        spawn(makework, iters, 1)
        spawn(makework, iters, 2)
        spawn(makework, iters, 3)
        p.spawn(pressure, (0, 0))
        latest = [-1] * 4
        received = 0
        it = iter(p)
        while True:
            try:
                i = it.next()
            except StressException, exc:
                i = exc.args[0]
            except StopIteration:
                break
            received += 1
            if received % 5 == 0:
                sleep(0.0001)
            unique, order = i
            self.assert_(latest[unique] < order)
            latest[unique] = order
        for l in latest[1:]:
            self.assertEquals(l, iters - 1)

    @tests.attr('perf')
    def test_ordering_5 (self):
        self.spawn_order_check(5)

    @tests.attr('perf')
    def test_ordering_50 (self):
        self.spawn_order_check(50)

    def imap_memory_check (self, concurrency):
        # checks that imap is strictly
        # ordered and consumes a constant amount of memory
        p = GreenPool(concurrency)
        count = 1000
        it = p.imap(passthru, xrange(count))
        latest = -1
        while True:
            try:
                i = it.next()
            except StopIteration:
                break

            if latest == -1:
                gc.collect()
                initial_obj_count = len(gc.get_objects())
            self.assert_(i > latest)
            latest = i
            if latest % 5 == 0:
                sleep(0.001)
            if latest % 10 == 0:
                gc.collect()
                objs_created = len(gc.get_objects()) - initial_obj_count
                self.assert_(objs_created < 25 * concurrency, objs_created)
            # make sure we got to the end
        self.assertEquals(latest, count - 1)

    @tests.attr('perf')
    def test_imap_50 (self):
        self.imap_memory_check(50)

    @tests.attr('perf')
    def test_imap_500 (self):
        self.imap_memory_check(500)

    @tests.attr('perf')
    def test_with_intpool (self):
        from evy.pools import Pool

        class IntPool(Pool):
            def create (self):
                self.current_integer = getattr(self, 'current_integer', 0) + 1
                return self.current_integer

        def subtest (intpool_size, pool_size, num_executes):
            def run (int_pool):
                token = int_pool.get()
                sleep(0.0001)
                int_pool.put(token)
                return token

            int_pool = IntPool(max_size = intpool_size)
            pool = GreenPool(pool_size)
            for ix in xrange(num_executes):
                pool.spawn(run, int_pool)
            pool.waitall()

        subtest(4, 7, 7)
        subtest(50, 75, 100)
        for isize in (10, 20, 30, 40, 50):
            for psize in (5, 25, 35, 50):
                subtest(isize, psize, psize)
<|endoftext|>


<commit_before>input_names = {'TL': '../examples/large_deformation/hyperelastic.py',
               'UL': '../examples/large_deformation/hyperelastic_ul.py'}
output_name_trunk = 'test_hyperelastic_'

from sfepy.base.testing import TestCommon
from testsBasic import NLSStatus

class Test(TestCommon):

    @staticmethod
    def from_conf(conf, options):
        return Test(conf = conf, options = options)

    def test_solution(self):

        from sfepy.base.base import Struct
        from sfepy.base.conf import ProblemConf, get_standard_keywords
        from sfepy.applications.simple_app import assign_standard_hooks
        from sfepy.solvers.generic import solve_direct
        import numpy as nm
        import os.path as op

        solutions = {}
        ok = True

        for hp, pb_filename in input_names.iteritems():

            required, other = get_standard_keywords()
            input_name = op.join(op.dirname(__file__), pb_filename)
            test_conf = ProblemConf.from_file(input_name, required, other)

            solver_options = Struct(output_filename_trunk = output_name_trunk + hp,
                                    output_format ='vtk',
                                    save_ebc = False, save_regions = False,
                                    save_regions_as_groups = False,
                                    save_field_meshes = False,
                                    solve_not = False)
            assign_standard_hooks(self, test_conf.options.get_default_attr,
                                  test_conf)

            self.report( 'hyperelastic formulation: %s' % (hp, ) )

            status = NLSStatus(conditions=[])

            pb, state = solve_direct(test_conf,
                                     solver_options,
                                     step_hook=self.step_hook,
                                     post_process_hook=self.post_process_hook,
                                     post_process_hook_final=self.post_process_hook_final,
                                     nls_status=status)

            converged = status.condition == 0
            ok = ok and converged

            solutions[hp] = state.get_parts()['u']
            self.report('%s solved' % input_name)

        rerr = 1.0e-2;
        aerr = nm.linalg.norm(solutions['TL'], ord=None) * rerr

        self.report('allowederror: rel = %e, abs = %e' % (rerr, aerr) )
        ok = ok and self.compare_vectors( solutions['TL'], solutions['UL'],
                                          label1 = 'TLF',
                                          label2 = 'ULF',
                                          allowed_error = rerr)

        return ok
<commit_msg>fix output directory in test_hyperelastic_tlul.py<commit_after>input_names = {'TL': '../examples/large_deformation/hyperelastic.py',
               'UL': '../examples/large_deformation/hyperelastic_ul.py'}
output_name_trunk = 'test_hyperelastic_'

from sfepy.base.testing import TestCommon
from testsBasic import NLSStatus

class Test(TestCommon):

    @staticmethod
    def from_conf(conf, options):
        return Test(conf = conf, options = options)

    def test_solution(self):

        from sfepy.base.base import Struct
        from sfepy.base.conf import ProblemConf, get_standard_keywords
        from sfepy.applications.simple_app import assign_standard_hooks
        from sfepy.solvers.generic import solve_direct
        import numpy as nm
        import os.path as op

        solutions = {}
        ok = True

        for hp, pb_filename in input_names.iteritems():

            required, other = get_standard_keywords()
            input_name = op.join(op.dirname(__file__), pb_filename)
            test_conf = ProblemConf.from_file(input_name, required, other)

            name = op.join(self.options.out_dir, output_name_trunk + hp)
            solver_options = Struct(output_filename_trunk = name,
                                    output_format ='vtk',
                                    save_ebc = False, save_regions = False,
                                    save_regions_as_groups = False,
                                    save_field_meshes = False,
                                    solve_not = False)
            assign_standard_hooks(self, test_conf.options.get_default_attr,
                                  test_conf)

            self.report( 'hyperelastic formulation: %s' % (hp, ) )

            status = NLSStatus(conditions=[])

            pb, state = solve_direct(test_conf,
                                     solver_options,
                                     step_hook=self.step_hook,
                                     post_process_hook=self.post_process_hook,
                                     post_process_hook_final=self.post_process_hook_final,
                                     nls_status=status)

            converged = status.condition == 0
            ok = ok and converged

            solutions[hp] = state.get_parts()['u']
            self.report('%s solved' % input_name)

        rerr = 1.0e-3
        aerr = nm.linalg.norm(solutions['TL'], ord=None) * rerr

        self.report('allowed error: rel = %e, abs = %e' % (rerr, aerr))
        ok = ok and self.compare_vectors(solutions['TL'], solutions['UL'],
                                         label1='TLF',
                                         label2='ULF',
                                         allowed_error=rerr)

        return ok
<|endoftext|>


<commit_before>from pyramid import testing
from pytest import fixture
from pytest import mark

def register_and_add_sheet(context, registry, mock_sheet):
    from zope.interface import alsoProvides
    from adhocracy_core.interfaces import IResourceSheet
    isheet = mock_sheet.meta.isheet
    alsoProvides(context, isheet)
    registry.registerAdapter(lambda x: mock_sheet, (isheet,),
                             IResourceSheet,
                             isheet.__identifier__)

class TestResourceModifiedMetadataSubscriber:

    def _call_fut(self, event):
        from adhocracy_core.sheets.metadata import resource_modified_metadata_subscriber
        return resource_modified_metadata_subscriber(event)

    def test_with_metadata_isheet(self, context, registry, mock_sheet,
                                  cornice_request):
        from datetime import datetime
        from adhocracy_core.sheets.metadata import IMetadata
        event = testing.DummyResource(object=context,
                                      registry=registry,
                                      request=cornice_request)
        mock_sheet.meta = mock_sheet.meta._replace(isheet=IMetadata)
        register_and_add_sheet(context, registry, mock_sheet)

        self._call_fut(event)

        set_modification_date = mock_sheet.set.call_args[0][0]['modification_date']
        assert set_modification_date.date() == datetime.now().date()

class TestIMetadataSchema:

    def _make_one(self, **kwargs):
        from adhocracy_core.sheets.metadata import MetadataSchema
        return MetadataSchema(**kwargs)

    def test_deserialize_empty(self):
        inst = self._make_one()
        result = inst.deserialize({})
        assert result == {'deleted': False, 'hidden': False}

    def test_serialize_empty(self):
        from colander import null
        inst = self._make_one()
        result = inst.serialize({})
        assert result['creation_date'] == null
        assert result['creator'] == ''
        assert result['item_creation_date'] == null
        assert result['modification_date'] == null
        assert result['modified_by'] == ''
        assert result['deleted'] == 'false'
        assert result['hidden'] == 'false'

    def test_serialize_empty_and_bind(self):
        from datetime import datetime
        inst = self._make_one().bind()
        result = inst.serialize({})
        this_year = str(datetime.now().year)
        assert this_year in result['creation_date']
        assert this_year in result['item_creation_date']
        assert this_year in result['modification_date']

class TestMetadataSheet:

    @fixture
    def meta(self):
        from adhocracy_core.sheets.metadata import metadata_metadata
        return metadata_metadata

    def test_create(self, meta, context):
        from adhocracy_core.sheets.metadata import IMetadata
        from adhocracy_core.sheets.metadata import MetadataSchema
        inst = meta.sheet_class(meta, context)
        assert inst.meta.isheet == IMetadata
        assert inst.meta.schema_class == MetadataSchema
        assert inst.meta.editable is True
        assert inst.meta.creatable is True
        assert inst.meta.readable is True

@fixture
def integration(config):
    config.include('adhocracy_core.catalog')
    config.include('adhocracy_core.events')
    config.include('adhocracy_core.sheets.metadata')

@mark.usefixtures('integration')
def test_includeme_register_metadata_sheet(config):
    from adhocracy_core.sheets.metadata import IMetadata
    from adhocracy_core.utils import get_sheet
    context = testing.DummyResource(__provides__=IMetadata)
    assert get_sheet(context, IMetadata)

@mark.usefixtures('integration')
def test_includeme_register_metadata_update_subscriber(config):
    handlers = config.registry.registeredHandlers()
    handler_names = [x.handler.__name__ for x in handlers]
    assert 'resource_modified_metadata_subscriber' in handler_names

class TestVisibility:

    @fixture
    def resource_with_metadata(self, integration):
        from adhocracy_core.interfaces import IResource
        from adhocracy_core.sheets.metadata import IMetadata
        return testing.DummyResource(__provides__=[IResource, IMetadata])

    def test_is_deleted_attribute_is_true(self, context):
        from adhocracy_core.sheets.metadata import is_deleted
        context.deleted = True
        assert is_deleted(context) is True

    def test_is_deleted_attribute_is_false(self, context):
        from adhocracy_core.sheets.metadata import is_deleted
        context.deleted = False
        assert is_deleted(context) is False

    def test_is_deleted_attribute_not_set(self, context):
        from adhocracy_core.sheets.metadata import is_deleted
        assert is_deleted(context) is False

    def test_is_deleted_parent_attribute_is_true(self, context):
        from adhocracy_core.interfaces import IResource
        from adhocracy_core.sheets.metadata import is_deleted
        child = testing.DummyResource(__provides__=IResource)
        context['child'] = child
        context.deleted = True
        assert is_deleted(child) is True

    def test_is_deleted_parent_attribute_is_false(self, context):
        from adhocracy_core.interfaces import IResource
        from adhocracy_core.sheets.metadata import is_deleted
        child = testing.DummyResource(__provides__=IResource)
        context['child'] = child
        context.deleted = False
        assert is_deleted(child) is False

    def test_is_deleted_parent_attribute_not_set(self, context):
        from adhocracy_core.interfaces import IResource
        from adhocracy_core.sheets.metadata import is_deleted
        child = testing.DummyResource(__provides__=IResource)
        context['child'] = child
        assert is_deleted(child) is False

    def test_is_deleted_parent_attrib_true_child_attrib_false(self, context):
        from adhocracy_core.interfaces import IResource
        from adhocracy_core.sheets.metadata import is_deleted
        child = testing.DummyResource(__provides__=IResource)
        context['child'] = child
        context.deleted = True
        child.deleted = False
        assert is_deleted(child) is True

    def test_is_hidden_attribute_is_true(self, context):
        from adhocracy_core.sheets.metadata import is_hidden
        context.hidden = True
        assert is_hidden(context) is True

    def test_is_hidden_attribute_is_false(self, context):
        from adhocracy_core.sheets.metadata import is_hidden
        context.hidden = False
        assert is_hidden(context) is False

    def test_is_hidden_attribute_not_set(self, context):
        from adhocracy_core.sheets.metadata import is_hidden
        assert is_hidden(context) is False

    def test_is_hidden_parent_attribute_is_true(self, context):
        from adhocracy_core.interfaces import IResource
        from adhocracy_core.sheets.metadata import is_hidden
        child = testing.DummyResource(__provides__=IResource)
        context['child'] = child
        context.hidden = True
        assert is_hidden(child) is True

    def test_is_hidden_parent_attribute_is_false(self, context):
        from adhocracy_core.interfaces import IResource
        from adhocracy_core.sheets.metadata import is_hidden
        child = testing.DummyResource(__provides__=IResource)
        context['child'] = child
        context.hidden = False
        assert is_hidden(child) is False

    def test_is_hidden_parent_attribute_not_set(self, context):
        from adhocracy_core.interfaces import IResource
        from adhocracy_core.sheets.metadata import is_hidden
        child = testing.DummyResource(__provides__=IResource)
        context['child'] = child
        assert is_hidden(child) is False

    def test_is_hidden_parent_attrib_true_child_attrib_false(self, context):
        from adhocracy_core.interfaces import IResource
        from adhocracy_core.sheets.metadata import is_hidden
        child = testing.DummyResource(__provides__=IResource)
        context['child'] = child
        context.hidden = True
        child.hidden = False
        assert is_hidden(child) is True

    def test_view_blocked_by_metadata_no_metadata(self, registry):
        from adhocracy_core.interfaces import IResource
        from adhocracy_core.sheets.metadata import view_blocked_by_metadata
        resource = testing.DummyResource(__provides__=IResource)
        assert view_blocked_by_metadata(resource, registry) is None

    @mark.usefixtures('integration')
    def test_view_blocked_by_metadata_not_blocked(self, registry):
        from adhocracy_core.interfaces import IResource
        from adhocracy_core.sheets.metadata import IMetadata
        from adhocracy_core.sheets.metadata import view_blocked_by_metadata
        resource = testing.DummyResource(__provides__=[IResource, IMetadata])
        assert view_blocked_by_metadata(resource, registry) is None

    def test_view_blocked_by_metadata_deleted(self, resource_with_metadata,
                                              registry):
        from adhocracy_core.sheets.metadata import view_blocked_by_metadata
        resource_with_metadata.deleted = True
        result = view_blocked_by_metadata(resource_with_metadata, registry)
        assert result['reason'] == 'deleted'

    def test_view_blocked_by_metadata_hidden(self, resource_with_metadata,
                                              registry):
        from adhocracy_core.sheets.metadata import view_blocked_by_metadata
        resource_with_metadata.hidden = True
        result = view_blocked_by_metadata(resource_with_metadata, registry)
        assert result['reason'] == 'hidden'

    def test_view_blocked_by_metadata_both(self, resource_with_metadata,
                                              registry):
        from adhocracy_core.sheets.metadata import view_blocked_by_metadata
        resource_with_metadata.deleted = True
        resource_with_metadata.hidden = True
        result = view_blocked_by_metadata(resource_with_metadata, registry)
        assert result['reason'] == 'both'

    def test_view_blocked_by_metadata_result_fields_correct(
            self, pool_graph, resource_with_metadata, registry):
        from datetime import datetime
        from adhocracy_core.resources.principal import IUser
        from adhocracy_core.sheets.metadata import IMetadata
        from adhocracy_core.sheets.metadata import view_blocked_by_metadata
        from adhocracy_core.utils import get_sheet
        pool_graph['res'] = resource_with_metadata
        metadata = get_sheet(resource_with_metadata, IMetadata,
                             registry=registry)
        appstruct = metadata.get()
        user = testing.DummyRequest(__provides__=IUser)
        pool_graph['user'] = user
        now = datetime.now()
        appstruct['modified_by'] = user
        appstruct['modification_date'] = now
        metadata.set(appstruct, force=True, send_event=False)
        resource_with_metadata.hidden = True
        result = view_blocked_by_metadata(resource_with_metadata, registry)
        assert result['modified_by'] == user
        assert result['modification_date'] == now

    def test_index_visibility_visible(self, context):
        from adhocracy_core.sheets.metadata import index_visibility
        assert index_visibility(context, 'default') == ['visible']

    def test_index_visibility_deleted(self, context):
        from adhocracy_core.sheets.metadata import index_visibility
        context.deleted = True
        assert index_visibility(context, 'default') == ['deleted']

    def test_index_visibility_hidden(self, context):
        from adhocracy_core.sheets.metadata import index_visibility
        context.hidden = True
        assert index_visibility(context, 'default') == ['hidden']

    def test_index_visibility_both(self, context):
        from adhocracy_core.sheets.metadata import index_visibility
        context.deleted = True
        context.hidden = True
        assert sorted(index_visibility(context, 'default')) == ['deleted',
                                                                'hidden']
<commit_msg>Simplify test<commit_after>from pyramid import testing
from pytest import fixture
from pytest import mark

def register_and_add_sheet(context, registry, mock_sheet):
    from zope.interface import alsoProvides
    from adhocracy_core.interfaces import IResourceSheet
    isheet = mock_sheet.meta.isheet
    alsoProvides(context, isheet)
    registry.registerAdapter(lambda x: mock_sheet, (isheet,),
                             IResourceSheet,
                             isheet.__identifier__)

class TestResourceModifiedMetadataSubscriber:

    def _call_fut(self, event):
        from adhocracy_core.sheets.metadata import resource_modified_metadata_subscriber
        return resource_modified_metadata_subscriber(event)

    def test_with_metadata_isheet(self, context, registry, mock_sheet,
                                  cornice_request):
        from datetime import datetime
        from adhocracy_core.sheets.metadata import IMetadata
        event = testing.DummyResource(object=context,
                                      registry=registry,
                                      request=cornice_request)
        mock_sheet.meta = mock_sheet.meta._replace(isheet=IMetadata)
        register_and_add_sheet(context, registry, mock_sheet)

        self._call_fut(event)

        set_modification_date = mock_sheet.set.call_args[0][0]['modification_date']
        assert set_modification_date.date() == datetime.now().date()

class TestIMetadataSchema:

    def _make_one(self, **kwargs):
        from adhocracy_core.sheets.metadata import MetadataSchema
        return MetadataSchema(**kwargs)

    def test_deserialize_empty(self):
        inst = self._make_one()
        result = inst.deserialize({})
        assert result == {'deleted': False, 'hidden': False}

    def test_serialize_empty(self):
        from colander import null
        inst = self._make_one()
        result = inst.serialize({})
        assert result['creation_date'] == null
        assert result['creator'] == ''
        assert result['item_creation_date'] == null
        assert result['modification_date'] == null
        assert result['modified_by'] == ''
        assert result['deleted'] == 'false'
        assert result['hidden'] == 'false'

    def test_serialize_empty_and_bind(self):
        from datetime import datetime
        inst = self._make_one().bind()
        result = inst.serialize({})
        this_year = str(datetime.now().year)
        assert this_year in result['creation_date']
        assert this_year in result['item_creation_date']
        assert this_year in result['modification_date']

class TestMetadataSheet:

    @fixture
    def meta(self):
        from adhocracy_core.sheets.metadata import metadata_metadata
        return metadata_metadata

    def test_create(self, meta, context):
        from adhocracy_core.sheets.metadata import IMetadata
        from adhocracy_core.sheets.metadata import MetadataSchema
        inst = meta.sheet_class(meta, context)
        assert inst.meta.isheet == IMetadata
        assert inst.meta.schema_class == MetadataSchema
        assert inst.meta.editable is True
        assert inst.meta.creatable is True
        assert inst.meta.readable is True

@fixture
def integration(config):
    config.include('adhocracy_core.catalog')
    config.include('adhocracy_core.events')
    config.include('adhocracy_core.sheets.metadata')

@mark.usefixtures('integration')
def test_includeme_register_metadata_sheet(config):
    from adhocracy_core.sheets.metadata import IMetadata
    from adhocracy_core.utils import get_sheet
    context = testing.DummyResource(__provides__=IMetadata)
    assert get_sheet(context, IMetadata)

@mark.usefixtures('integration')
def test_includeme_register_metadata_update_subscriber(config):
    handlers = config.registry.registeredHandlers()
    handler_names = [x.handler.__name__ for x in handlers]
    assert 'resource_modified_metadata_subscriber' in handler_names

class TestVisibility:

    @fixture
    def resource_with_metadata(self, integration):
        from adhocracy_core.interfaces import IResource
        from adhocracy_core.sheets.metadata import IMetadata
        return testing.DummyResource(__provides__=[IResource, IMetadata])

    def test_is_deleted_attribute_is_true(self, context):
        from adhocracy_core.sheets.metadata import is_deleted
        context.deleted = True
        assert is_deleted(context) is True

    def test_is_deleted_attribute_is_false(self, context):
        from adhocracy_core.sheets.metadata import is_deleted
        context.deleted = False
        assert is_deleted(context) is False

    def test_is_deleted_attribute_not_set(self, context):
        from adhocracy_core.sheets.metadata import is_deleted
        assert is_deleted(context) is False

    def test_is_deleted_parent_attribute_is_true(self, context):
        from adhocracy_core.interfaces import IResource
        from adhocracy_core.sheets.metadata import is_deleted
        child = testing.DummyResource(__provides__=IResource)
        context['child'] = child
        context.deleted = True
        assert is_deleted(child) is True

    def test_is_deleted_parent_attribute_is_false(self, context):
        from adhocracy_core.interfaces import IResource
        from adhocracy_core.sheets.metadata import is_deleted
        child = testing.DummyResource(__provides__=IResource)
        context['child'] = child
        context.deleted = False
        assert is_deleted(child) is False

    def test_is_deleted_parent_attribute_not_set(self, context):
        from adhocracy_core.interfaces import IResource
        from adhocracy_core.sheets.metadata import is_deleted
        child = testing.DummyResource(__provides__=IResource)
        context['child'] = child
        assert is_deleted(child) is False

    def test_is_deleted_parent_attrib_true_child_attrib_false(self, context):
        from adhocracy_core.interfaces import IResource
        from adhocracy_core.sheets.metadata import is_deleted
        child = testing.DummyResource(__provides__=IResource)
        context['child'] = child
        context.deleted = True
        child.deleted = False
        assert is_deleted(child) is True

    def test_is_hidden_attribute_is_true(self, context):
        from adhocracy_core.sheets.metadata import is_hidden
        context.hidden = True
        assert is_hidden(context) is True

    def test_is_hidden_attribute_is_false(self, context):
        from adhocracy_core.sheets.metadata import is_hidden
        context.hidden = False
        assert is_hidden(context) is False

    def test_is_hidden_attribute_not_set(self, context):
        from adhocracy_core.sheets.metadata import is_hidden
        assert is_hidden(context) is False

    def test_is_hidden_parent_attribute_is_true(self, context):
        from adhocracy_core.interfaces import IResource
        from adhocracy_core.sheets.metadata import is_hidden
        child = testing.DummyResource(__provides__=IResource)
        context['child'] = child
        context.hidden = True
        assert is_hidden(child) is True

    def test_is_hidden_parent_attribute_is_false(self, context):
        from adhocracy_core.interfaces import IResource
        from adhocracy_core.sheets.metadata import is_hidden
        child = testing.DummyResource(__provides__=IResource)
        context['child'] = child
        context.hidden = False
        assert is_hidden(child) is False

    def test_is_hidden_parent_attribute_not_set(self, context):
        from adhocracy_core.interfaces import IResource
        from adhocracy_core.sheets.metadata import is_hidden
        child = testing.DummyResource(__provides__=IResource)
        context['child'] = child
        assert is_hidden(child) is False

    def test_is_hidden_parent_attrib_true_child_attrib_false(self, context):
        from adhocracy_core.interfaces import IResource
        from adhocracy_core.sheets.metadata import is_hidden
        child = testing.DummyResource(__provides__=IResource)
        context['child'] = child
        context.hidden = True
        child.hidden = False
        assert is_hidden(child) is True

    def test_view_blocked_by_metadata_no_metadata(self, registry):
        from adhocracy_core.interfaces import IResource
        from adhocracy_core.sheets.metadata import view_blocked_by_metadata
        resource = testing.DummyResource(__provides__=IResource)
        assert view_blocked_by_metadata(resource, registry) is None

    def test_view_blocked_by_metadata_not_blocked(self, resource_with_metadata,
                                                  registry):
        from adhocracy_core.sheets.metadata import view_blocked_by_metadata
        result = view_blocked_by_metadata(resource_with_metadata, registry)
        assert result is None

    def test_view_blocked_by_metadata_deleted(self, resource_with_metadata,
                                              registry):
        from adhocracy_core.sheets.metadata import view_blocked_by_metadata
        resource_with_metadata.deleted = True
        result = view_blocked_by_metadata(resource_with_metadata, registry)
        assert result['reason'] == 'deleted'

    def test_view_blocked_by_metadata_hidden(self, resource_with_metadata,
                                              registry):
        from adhocracy_core.sheets.metadata import view_blocked_by_metadata
        resource_with_metadata.hidden = True
        result = view_blocked_by_metadata(resource_with_metadata, registry)
        assert result['reason'] == 'hidden'

    def test_view_blocked_by_metadata_both(self, resource_with_metadata,
                                              registry):
        from adhocracy_core.sheets.metadata import view_blocked_by_metadata
        resource_with_metadata.deleted = True
        resource_with_metadata.hidden = True
        result = view_blocked_by_metadata(resource_with_metadata, registry)
        assert result['reason'] == 'both'

    def test_view_blocked_by_metadata_result_fields_correct(
            self, pool_graph, resource_with_metadata, registry):
        from datetime import datetime
        from adhocracy_core.resources.principal import IUser
        from adhocracy_core.sheets.metadata import IMetadata
        from adhocracy_core.sheets.metadata import view_blocked_by_metadata
        from adhocracy_core.utils import get_sheet
        pool_graph['res'] = resource_with_metadata
        metadata = get_sheet(resource_with_metadata, IMetadata,
                             registry=registry)
        appstruct = metadata.get()
        user = testing.DummyRequest(__provides__=IUser)
        pool_graph['user'] = user
        now = datetime.now()
        appstruct['modified_by'] = user
        appstruct['modification_date'] = now
        metadata.set(appstruct, force=True, send_event=False)
        resource_with_metadata.hidden = True
        result = view_blocked_by_metadata(resource_with_metadata, registry)
        assert result['modified_by'] == user
        assert result['modification_date'] == now

    def test_index_visibility_visible(self, context):
        from adhocracy_core.sheets.metadata import index_visibility
        assert index_visibility(context, 'default') == ['visible']

    def test_index_visibility_deleted(self, context):
        from adhocracy_core.sheets.metadata import index_visibility
        context.deleted = True
        assert index_visibility(context, 'default') == ['deleted']

    def test_index_visibility_hidden(self, context):
        from adhocracy_core.sheets.metadata import index_visibility
        context.hidden = True
        assert index_visibility(context, 'default') == ['hidden']

    def test_index_visibility_both(self, context):
        from adhocracy_core.sheets.metadata import index_visibility
        context.deleted = True
        context.hidden = True
        assert sorted(index_visibility(context, 'default')) == ['deleted',
                                                                'hidden']
<|endoftext|>