<commit_before># -*- coding: utf-8 -*-

from __future__ import division, print_function, absolute_import
from __future__ import unicode_literals

import numpy as np
import os
import subprocess

os.chdir(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..'))
outfile = 'tests/output.txt'

def setup_function(function):
    try:
        os.remove(outfile)
    except:
        pass

teardown_function = setup_function

def test_module_invocation():
    pipe = subprocess.Popen(['python', '-m', 'apexpy', 'geo', 'apex', '2015',
                             '--height', '300', '-i', 'tests/test_convert.txt',
                             '-o', outfile])
    pipe.communicate()
    pipe.wait()
    assert os.path.isfile(outfile)
    data = np.loadtxt(outfile)
    np.testing.assert_allclose(data, [[57.469547, 93.639816],
                                      [58.522701, 94.044762],
                                      [59.571465, 94.477257]], rtol=1e-4)

def test_convert_YYYY():
    pipe = subprocess.Popen(['python', '-m', 'apexpy', 'geo', 'apex', '2015',
                             '--height', '300',
                             '-i', 'tests/test_convert.txt', '-o', outfile])
    pipe.communicate()
    pipe.wait()
    assert os.path.isfile(outfile)
    data = np.loadtxt(outfile)
    np.testing.assert_allclose(data, [[57.469547, 93.639816],
                                      [58.522701, 94.044762],
                                      [59.571465, 94.477257]], rtol=1e-4)

def test_convert_YYYYMM():
    pipe = subprocess.Popen(['python', '-m', 'apexpy', 'geo', 'apex', '201501',
                             '--height', '300', '-i', 'tests/test_convert.txt',
                             '-o', outfile])
    pipe.communicate()
    pipe.wait()
    assert os.path.isfile(outfile)
    data = np.loadtxt(outfile)
    np.testing.assert_allclose(data, [[57.469547, 93.639816],
                                      [58.522701, 94.044762],
                                      [59.571465, 94.477257]], rtol=1e-4)

def test_convert_YYYYMMDD():
    pipe = subprocess.Popen(['python', '-m', 'apexpy', 'geo', 'apex',
                             '20150101', '--height', '300', '-i',
                             'tests/test_convert.txt', '-o', outfile])
    pipe.communicate()
    pipe.wait()
    assert os.path.isfile(outfile)
    data = np.loadtxt(outfile)
    np.testing.assert_allclose(data, [[57.469547, 93.639816],
                                      [58.522701, 94.044762],
                                      [59.571465, 94.477257]], rtol=1e-4)

def test_convert_YYYYMMDDHHMMSS():
    pipe = subprocess.Popen(['python', '-m', 'apexpy', 'geo', 'apex',
                             '20150101000000', '--height', '300', '-i',
                             'tests/test_convert.txt', '-o', outfile])
    pipe.communicate()
    pipe.wait()
    assert os.path.isfile(outfile)
    data = np.loadtxt(outfile)
    np.testing.assert_allclose(data, [[57.469547, 93.639816],
                                      [58.522701, 94.044762],
                                      [59.571465, 94.477257]], rtol=1e-4)

def test_convert_single_line():
    pipe = subprocess.Popen(['python', '-m', 'apexpy', 'geo', 'apex',
                             '20150101000000', '--height', '300', '-i',
                             'tests/test_convert_single_line.txt', '-o',
                             outfile])
    pipe.communicate()
    pipe.wait()
    assert os.path.isfile(outfile)
    data = np.loadtxt(outfile)
    np.testing.assert_allclose(data, [57.469547, 93.639816], rtol=1e-4)

def test_convert_stdin_stdout():
    pipe = subprocess.Popen('echo 60 15 | apexpy geo apex 2015 --height 300',
                            shell=True, stdout=subprocess.PIPE)
    stdout, _ = pipe.communicate()
    pipe.wait()
    np.testing.assert_allclose(np.array(stdout.split(b' '), dtype=float),
                               [57.469547, 93.639816], rtol=1e-4)

def test_convert_refh():
    pipe = subprocess.Popen('echo 60 15 | apexpy geo apex 2000 --height 100 --refh=300', shell=True, stdout=subprocess.PIPE)
    stdout, _ = pipe.communicate()
    pipe.wait()
    np.testing.assert_allclose(np.array(stdout.split(b' '), dtype=float),
                               [55.94841766, 94.1068344], rtol=1e-4)

def test_convert_mlt():
    pipe = subprocess.Popen(['python', '-m', 'apexpy', 'geo', 'mlt',
                             '20150101000000', '--height', '300', '-i',
                             'tests/test_convert_single_line.txt', '-o',
                             outfile])
    pipe.communicate()
    pipe.wait()
    assert os.path.isfile(outfile)
    data = np.loadtxt(outfile)
    np.testing.assert_allclose(data, [57.469547, 1.06324], rtol=1e-4)

def test_invalid_date():
    pipe = subprocess.Popen('echo 60 15 | apexpy geo apex 201501010',
                            shell=True, stderr=subprocess.PIPE)
    _, stderr = pipe.communicate()
    pipe.wait()
    assert b'ValueError' in stderr

    pipe = subprocess.Popen('echo 60 15 | apexpy geo apex 2015010100000',
                            shell=True, stderr=subprocess.PIPE)
    _, stderr = pipe.communicate()
    pipe.wait()
    assert b'ValueError' in stderr

def test_mlt_nodatetime():
    pipe = subprocess.Popen('echo 60 15 | apexpy geo mlt 20150101', shell=True,
                            stderr=subprocess.PIPE)
    _, stderr = pipe.communicate()
    pipe.wait()
    assert b'ValueError' in stderr

def test_invalid_coord():
    pipe = subprocess.Popen('echo 60 15 | apexpy foobar apex 2015', shell=True,
                            stderr=subprocess.PIPE)
    _, stderr = pipe.communicate()
    pipe.wait()
    assert b'invalid choice' in stderr

    pipe = subprocess.Popen('echo 60 15 | apexpy geo foobar 2015', shell=True,
                            stderr=subprocess.PIPE)
    _, stderr = pipe.communicate()
    pipe.wait()
    assert b'invalid choice' in stderr
<commit_msg>TST: resolved merge conflicts<commit_after># -*- coding: utf-8 -*-

from __future__ import division, print_function, absolute_import
from __future__ import unicode_literals

import numpy as np
import os
import subprocess

os.chdir(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..'))
outfile = 'tests/output.txt'

def setup_function(function):
    try:
        os.remove(outfile)
    except:
        pass

teardown_function = setup_function

def test_module_invocation():
    pipe = subprocess.Popen(['python', '-m', 'apexpy', 'geo', 'apex', '2015',
                             '--height', '300', '-i', 'tests/test_convert.txt',
                             '-o', outfile])
    pipe.communicate()
    pipe.wait()
    assert os.path.isfile(outfile)
    data = np.loadtxt(outfile)
    np.testing.assert_allclose(data, [[57.469547, 93.639816],
                                      [58.522701, 94.044762],
                                      [59.571465, 94.477257]], rtol=1e-4)

def test_convert_YYYY():
    pipe = subprocess.Popen(['python', '-m', 'apexpy', 'geo', 'apex', '2015',
                             '--height', '300', '-i', 'tests/test_convert.txt',
                             '-o', outfile])
    pipe.communicate()
    pipe.wait()
    assert os.path.isfile(outfile)
    data = np.loadtxt(outfile)
    np.testing.assert_allclose(data, [[57.469547, 93.639816],
                                      [58.522701, 94.044762],
                                      [59.571465, 94.477257]], rtol=1e-4)

def test_convert_YYYYMM():
    pipe = subprocess.Popen(['python', '-m', 'apexpy', 'geo', 'apex', '201501',
                             '--height', '300', '-i', 'tests/test_convert.txt',
                             '-o', outfile])
    pipe.communicate()
    pipe.wait()
    assert os.path.isfile(outfile)
    data = np.loadtxt(outfile)
    np.testing.assert_allclose(data, [[57.469547, 93.639816],
                                      [58.522701, 94.044762],
                                      [59.571465, 94.477257]], rtol=1e-4)

def test_convert_YYYYMMDD():
    pipe = subprocess.Popen(['python', '-m', 'apexpy', 'geo', 'apex',
                             '20150101', '--height', '300', '-i',
                             'tests/test_convert.txt', '-o', outfile])
    pipe.communicate()
    pipe.wait()
    assert os.path.isfile(outfile)
    data = np.loadtxt(outfile)
    np.testing.assert_allclose(data, [[57.469547, 93.639816],
                                      [58.522701, 94.044762],
                                      [59.571465, 94.477257]], rtol=1e-4)

def test_convert_YYYYMMDDHHMMSS():
    pipe = subprocess.Popen(['python', '-m', 'apexpy', 'geo', 'apex',
                             '20150101000000', '--height', '300', '-i',
                             'tests/test_convert.txt', '-o', outfile])
    pipe.communicate()
    pipe.wait()
    assert os.path.isfile(outfile)
    data = np.loadtxt(outfile)
    np.testing.assert_allclose(data, [[57.469547, 93.639816],
                                      [58.522701, 94.044762],
                                      [59.571465, 94.477257]], rtol=1e-4)

def test_convert_single_line():
    pipe = subprocess.Popen(['python', '-m', 'apexpy', 'geo', 'apex',
                             '20150101000000', '--height', '300', '-i',
                             'tests/test_convert_single_line.txt', '-o',
                             outfile])
    pipe.communicate()
    pipe.wait()
    assert os.path.isfile(outfile)
    data = np.loadtxt(outfile)
    np.testing.assert_allclose(data, [57.469547, 93.639816], rtol=1e-4)

def test_convert_stdin_stdout():
    """ Test use of pipe input to command-line call
    """
    pipe = subprocess.Popen('echo 60 15 | apexpy geo apex 2015 --height 300',
                            shell=True, stdout=subprocess.PIPE)
    stdout, _ = pipe.communicate()
    pipe.wait()
    np.testing.assert_allclose(np.array(stdout.split(b' '), dtype=float),
                               [57.469547, 93.639816], rtol=1e-4)

def test_convert_refh():
    pipe = subprocess.Popen(
        'echo 60 15 | apexpy geo apex 2000 --height 100 --refh=300',
        shell=True, stdout=subprocess.PIPE)
    stdout, _ = pipe.communicate()
    pipe.wait()
    np.testing.assert_allclose(np.array(stdout.split(b' '), dtype=float),
                               [55.94841766, 94.1068344], rtol=1e-4)

def test_convert_mlt():
    pipe = subprocess.Popen(['python', '-m', 'apexpy', 'geo', 'mlt',
                             '20150101000000', '--height', '300', '-i',
                             'tests/test_convert_single_line.txt', '-o',
                             outfile])
    pipe.communicate()
    pipe.wait()
    assert os.path.isfile(outfile)
    data = np.loadtxt(outfile)
    np.testing.assert_allclose(data, [57.469547, 1.06324], rtol=1e-4)

def test_invalid_date():
    pipe = subprocess.Popen('echo 60 15 | apexpy geo apex 201501010',
                            shell=True, stderr=subprocess.PIPE)
    _, stderr = pipe.communicate()
    pipe.wait()
    assert b'ValueError' in stderr

    pipe = subprocess.Popen('echo 60 15 | apexpy geo apex 2015010100000',
                            shell=True, stderr=subprocess.PIPE)
    _, stderr = pipe.communicate()
    pipe.wait()
    assert b'ValueError' in stderr

def test_mlt_nodatetime():
    pipe = subprocess.Popen('echo 60 15 | apexpy geo mlt 20150101', shell=True,
                            stderr=subprocess.PIPE)
    _, stderr = pipe.communicate()
    pipe.wait()
    assert b'ValueError' in stderr

def test_invalid_coord():
    pipe = subprocess.Popen('echo 60 15 | apexpy foobar apex 2015', shell=True,
                            stderr=subprocess.PIPE)
    _, stderr = pipe.communicate()
    pipe.wait()
    assert b'invalid choice' in stderr

    pipe = subprocess.Popen('echo 60 15 | apexpy geo foobar 2015', shell=True,
                            stderr=subprocess.PIPE)
    _, stderr = pipe.communicate()
    pipe.wait()
    assert b'invalid choice' in stderr
<|endoftext|>


<commit_before>#!/usr/bin/env python
# Copyright 2016 IBM Corp. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""
Unit tests for _cpc module.
"""

from __future__ import absolute_import

import unittest
import requests_mock

from zhmcclient import Session, Client, LparManager, PartitionManager

class CpcTests(unittest.TestCase):
    """All tests for Cpc and CpcManager classes."""

    def setUp(self):
        self.session = Session('fake-host', 'fake-user', 'fake-id')
        self.client = Client(self.session)  # contains CpcManager object
        with requests_mock.mock() as m:
            # Because logon is deferred until needed, we perform it
            # explicitly in order to keep mocking in the actual test simple.
            m.post('/api/sessions', json={'api-session': 'fake-session-id'})
            self.session.logon()

    def tearDown(self):
        with requests_mock.mock() as m:
            m.delete('/api/sessions/this-session', status_code=204)
            self.session.logoff()

    def test_init(self):
        """Test __init__() on CpcManager instance in client."""
        cpc_mgr = self.client.cpcs
        self.assertEqual(cpc_mgr.parent, None)
        self.assertTrue(cpc_mgr.session is self.session)

    def test_list_short_ok(self):
        """
        Test successful list() with short set of properties on CpcManager
        instance in client.
        """
        cpc_mgr = self.client.cpcs
        with requests_mock.mock() as m:
            result = {
                'cpcs': [
                    {
                        'object-uri': '/api/cpcs/fake-cpc-id-1',
                        'name': 'P0ZHMP02',
                        'status': 'service-required',
                    },
                    {
                        'object-uri': '/api/cpcs/fake-cpc-id-2',
                        'name': 'P0000P30',
                        'status': 'service-required',
                    }
                ]
            }
            m.get('/api/cpcs', json=result)

            cpcs = cpc_mgr.list(full_properties=False)

            self.assertEqual(len(cpcs), len(result['cpcs']))
            for idx, cpc in enumerate(cpcs):
                self.assertEqual(cpc.properties, result['cpcs'][idx])

    def test_list_full_ok(self):
        """
        Test successful list() with full set of properties on CpcManager
        instance in client.
        """
        cpc_mgr = self.client.cpcs
        with requests_mock.mock() as m:
            mock_result_cpcs = {
                'cpcs': [
                    {
                        'object-uri': '/api/cpcs/fake-cpc-id-1',
                        'name': 'P0ZHMP02',
                        'status': 'service-required',
                    },
                    {
                        'object-uri': '/api/cpcs/fake-cpc-id-2',
                        'name': 'P0000P30',
                        'status': 'service-required',
                    },
                    {
                        'object-uri': '/api/cpcs/fake-cpc-id-3',
                        'name': 'P0000OLD',
                        'status': 'enabled',
                    }
                ]
            }
            m.get('/api/cpcs', json=mock_result_cpcs)
            mock_result_cpc1 = {
                'object-uri': '/api/cpcs/fake-cpc-id-1',
                'name': 'P0ZHMP02',
                'status': 'service-required',
                'dpm-enabled': True,
                'bla': 'blub',
            }
            m.get('/api/cpcs/fake-cpc-id-1', json=mock_result_cpc1)
            mock_result_cpc2 = {
                'object-uri': '/api/cpcs/fake-cpc-id-2',
                'name': 'P0000P30',
                'status': 'service-required',
                'dpm-enabled': False,
                'bla': 'baz',
            }
            m.get('/api/cpcs/fake-cpc-id-2', json=mock_result_cpc2)
            mock_result_cpc3 = {
                'object-uri': '/api/cpcs/fake-cpc-id-3',
                'name': 'P0000OLD',
                'status': 'enabled',
                'bla': 'foo',
            }
            m.get('/api/cpcs/fake-cpc-id-3', json=mock_result_cpc3)
            result = {
                'cpcs': [
                    mock_result_cpc1,
                    mock_result_cpc2,
                    mock_result_cpc3,
                ]
            }
            dpm_enabled_result = [
                True,
                False,
                False,
            ]

            cpcs = cpc_mgr.list(full_properties=True)

            self.assertEqual(len(cpcs), len(result['cpcs']))
            for idx, cpc in enumerate(cpcs):
                self.assertEqual(cpc.properties, result['cpcs'][idx])
                self.assertEqual(cpc.dpm_enabled, dpm_enabled_result[idx])
                if dpm_enabled_result[idx]:
                    self.assertEqual(cpc.lpars, None)
                    self.assertTrue(
                        isinstance(cpc.partitions, PartitionManager))
                else:
                    self.assertEqual(cpc.partitions, None)
                    self.assertTrue(isinstance(cpc.lpars, LparManager))

if __name__ == '__main__':
    unittest.main()
<commit_msg>Updated Unit Tests because of removal of DPM checking.<commit_after>#!/usr/bin/env python
# Copyright 2016 IBM Corp. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""
Unit tests for _cpc module.
"""

from __future__ import absolute_import

import unittest
import requests_mock

from zhmcclient import Session, Client, LparManager, PartitionManager

class CpcTests(unittest.TestCase):
    """All tests for Cpc and CpcManager classes."""

    def setUp(self):
        self.session = Session('fake-host', 'fake-user', 'fake-id')
        self.client = Client(self.session)  # contains CpcManager object
        with requests_mock.mock() as m:
            # Because logon is deferred until needed, we perform it
            # explicitly in order to keep mocking in the actual test simple.
            m.post('/api/sessions', json={'api-session': 'fake-session-id'})
            self.session.logon()

    def tearDown(self):
        with requests_mock.mock() as m:
            m.delete('/api/sessions/this-session', status_code=204)
            self.session.logoff()

    def test_init(self):
        """Test __init__() on CpcManager instance in client."""
        cpc_mgr = self.client.cpcs
        self.assertEqual(cpc_mgr.parent, None)
        self.assertTrue(cpc_mgr.session is self.session)

    def test_list_short_ok(self):
        """
        Test successful list() with short set of properties on CpcManager
        instance in client.
        """
        cpc_mgr = self.client.cpcs
        with requests_mock.mock() as m:
            result = {
                'cpcs': [
                    {
                        'object-uri': '/api/cpcs/fake-cpc-id-1',
                        'name': 'P0ZHMP02',
                        'status': 'service-required',
                    },
                    {
                        'object-uri': '/api/cpcs/fake-cpc-id-2',
                        'name': 'P0000P30',
                        'status': 'service-required',
                    }
                ]
            }
            m.get('/api/cpcs', json=result)

            cpcs = cpc_mgr.list(full_properties=False)

            self.assertEqual(len(cpcs), len(result['cpcs']))
            for idx, cpc in enumerate(cpcs):
                self.assertEqual(cpc.properties, result['cpcs'][idx])

    def test_list_full_ok(self):
        """
        Test successful list() with full set of properties on CpcManager
        instance in client.
        """
        cpc_mgr = self.client.cpcs
        with requests_mock.mock() as m:
            mock_result_cpcs = {
                'cpcs': [
                    {
                        'object-uri': '/api/cpcs/fake-cpc-id-1',
                        'name': 'P0ZHMP02',
                        'status': 'service-required',
                    },
                    {
                        'object-uri': '/api/cpcs/fake-cpc-id-2',
                        'name': 'P0000P30',
                        'status': 'service-required',
                    },
                    {
                        'object-uri': '/api/cpcs/fake-cpc-id-3',
                        'name': 'P0000OLD',
                        'status': 'enabled',
                    }
                ]
            }
            m.get('/api/cpcs', json=mock_result_cpcs)
            mock_result_cpc1 = {
                'object-uri': '/api/cpcs/fake-cpc-id-1',
                'name': 'P0ZHMP02',
                'status': 'service-required',
                'dpm-enabled': True,
                'bla': 'blub',
            }
            m.get('/api/cpcs/fake-cpc-id-1', json=mock_result_cpc1)
            mock_result_cpc2 = {
                'object-uri': '/api/cpcs/fake-cpc-id-2',
                'name': 'P0000P30',
                'status': 'service-required',
                'dpm-enabled': False,
                'bla': 'baz',
            }
            m.get('/api/cpcs/fake-cpc-id-2', json=mock_result_cpc2)
            mock_result_cpc3 = {
                'object-uri': '/api/cpcs/fake-cpc-id-3',
                'name': 'P0000OLD',
                'status': 'enabled',
                'bla': 'foo',
            }
            m.get('/api/cpcs/fake-cpc-id-3', json=mock_result_cpc3)
            result = {
                'cpcs': [
                    mock_result_cpc1,
                    mock_result_cpc2,
                    mock_result_cpc3,
                ]
            }
            dpm_enabled_result = [
                True,
                False,
                False,
            ]

            cpcs = cpc_mgr.list(full_properties=True)

            self.assertEqual(len(cpcs), len(result['cpcs']))
            for idx, cpc in enumerate(cpcs):
                self.assertEqual(cpc.properties, result['cpcs'][idx])
                self.assertEqual(cpc.dpm_enabled, dpm_enabled_result[idx])
                if dpm_enabled_result[idx]:
                    self.assertTrue(
                        isinstance(cpc.partitions, PartitionManager))
                else:
                    self.assertTrue(isinstance(cpc.lpars, LparManager))

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


<commit_before>from datetime import (
    datetime,
    timedelta,
)
from mock import (
    Mock,
    patch,
)
from argparse import Namespace

import pytz

from tests import TestCase
import gce

GCE_ENVIRON = {
    'GCE_SA_EMAIL': 'me@serviceaccount.google.com',
    'GCE_PEM_PATH': '/gce-serveraccount.json',
    'GCE_PROJECT_ID': 'test-project',
}

def make_fake_client():
    client = Mock(['list_nodes', 'destroy_node'])
    return client

class GCETestCase(TestCase):

    test_environ = GCE_ENVIRON

    def test_main_list_instances(self):
        client = make_fake_client()
        with patch('gce.get_client', autospec=True,
                   return_value=client) as gc_mock:
            with patch('gce.list_instances', autospec=True) as li_mock:
                with patch.dict('os.environ', GCE_ENVIRON):
                    code = gce.main(
                        ['gce.py', 'list-instances', 'juju-deploy*'])
        self.assertEqual(0, code)
        gc_mock.assert_called_once_with(
            GCE_ENVIRON['GCE_SA_EMAIL'], GCE_ENVIRON['GCE_PEM_PATH'],
            GCE_ENVIRON['GCE_PROJECT_ID'])
        li_mock.assert_called_once_with(
            client, glob='juju-deploy*', print_out=True)

    def test_main_delete_instance(self):
        client = make_fake_client()
        with patch('gce.get_client', autospec=True,
                   return_value=client) as gc_mock:
            with patch('gce.delete_instances', autospec=True) as di_mock:
                with patch.dict('os.environ', GCE_ENVIRON):
                    code = gce.main(
                        ['gce.py', 'delete-instances', '-o', '2',
                         'juju-deploy*'])
        self.assertEqual(0, code)
        gc_mock.assert_called_once_with(
            GCE_ENVIRON['GCE_SA_EMAIL'], GCE_ENVIRON['GCE_PEM_PATH'],
            GCE_ENVIRON['GCE_PROJECT_ID'])
        di_mock.assert_called_once_with(
            client, 'juju-deploy*', old_age=2, dry_run=False)

    def test_parse_args_delete_instaces(self):
        with patch.dict('os.environ', GCE_ENVIRON):
            args = gce.parse_args(
                ['gce.py', '-v', '-d',
                 'delete-instances', '-o', '2', 'juju-deploy*'])
        expected = Namespace(
            command='delete-instances', dry_run=True, filter='juju-deploy*',
            old_age=2, pem_path='/gce-serveraccount.json',
            project_id='test-project', sa_email='me@serviceaccount.google.com',
            verbose=10)
        self.assertEqual(expected, args)

    def test_parse_args_list_instances(self):
        with patch.dict('os.environ', GCE_ENVIRON):
            args = gce.parse_args(
                ['gce.py', '-v', '-d', 'list-instances', 'juju-deploy*'])
        expected = Namespace(
            command='list-instances', dry_run=True, filter='juju-deploy*',
            pem_path='/gce-serveraccount.json',
            project_id='test-project', sa_email='me@serviceaccount.google.com',
            verbose=10)
        self.assertEqual(expected, args)

    def test_parse_args_without_env(self):
        args = gce.parse_args(
            ['gce.py', '-v', '-d',
             '--sa-email', 'me@serviceaccount.google.com',
             '--pem-path', '/gce-serveraccount.json',
             '--project-id', 'test-project',
             'delete-instances', '-o', '2', 'juju-deploy*'])
        expected = Namespace(
            command='delete-instances', dry_run=True, filter='juju-deploy*',
            old_age=2, pem_path='/gce-serveraccount.json',
            project_id='test-project', sa_email='me@serviceaccount.google.com',
            verbose=10)
        self.assertEqual(expected, args)

    def test_is_permanent_true(self):
        node = Mock(extra={'tags': ['permanent', 'bingo']})
        self.assertIsTrue(gce.is_permanent(node))

    def test_is_permanent_false(self):
        node = Mock(extra={'tags': ['bingo']})
        self.assertIsFalse(gce.is_permanent(node))

    def test_is_permanent_no_tags(self):
        node = Mock(extra={})
        self.assertIsFalse(gce.is_permanent(node))

    # def test_list_instances(self):
    #     client = make_fake_client()
    #     client.init_services()
    #     groups = [ResourceGroup('juju-foo-0'), ResourceGroup('juju-bar-1')]
    #     client.resource.resource_groups.list.return_value = groups
    #     result = list_instances(client, 'juju-bar*')
    #     rgd = ResourceGroupDetails(client, groups[-1])
    #     self.assertEqual([rgd], result)
    #     client.resource.resource_groups.list.assert_called_once_with()

    # def test_list_instances_ignore_default(self):
    #     # Default resources are created by Azure. They should only be
    #     # seen via the UI. A glob for everything will still ignore defaults.
    #     client = make_fake_client()
    #     client.init_services()
    #     groups = [ResourceGroup('{}-network'.format(DEFAULT_RESOURCE_PREFIX))]
    #     client.resource.resource_groups.list.return_value = groups
    #     result = list_instances(client, '*')
    #     self.assertEqual([], result)

    # def test_delete_instances_found_old(self):
    #     now = datetime.now(tz=pytz.utc)
    #     client = make_fake_client()
    #     client.init_services()
    #     group = ResourceGroup('juju-bar-1')
    #     client.resource.resource_groups.list.return_value = [group]
    #     # The resource_groups's storage_account is 4 hours old.
    #     storage_account = StorageAccount('abcd-12', now - timedelta(hours=4))
    #     client.storage.storage_accounts.list_by_resource_group.return_value = [
    #         storage_account]
    #     poller = FakePoller()
    #     client.resource.resource_groups.delete.return_value = poller
    #     # Delete resource groups that are 2 hours old.
    #     count = delete_instances(client, 'juju-bar*', old_age=2, now=now)
    #     self.assertEqual(1, count)
    #     client.resource.resource_groups.delete.assert_called_once_with(
    #         'juju-bar-1')
    #     self.assertIs(True, poller.is_done)

    # def test_delete_instances_not_found_old(self):
    #     now = datetime.now(tz=pytz.utc)
    #     client = make_fake_client()
    #     client.init_services()
    #     group = ResourceGroup('juju-bar-1')
    #     client.resource.resource_groups.list.return_value = [group]
    #     # The resource_groups's storage_account is 2 hours old.
    #     storage_account = StorageAccount('abcd-12', now - timedelta(hours=2))
    #     client.storage.storage_accounts.list_by_resource_group.return_value = [
    #         storage_account]
    #     # Delete resource groups that are 8 hours old.
    #     count = delete_instances(client, 'juju-bar*', old_age=8, now=now)
    #     self.assertEqual(0, count)
    #     self.assertEqual(0, client.resource.resource_groups.delete.call_count)

    # def test_delete_instances_read_only(self):
    #     now = datetime.now(tz=pytz.utc)
    #     client = ARMClient(
    #         'subscription_id', 'client_id', 'secret', 'tenant', read_only=True)
    #     client.init_services()
    #     group = ResourceGroup('juju-bar-1')
    #     client.resource.resource_groups.list.return_value = [group]
    #     # The resource_groups's storage_account is 4 hours old.
    #     storage_account = StorageAccount('abcd-12', now - timedelta(hours=4))
    #     client.storage.storage_accounts.list_by_resource_group.return_value = [
    #         storage_account]
    #     count = delete_instances(client, 'juju-bar*', old_age=2, now=now)
    #     self.assertEqual(0, count)
    #     self.assertEqual(0, client.resource.resource_groups.delete.call_count)

    # def test_delete_instances_old_age_0(self):
    #     now = datetime.now(tz=pytz.utc)
    #     client = make_fake_client()
    #     client.init_services()
    #     a_group = ResourceGroup('juju-bar-1')
    #     b_group = ResourceGroup('juju-foo-0')
    #     client.resource.resource_groups.list.return_value = [a_group, b_group]
    #     poller = FakePoller()
    #     client.resource.resource_groups.delete.return_value = poller
    #     # Delete resource groups that are 0 hours old.
    #     # All matched resource_groups are deleted
    #     count = delete_instances(client, 'juju-bar*', old_age=0, now=now)
    #     self.assertEqual(1, count)
    #     self.assertEqual(1, client.resource.resource_groups.delete.call_count)
    #     self.assertIs(True, poller.is_done)

    # def test_delete_instance_with_id(self):
    #     client = make_fake_client()
    #     client.init_services()
    #     poller = FakePoller()
    #     client.compute.virtual_machines.delete.return_value = poller
    #     vm1 = VirtualMachine('name-0', 'id-a')
    #     rgd1 = ResourceGroupDetails(client, ResourceGroup('one'), vms=[vm1])
    #     vm2 = VirtualMachine('name-0', 'id-b')
    #     rgd2 = ResourceGroupDetails(client, ResourceGroup('two'), vms=[vm2])
    #     with patch('gce.list_instances', autospec=True,
    #                return_value=[rgd1, rgd2]) as lr_mock:
    #         # Passing just an id will take the * glob path.
    #         delete_instance(client, 'id-a')
    #     lr_mock.assert_called_once_with(client, glob='*', recursive=True)
    #     client.compute.virtual_machines.delete.assert_called_once_with(
    #         'one', 'name-0')
    #     self.assertIs(True, poller.is_done)

    # def test_delete_instance_without_match(self):
    #     client = make_fake_client()
    #     client.init_services()
    #     vm1 = VirtualMachine('name-0', 'id-a')
    #     rgd1 = ResourceGroupDetails(client, ResourceGroup('one'), vms=[vm1])
    #     with patch('gce.list_instances', autospec=True,
    #                return_value=[rgd1]):
    #         # Passing an non-existent id bypasses the call to delete.
    #         with self.assertRaises(ValueError):
    #             delete_instance(client, 'id-z')
    #     self.assertEqual(0, client.compute.virtual_machines.delete.call_count)
<commit_msg>Added test for is_young<commit_after>from datetime import (
    datetime,
    timedelta,
)
from mock import (
    Mock,
    patch,
)
from argparse import Namespace

import pytz

from tests import TestCase
import gce

GCE_ENVIRON = {
    'GCE_SA_EMAIL': 'me@serviceaccount.google.com',
    'GCE_PEM_PATH': '/gce-serveraccount.json',
    'GCE_PROJECT_ID': 'test-project',
}

def make_fake_client():
    client = Mock(['list_nodes', 'destroy_node'])
    return client

class GCETestCase(TestCase):

    test_environ = GCE_ENVIRON

    def test_main_list_instances(self):
        client = make_fake_client()
        with patch('gce.get_client', autospec=True,
                   return_value=client) as gc_mock:
            with patch('gce.list_instances', autospec=True) as li_mock:
                with patch.dict('os.environ', GCE_ENVIRON):
                    code = gce.main(
                        ['gce.py', 'list-instances', 'juju-deploy*'])
        self.assertEqual(0, code)
        gc_mock.assert_called_once_with(
            GCE_ENVIRON['GCE_SA_EMAIL'], GCE_ENVIRON['GCE_PEM_PATH'],
            GCE_ENVIRON['GCE_PROJECT_ID'])
        li_mock.assert_called_once_with(
            client, glob='juju-deploy*', print_out=True)

    def test_main_delete_instance(self):
        client = make_fake_client()
        with patch('gce.get_client', autospec=True,
                   return_value=client) as gc_mock:
            with patch('gce.delete_instances', autospec=True) as di_mock:
                with patch.dict('os.environ', GCE_ENVIRON):
                    code = gce.main(
                        ['gce.py', 'delete-instances', '-o', '2',
                         'juju-deploy*'])
        self.assertEqual(0, code)
        gc_mock.assert_called_once_with(
            GCE_ENVIRON['GCE_SA_EMAIL'], GCE_ENVIRON['GCE_PEM_PATH'],
            GCE_ENVIRON['GCE_PROJECT_ID'])
        di_mock.assert_called_once_with(
            client, 'juju-deploy*', old_age=2, dry_run=False)

    def test_parse_args_delete_instaces(self):
        with patch.dict('os.environ', GCE_ENVIRON):
            args = gce.parse_args(
                ['gce.py', '-v', '-d',
                 'delete-instances', '-o', '2', 'juju-deploy*'])
        expected = Namespace(
            command='delete-instances', dry_run=True, filter='juju-deploy*',
            old_age=2, pem_path='/gce-serveraccount.json',
            project_id='test-project', sa_email='me@serviceaccount.google.com',
            verbose=10)
        self.assertEqual(expected, args)

    def test_parse_args_list_instances(self):
        with patch.dict('os.environ', GCE_ENVIRON):
            args = gce.parse_args(
                ['gce.py', '-v', '-d', 'list-instances', 'juju-deploy*'])
        expected = Namespace(
            command='list-instances', dry_run=True, filter='juju-deploy*',
            pem_path='/gce-serveraccount.json',
            project_id='test-project', sa_email='me@serviceaccount.google.com',
            verbose=10)
        self.assertEqual(expected, args)

    def test_parse_args_without_env(self):
        args = gce.parse_args(
            ['gce.py', '-v', '-d',
             '--sa-email', 'me@serviceaccount.google.com',
             '--pem-path', '/gce-serveraccount.json',
             '--project-id', 'test-project',
             'delete-instances', '-o', '2', 'juju-deploy*'])
        expected = Namespace(
            command='delete-instances', dry_run=True, filter='juju-deploy*',
            old_age=2, pem_path='/gce-serveraccount.json',
            project_id='test-project', sa_email='me@serviceaccount.google.com',
            verbose=10)
        self.assertEqual(expected, args)

    def test_is_permanent_true(self):
        node = Mock(extra={'tags': ['permanent', 'bingo']})
        self.assertIsTrue(gce.is_permanent(node))

    def test_is_permanent_false(self):
        node = Mock(extra={'tags': ['bingo']})
        self.assertIsFalse(gce.is_permanent(node))

    def test_is_permanent_no_tags(self):
        node = Mock(extra={})
        self.assertIsFalse(gce.is_permanent(node))

    def test_is_young_no_created(self):
        node = Mock(extra={})
        self.assertIsTrue(gce.is_young(node, gce.OLD_MACHINE_AGE))

    # def test_list_instances(self):
    #     client = make_fake_client()
    #     client.init_services()
    #     groups = [ResourceGroup('juju-foo-0'), ResourceGroup('juju-bar-1')]
    #     client.resource.resource_groups.list.return_value = groups
    #     result = list_instances(client, 'juju-bar*')
    #     rgd = ResourceGroupDetails(client, groups[-1])
    #     self.assertEqual([rgd], result)
    #     client.resource.resource_groups.list.assert_called_once_with()

    # def test_list_instances_ignore_default(self):
    #     # Default resources are created by Azure. They should only be
    #     # seen via the UI. A glob for everything will still ignore defaults.
    #     client = make_fake_client()
    #     client.init_services()
    #     groups = [ResourceGroup('{}-network'.format(DEFAULT_RESOURCE_PREFIX))]
    #     client.resource.resource_groups.list.return_value = groups
    #     result = list_instances(client, '*')
    #     self.assertEqual([], result)

    # def test_delete_instances_found_old(self):
    #     now = datetime.now(tz=pytz.utc)
    #     client = make_fake_client()
    #     client.init_services()
    #     group = ResourceGroup('juju-bar-1')
    #     client.resource.resource_groups.list.return_value = [group]
    #     # The resource_groups's storage_account is 4 hours old.
    #     storage_account = StorageAccount('abcd-12', now - timedelta(hours=4))
    #     client.storage.storage_accounts.list_by_resource_group.return_value = [
    #         storage_account]
    #     poller = FakePoller()
    #     client.resource.resource_groups.delete.return_value = poller
    #     # Delete resource groups that are 2 hours old.
    #     count = delete_instances(client, 'juju-bar*', old_age=2, now=now)
    #     self.assertEqual(1, count)
    #     client.resource.resource_groups.delete.assert_called_once_with(
    #         'juju-bar-1')
    #     self.assertIs(True, poller.is_done)

    # def test_delete_instances_not_found_old(self):
    #     now = datetime.now(tz=pytz.utc)
    #     client = make_fake_client()
    #     client.init_services()
    #     group = ResourceGroup('juju-bar-1')
    #     client.resource.resource_groups.list.return_value = [group]
    #     # The resource_groups's storage_account is 2 hours old.
    #     storage_account = StorageAccount('abcd-12', now - timedelta(hours=2))
    #     client.storage.storage_accounts.list_by_resource_group.return_value = [
    #         storage_account]
    #     # Delete resource groups that are 8 hours old.
    #     count = delete_instances(client, 'juju-bar*', old_age=8, now=now)
    #     self.assertEqual(0, count)
    #     self.assertEqual(0, client.resource.resource_groups.delete.call_count)

    # def test_delete_instances_read_only(self):
    #     now = datetime.now(tz=pytz.utc)
    #     client = ARMClient(
    #         'subscription_id', 'client_id', 'secret', 'tenant', read_only=True)
    #     client.init_services()
    #     group = ResourceGroup('juju-bar-1')
    #     client.resource.resource_groups.list.return_value = [group]
    #     # The resource_groups's storage_account is 4 hours old.
    #     storage_account = StorageAccount('abcd-12', now - timedelta(hours=4))
    #     client.storage.storage_accounts.list_by_resource_group.return_value = [
    #         storage_account]
    #     count = delete_instances(client, 'juju-bar*', old_age=2, now=now)
    #     self.assertEqual(0, count)
    #     self.assertEqual(0, client.resource.resource_groups.delete.call_count)

    # def test_delete_instances_old_age_0(self):
    #     now = datetime.now(tz=pytz.utc)
    #     client = make_fake_client()
    #     client.init_services()
    #     a_group = ResourceGroup('juju-bar-1')
    #     b_group = ResourceGroup('juju-foo-0')
    #     client.resource.resource_groups.list.return_value = [a_group, b_group]
    #     poller = FakePoller()
    #     client.resource.resource_groups.delete.return_value = poller
    #     # Delete resource groups that are 0 hours old.
    #     # All matched resource_groups are deleted
    #     count = delete_instances(client, 'juju-bar*', old_age=0, now=now)
    #     self.assertEqual(1, count)
    #     self.assertEqual(1, client.resource.resource_groups.delete.call_count)
    #     self.assertIs(True, poller.is_done)

    # def test_delete_instance_with_id(self):
    #     client = make_fake_client()
    #     client.init_services()
    #     poller = FakePoller()
    #     client.compute.virtual_machines.delete.return_value = poller
    #     vm1 = VirtualMachine('name-0', 'id-a')
    #     rgd1 = ResourceGroupDetails(client, ResourceGroup('one'), vms=[vm1])
    #     vm2 = VirtualMachine('name-0', 'id-b')
    #     rgd2 = ResourceGroupDetails(client, ResourceGroup('two'), vms=[vm2])
    #     with patch('gce.list_instances', autospec=True,
    #                return_value=[rgd1, rgd2]) as lr_mock:
    #         # Passing just an id will take the * glob path.
    #         delete_instance(client, 'id-a')
    #     lr_mock.assert_called_once_with(client, glob='*', recursive=True)
    #     client.compute.virtual_machines.delete.assert_called_once_with(
    #         'one', 'name-0')
    #     self.assertIs(True, poller.is_done)

    # def test_delete_instance_without_match(self):
    #     client = make_fake_client()
    #     client.init_services()
    #     vm1 = VirtualMachine('name-0', 'id-a')
    #     rgd1 = ResourceGroupDetails(client, ResourceGroup('one'), vms=[vm1])
    #     with patch('gce.list_instances', autospec=True,
    #                return_value=[rgd1]):
    #         # Passing an non-existent id bypasses the call to delete.
    #         with self.assertRaises(ValueError):
    #             delete_instance(client, 'id-z')
    #     self.assertEqual(0, client.compute.virtual_machines.delete.call_count)
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
"""Tests for libvcs git repos."""
from __future__ import absolute_import, print_function, unicode_literals

import datetime
import os
import re
import textwrap

import pytest

from libvcs import exc
from libvcs._compat import string_types
from libvcs.git import GitRemote, GitRepo
from libvcs.shortcuts import create_repo_from_pip_url
from libvcs.util import run, which

if not which('git'):
    pytestmark = pytest.mark.skip(reason="git is not available")

def test_repo_git_obtain_initial_commit_repo(tmpdir):
    """initial commit repos return 'initial'.

    note: this behaviors differently from git(1)'s use of the word "bare".
    running `git rev-parse --is-bare-repository` would return false.
    """
    repo_name = 'my_git_project'

    run(['git', 'init', repo_name], cwd=str(tmpdir))

    bare_repo_dir = tmpdir.join(repo_name)

    git_repo = create_repo_from_pip_url(
        **{
            'pip_url': 'git+file://' + str(bare_repo_dir),
            'repo_dir': str(tmpdir.join('obtaining a bare repo')),
        }
    )

    git_repo.obtain()
    assert git_repo.get_revision() == 'initial'

def test_repo_git_obtain_full(tmpdir, git_remote):
    git_repo = create_repo_from_pip_url(
        **{
            'pip_url': 'git+file://' + git_remote,
            'repo_dir': str(tmpdir.join('myrepo')),
        }
    )

    git_repo.obtain()

    test_repo_revision = run(['git', 'rev-parse', 'HEAD'], cwd=git_remote)

    assert git_repo.get_revision() == test_repo_revision
    assert os.path.exists(str(tmpdir.join('myrepo')))

def test_repo_update_handle_cases(tmpdir, git_remote, mocker):
    git_repo = create_repo_from_pip_url(
        **{
            'pip_url': 'git+file://' + git_remote,
            'repo_dir': str(tmpdir.join('myrepo')),
        }
    )

    git_repo.obtain()  # clone initial repo
    mocka = mocker.spy(git_repo, 'run')
    git_repo.update_repo()

    mocka.assert_any_call(['symbolic-ref', '--short', 'HEAD'])

    mocka.reset_mock()

    # will only look up symbolic-ref if no rev specified for object
    git_repo.rev = 'HEAD'
    git_repo.update_repo()
    assert mocker.call(['symbolic-ref', '--short', 'HEAD']) not in mocka.mock_calls

def test_progress_callback(tmpdir, git_remote, mocker):
    def progress_callback_spy(output, timestamp):
        assert isinstance(output, string_types)
        assert isinstance(timestamp, datetime.datetime)

    progress_callback = mocker.Mock(
        name='progress_callback_stub', side_effect=progress_callback_spy
    )

    run(['git', 'rev-parse', 'HEAD'], cwd=git_remote)

    # create a new repo with the repo as a remote
    git_repo = create_repo_from_pip_url(
        **{
            'pip_url': 'git+file://' + git_remote,
            'repo_dir': str(tmpdir.join('myrepo')),
            'progress_callback': progress_callback,
        }
    )
    git_repo.obtain()

    assert progress_callback.called

def test_remotes(parentdir, git_remote):
    repo_name = 'myrepo'
    remote_name = 'myremote'
    remote_url = 'https://localhost/my/git/repo.git'

    git_repo = create_repo_from_pip_url(
        pip_url='git+file://{git_remote}'.format(git_remote=git_remote),
        repo_dir=os.path.join(str(parentdir), repo_name),
    )
    git_repo.obtain()
    git_repo.set_remote(name=remote_name, url=remote_url)

    assert (remote_name, remote_url, remote_url) == git_repo.remote(remote_name)

def test_git_get_url_and_rev_from_pip_url():
    pip_url = 'git+ssh://git@bitbucket.example.com:7999/PROJ/repo.git'
    url, rev = GitRepo.get_url_and_revision_from_pip_url(pip_url)
    assert 'ssh://git@bitbucket.example.com:7999/PROJ/repo.git' == url
    assert rev is None

    pip_url = '%s@%s' % (
        'git+ssh://git@bitbucket.example.com:7999/PROJ/repo.git',
        'eucalyptus',
    )
    url, rev = GitRepo.get_url_and_revision_from_pip_url(pip_url)
    assert 'ssh://git@bitbucket.example.com:7999/PROJ/repo.git' == url
    assert rev == 'eucalyptus'

    # the git manual refers to this as "scp-like syntax"
    # https://git-scm.com/docs/git-clone
    pip_url = '%s@%s' % ('git+user@hostname:user/repo.git', 'eucalyptus')
    url, rev = GitRepo.get_url_and_revision_from_pip_url(pip_url)
    assert 'user@hostname:user/repo.git' == url
    assert rev == 'eucalyptus'

def test_remotes_preserves_git_ssh(parentdir, git_remote):
    # Regression test for #14
    repo_name = 'myexamplegit'
    repo_dir = os.path.join(str(parentdir), repo_name)
    remote_name = 'myremote'
    remote_url = 'git+ssh://git@github.com/tony/AlgoXY.git'

    git_repo = create_repo_from_pip_url(
        pip_url='git+file://{git_remote}'.format(git_remote=git_remote),
        repo_dir=repo_dir,
    )
    git_repo.obtain()
    git_repo.set_remote(name=remote_name, url=remote_url)

    assert (
        GitRemote(remote_name, remote_url, remote_url)._asdict()
        in git_repo.remotes().values()
    )

def test_private_ssh_format(pip_url_kwargs):
    pip_url_kwargs.update(
        **{'pip_url': 'git+ssh://github.com:' + '/tmp/omg/private_ssh_repo'}
    )

    with pytest.raises(exc.LibVCSException) as excinfo:
        create_repo_from_pip_url(**pip_url_kwargs)
    excinfo.match(r'is malformatted')

def test_ls_remotes(git_repo):
    remotes = git_repo.remotes()

    assert 'origin' in remotes
    assert 'origin' in git_repo.remotes(flat=True)

def test_get_remotes(git_repo):
    assert 'origin' in git_repo.remotes()

@pytest.mark.parametrize('repo_name,new_repo_url', [['myrepo', 'file:///apples'],])
def test_set_remote(git_repo, repo_name, new_repo_url):
    mynewremote = git_repo.set_remote(name=repo_name, url='file:///')

    assert 'file:///' in mynewremote, 'set_remote returns remote'

    assert 'file:///' in git_repo.remote(name=repo_name), 'remote returns remote'

    assert 'myrepo' in git_repo.remotes(), '.remotes() returns new remote'

    with pytest.raises(
        exc.CommandError,
        match='.*remote {repo_name} already exists.*'.format(repo_name=repo_name),
    ):
        mynewremote = git_repo.set_remote(name='myrepo', url=new_repo_url)

    mynewremote = git_repo.set_remote(name='myrepo', url=new_repo_url, overwrite=True)

    assert new_repo_url in git_repo.remote(
        name='myrepo'
    ), 'Running remove_set should overwrite previous remote'

def extract_status(value):
    """Returns `git status -sb --porcelain=2` extracted to a dict"""
    pattern = re.compile(
        r"""[\n\r]?
        (
            #
            \W+
            branch.oid\W+
            (?P<branch_oid>
                [a-f0-9]{40}
            )
        )?
        (
            #
            \W+
            branch.head
            [\W]+
            (?P<branch_head>
                [\w-]*
            )

        )?
        (
            #
            \W+
            branch.upstream
            [\W]+
            (?P<branch_upstream>
                [/\w-]*
            )
        )?
        (
            #
            \W+
            branch.ab
            [\W]+
            (?P<branch_ab>
                \+(?P<branch_ahead>\d+)
                \W{1}
                \-(?P<branch_behind>\d+)
            )
        )?
        """,
        re.VERBOSE | re.MULTILINE,
    )
    matches = pattern.search(value)
    return matches.groupdict()

def test_extract_status():
    FIXTURE_A = textwrap.dedent(
        """
        # branch.oid d4ccd4d6af04b53949f89fbf0cdae13719dc5a08
        # branch.head fix-current-remote-name
        1 .M N... 100644 100644 100644 91082f119279b6f105ee9a5ce7795b3bdbe2b0de 91082f119279b6f105ee9a5ce7795b3bdbe2b0de CHANGES
    """  # NOQA: E501
    )
    assert {
        "branch_oid": 'd4ccd4d6af04b53949f89fbf0cdae13719dc5a08',
        "branch_head": 'fix-current-remote-name',
    }.items() <= extract_status(FIXTURE_A).items()

@pytest.mark.parametrize(
    'fixture,expected_result',
    [
        [
            """
        # branch.oid de6185fde0806e5c7754ca05676325a1ea4d6348
        # branch.head fix-current-remote-name
        # branch.upstream origin/fix-current-remote-name
        # branch.ab +0 -0
        1 .M N... 100644 100644 100644 91082f119279b6f105ee9a5ce7795b3bdbe2b0de 91082f119279b6f105ee9a5ce7795b3bdbe2b0de CHANGES
        1 .M N... 100644 100644 100644 302ca2c18d4c295ce217bff5f93e1ba342dc6665 302ca2c18d4c295ce217bff5f93e1ba342dc6665 tests/test_git.py
    """,  # NOQA: E501
            {
                "branch_oid": 'de6185fde0806e5c7754ca05676325a1ea4d6348',
                "branch_head": 'fix-current-remote-name',
                "branch_upstream": 'origin/fix-current-remote-name',
                "branch_ab": '+0 -0',
                "branch_ahead": '0',
                "branch_behind": '0',
            },
        ],
        [
            '# branch.upstream moo/origin/myslash/remote',
            {"branch_upstream": 'moo/origin/myslash/remote',},
        ],
    ],
)
def test_extract_status_b(fixture, expected_result):
    assert expected_result.items() <= extract_status(textwrap.dedent(fixture)).items()

@pytest.mark.parametrize(
    'fixture,expected_result',
    [
        [
            '# branch.ab +1 -83',
            {"branch_ab": '+1 -83', "branch_ahead": '1', "branch_behind": '83',},
        ],
        [
            """
            # branch.ab +0 -0
            """,
            {"branch_ab": '+0 -0', "branch_ahead": '0', "branch_behind": '0',},
        ],
        [
            """
            # branch.ab +1 -83
            """,
            {"branch_ab": '+1 -83', "branch_ahead": '1', "branch_behind": '83',},
        ],
        [
            """
            # branch.ab +9999999 -9999999
            """,
            {
                "branch_ab": '+9999999 -9999999',
                "branch_ahead": '9999999',
                "branch_behind": '9999999',
            },
        ],
    ],
)
def test_extract_status_c(fixture, expected_result):
    assert expected_result.items() <= extract_status(textwrap.dedent(fixture)).items()
<commit_msg>More test<commit_after># -*- coding: utf-8 -*-
"""Tests for libvcs git repos."""
from __future__ import absolute_import, print_function, unicode_literals

import datetime
import os
import textwrap

import pytest

from libvcs import exc
from libvcs._compat import string_types
from libvcs.git import GitRemote, GitRepo, extract_status
from libvcs.shortcuts import create_repo_from_pip_url
from libvcs.util import run, which

if not which('git'):
    pytestmark = pytest.mark.skip(reason="git is not available")

def test_repo_git_obtain_initial_commit_repo(tmpdir):
    """initial commit repos return 'initial'.

    note: this behaviors differently from git(1)'s use of the word "bare".
    running `git rev-parse --is-bare-repository` would return false.
    """
    repo_name = 'my_git_project'

    run(['git', 'init', repo_name], cwd=str(tmpdir))

    bare_repo_dir = tmpdir.join(repo_name)

    git_repo = create_repo_from_pip_url(
        **{
            'pip_url': 'git+file://' + str(bare_repo_dir),
            'repo_dir': str(tmpdir.join('obtaining a bare repo')),
        }
    )

    git_repo.obtain()
    assert git_repo.get_revision() == 'initial'

def test_repo_git_obtain_full(tmpdir, git_remote):
    git_repo = create_repo_from_pip_url(
        **{
            'pip_url': 'git+file://' + git_remote,
            'repo_dir': str(tmpdir.join('myrepo')),
        }
    )

    git_repo.obtain()

    test_repo_revision = run(['git', 'rev-parse', 'HEAD'], cwd=git_remote)

    assert git_repo.get_revision() == test_repo_revision
    assert os.path.exists(str(tmpdir.join('myrepo')))

def test_repo_update_handle_cases(tmpdir, git_remote, mocker):
    git_repo = create_repo_from_pip_url(
        **{
            'pip_url': 'git+file://' + git_remote,
            'repo_dir': str(tmpdir.join('myrepo')),
        }
    )

    git_repo.obtain()  # clone initial repo
    mocka = mocker.spy(git_repo, 'run')
    git_repo.update_repo()

    mocka.assert_any_call(['symbolic-ref', '--short', 'HEAD'])

    mocka.reset_mock()

    # will only look up symbolic-ref if no rev specified for object
    git_repo.rev = 'HEAD'
    git_repo.update_repo()
    assert mocker.call(['symbolic-ref', '--short', 'HEAD']) not in mocka.mock_calls

def test_progress_callback(tmpdir, git_remote, mocker):
    def progress_callback_spy(output, timestamp):
        assert isinstance(output, string_types)
        assert isinstance(timestamp, datetime.datetime)

    progress_callback = mocker.Mock(
        name='progress_callback_stub', side_effect=progress_callback_spy
    )

    run(['git', 'rev-parse', 'HEAD'], cwd=git_remote)

    # create a new repo with the repo as a remote
    git_repo = create_repo_from_pip_url(
        **{
            'pip_url': 'git+file://' + git_remote,
            'repo_dir': str(tmpdir.join('myrepo')),
            'progress_callback': progress_callback,
        }
    )
    git_repo.obtain()

    assert progress_callback.called

def test_remotes(parentdir, git_remote):
    repo_name = 'myrepo'
    remote_name = 'myremote'
    remote_url = 'https://localhost/my/git/repo.git'

    git_repo = create_repo_from_pip_url(
        pip_url='git+file://{git_remote}'.format(git_remote=git_remote),
        repo_dir=os.path.join(str(parentdir), repo_name),
    )
    git_repo.obtain()
    git_repo.set_remote(name=remote_name, url=remote_url)

    assert (remote_name, remote_url, remote_url) == git_repo.remote(remote_name)

def test_git_get_url_and_rev_from_pip_url():
    pip_url = 'git+ssh://git@bitbucket.example.com:7999/PROJ/repo.git'
    url, rev = GitRepo.get_url_and_revision_from_pip_url(pip_url)
    assert 'ssh://git@bitbucket.example.com:7999/PROJ/repo.git' == url
    assert rev is None

    pip_url = '%s@%s' % (
        'git+ssh://git@bitbucket.example.com:7999/PROJ/repo.git',
        'eucalyptus',
    )
    url, rev = GitRepo.get_url_and_revision_from_pip_url(pip_url)
    assert 'ssh://git@bitbucket.example.com:7999/PROJ/repo.git' == url
    assert rev == 'eucalyptus'

    # the git manual refers to this as "scp-like syntax"
    # https://git-scm.com/docs/git-clone
    pip_url = '%s@%s' % ('git+user@hostname:user/repo.git', 'eucalyptus')
    url, rev = GitRepo.get_url_and_revision_from_pip_url(pip_url)
    assert 'user@hostname:user/repo.git' == url
    assert rev == 'eucalyptus'

def test_remotes_preserves_git_ssh(parentdir, git_remote):
    # Regression test for #14
    repo_name = 'myexamplegit'
    repo_dir = os.path.join(str(parentdir), repo_name)
    remote_name = 'myremote'
    remote_url = 'git+ssh://git@github.com/tony/AlgoXY.git'

    git_repo = create_repo_from_pip_url(
        pip_url='git+file://{git_remote}'.format(git_remote=git_remote),
        repo_dir=repo_dir,
    )
    git_repo.obtain()
    git_repo.set_remote(name=remote_name, url=remote_url)

    assert (
        GitRemote(remote_name, remote_url, remote_url)._asdict()
        in git_repo.remotes().values()
    )

def test_private_ssh_format(pip_url_kwargs):
    pip_url_kwargs.update(
        **{'pip_url': 'git+ssh://github.com:' + '/tmp/omg/private_ssh_repo'}
    )

    with pytest.raises(exc.LibVCSException) as excinfo:
        create_repo_from_pip_url(**pip_url_kwargs)
    excinfo.match(r'is malformatted')

def test_ls_remotes(git_repo):
    remotes = git_repo.remotes()

    assert 'origin' in remotes
    assert 'origin' in git_repo.remotes(flat=True)

def test_get_remotes(git_repo):
    assert 'origin' in git_repo.remotes()

@pytest.mark.parametrize('repo_name,new_repo_url', [['myrepo', 'file:///apples'],])
def test_set_remote(git_repo, repo_name, new_repo_url):
    mynewremote = git_repo.set_remote(name=repo_name, url='file:///')

    assert 'file:///' in mynewremote, 'set_remote returns remote'

    assert 'file:///' in git_repo.remote(name=repo_name), 'remote returns remote'

    assert 'myrepo' in git_repo.remotes(), '.remotes() returns new remote'

    with pytest.raises(
        exc.CommandError,
        match='.*remote {repo_name} already exists.*'.format(repo_name=repo_name),
    ):
        mynewremote = git_repo.set_remote(name='myrepo', url=new_repo_url)

    mynewremote = git_repo.set_remote(name='myrepo', url=new_repo_url, overwrite=True)

    assert new_repo_url in git_repo.remote(
        name='myrepo'
    ), 'Running remove_set should overwrite previous remote'

def test_extract_status():
    FIXTURE_A = textwrap.dedent(
        """
        # branch.oid d4ccd4d6af04b53949f89fbf0cdae13719dc5a08
        # branch.head fix-current-remote-name
        1 .M N... 100644 100644 100644 91082f119279b6f105ee9a5ce7795b3bdbe2b0de 91082f119279b6f105ee9a5ce7795b3bdbe2b0de CHANGES
    """  # NOQA: E501
    )
    assert {
        "branch_oid": 'd4ccd4d6af04b53949f89fbf0cdae13719dc5a08',
        "branch_head": 'fix-current-remote-name',
    }.items() <= extract_status(FIXTURE_A).items()

@pytest.mark.parametrize(
    'fixture,expected_result',
    [
        [
            """
        # branch.oid de6185fde0806e5c7754ca05676325a1ea4d6348
        # branch.head fix-current-remote-name
        # branch.upstream origin/fix-current-remote-name
        # branch.ab +0 -0
        1 .M N... 100644 100644 100644 91082f119279b6f105ee9a5ce7795b3bdbe2b0de 91082f119279b6f105ee9a5ce7795b3bdbe2b0de CHANGES
        1 .M N... 100644 100644 100644 302ca2c18d4c295ce217bff5f93e1ba342dc6665 302ca2c18d4c295ce217bff5f93e1ba342dc6665 tests/test_git.py
    """,  # NOQA: E501
            {
                "branch_oid": 'de6185fde0806e5c7754ca05676325a1ea4d6348',
                "branch_head": 'fix-current-remote-name',
                "branch_upstream": 'origin/fix-current-remote-name',
                "branch_ab": '+0 -0',
                "branch_ahead": '0',
                "branch_behind": '0',
            },
        ],
        [
            '# branch.upstream moo/origin/myslash/remote',
            {"branch_upstream": 'moo/origin/myslash/remote',},
        ],
    ],
)
def test_extract_status_b(fixture, expected_result):
    assert expected_result.items() <= extract_status(textwrap.dedent(fixture)).items()

@pytest.mark.parametrize(
    'fixture,expected_result',
    [
        [
            '# branch.ab +1 -83',
            {"branch_ab": '+1 -83', "branch_ahead": '1', "branch_behind": '83',},
        ],
        [
            """
            # branch.ab +0 -0
            """,
            {"branch_ab": '+0 -0', "branch_ahead": '0', "branch_behind": '0',},
        ],
        [
            """
            # branch.ab +1 -83
            """,
            {"branch_ab": '+1 -83', "branch_ahead": '1', "branch_behind": '83',},
        ],
        [
            """
            # branch.ab +9999999 -9999999
            """,
            {
                "branch_ab": '+9999999 -9999999',
                "branch_ahead": '9999999',
                "branch_behind": '9999999',
            },
        ],
    ],
)
def test_extract_status_c(fixture, expected_result):
    assert expected_result.items() <= extract_status(textwrap.dedent(fixture)).items()
<|endoftext|>


<commit_before>from hdltools.verilog.parser import (VerilogModuleParser,
                                     verilog_bitstring_to_int)
from hdltools.abshdl.vector import HDLVectorDescriptor
from hdltools.abshdl.module import (HDLModulePort,
                                    HDLModule,
                                    HDLModuleParameter)
from hdltools.abshdl.expr import HDLExpression
from hdltools.abshdl.signal import HDLSignal, HDLSignalSlice
from hdltools.abshdl.const import HDLIntegerConstant
from hdltools.abshdl.sens import HDLSensitivityList, HDLSensitivityDescriptor
from hdltools.abshdl.seq import HDLSequentialBlock
from hdltools.abshdl.assign import HDLAssignment
import os
import ast

def test_constants():

    fit = HDLIntegerConstant.value_fits_width(8, 256)
    if fit is True:
        raise Exception
    fit = HDLIntegerConstant.value_fits_width(8, 255)
    if fit is False:
        raise Exception

# test HDL primitives
def test_vector_descriptor():

    # basic testing
    vec = HDLVectorDescriptor(0, 0)
    print(vec.dumps())
    if len(vec) != 1:
        raise Exception

    vec = HDLVectorDescriptor(7)

    # test failure modes
    try:
        vec = HDLVectorDescriptor(-1, 0)
        raise Exception
    except ValueError:
        pass

    try:
        vec = HDLVectorDescriptor('1', 0)
        raise Exception
    except TypeError:
        pass

    try:
        vec = HDLVectorDescriptor(left_size=1, right_size='1')
        raise Exception
    except TypeError:
        pass

    try:
        vec = HDLVectorDescriptor(7, stored_value='a')
        raise Exception
    except TypeError:
        pass

    vec = HDLVectorDescriptor(8, stored_value=256)
    left, right = vec.evaluate()

    try:
        HDLVectorDescriptor(7, stored_value=256)
        raise Exception
    except ValueError:
        pass

def test_module_port():

    port = HDLModulePort('in', 'myport', 3)
    port = HDLModulePort('out', 'myport', (2, 0))
    port = HDLModulePort('inout', 'myport', HDLVectorDescriptor(2, 0))
    print(port.dumps())

    # fail cases
    try:
        port = HDLModulePort('unknown', 'myport', 0)
        raise Exception
    except ValueError:
        pass

    try:
        port = HDLModulePort('in', 'myport', -1)
        raise Exception
    except ValueError:
        pass

    try:
        port = HDLModulePort('in', 'myport', (2, 3, 0))
        raise Exception
    except ValueError:
        pass

    try:
        port = HDLModulePort('in', 'myport', 'INVALID')
        raise Exception
    except TypeError:
        pass

def test_hdl_parameter():

    param = HDLModuleParameter('myparam', 'integer', param_default=0)
    print(param.dumps())

def test_hdl_module():

    mod = HDLModule('my_module')
    mod = HDLModule('my_module', [HDLModulePort('in', 'myport', 8)])
    mod = HDLModule('my_module', params=[HDLModuleParameter('myparam',
                                                            'integer',
                                                            0)])

    expr = ast.parse('myparam-1', mode='eval')
    vec = HDLVectorDescriptor(left_size=HDLExpression(expr),
                              right_size=0)
    mod = HDLModule('my_module',
                    ports=[HDLModulePort('in',
                                         'myport',
                                         vec)],
                    params=HDLModuleParameter('myparam',
                                              'integer',
                                              0))
    print(mod.dumps(evaluate=True))

    param_scope = mod.get_parameter_scope()
    full_scope = mod.get_full_scope()
    params = mod.get_param_names()
    ports = mod.get_port_names()

    # failures
    try:
        mod = HDLModule('my_module', 0)
        raise Exception
    except TypeError:
        pass

    try:
        mod = HDLModule('my_module', [0])
        raise Exception
    except TypeError:
        pass

    try:
        mod = HDLModule('my_module', params=[0])
        raise Exception
    except TypeError:
        pass

    try:
        mod = HDLModule('my_module', params=0)
        raise Exception
    except TypeError:
        pass

def test_hdl_expression():

    expr_1 = 'PARAM-2'
    expr_2 = 'PARAM_X+1'
    hdl_expr_1 = HDLExpression(ast.parse(expr_1, mode='eval'))
    hdl_expr_2 = HDLExpression(ast.parse(expr_2, mode='eval'))
    sum = hdl_expr_1 + hdl_expr_2
    print(sum.dumps())

    my_signal = HDLSignal('reg', 'signal_a', size=2)
    _ = HDLExpression(HDLIntegerConstant(1))
    _ = HDLExpression(1)
    _ = HDLExpression(my_signal)
    _ = HDLExpression(HDLSignalSlice(my_signal, 1))
    _ = HDLExpression(my_signal[1:0])

def test_hdl_signal():

    my_sig = HDLSignal('reg', 'signal_x', size=(7, 0))
    print(my_sig.dumps())
    my_sliced_sig = my_sig[3:1]
    other_slice = my_sig[7]
    yet_another = my_sig[2:]
    another = my_sig[:2]
    print(yet_another.dumps())
    _ = HDLSignal('reg', 'sig', HDLVectorDescriptor(1, 0))

    # exceptions
    try:
        _ = HDLSignal('unknown', 'sig', 1)
        raise Exception
    except ValueError:
        pass

    try:
        _ = HDLSignal('reg', 'sig', -1)
        raise Exception
    except ValueError:
        pass

    try:
        _ = HDLSignal('reg', 'sig', (1, 2, 3))
        raise Exception
    except ValueError:
        pass

    try:
        _ = HDLSignal('reg', 'sig', 'invalid')
        raise Exception
    except TypeError:
        pass

    _ = HDLSignalSlice(my_sig, HDLVectorDescriptor(1, 0))

    try:
        _ = HDLSignalSlice(my_sig, 'invalid')
        raise Exception
    except TypeError:
        pass

def test_sens():

    some_signal = HDLSignal('reg', 'signal', size=1)
    sens_1 = HDLSensitivityDescriptor(sens_type='rise', sig=some_signal)

    sens_list = HDLSensitivityList()
    sens_list.add(sens_1)

    print(sens_list.dumps())

def test_seq():

    some_signal = HDLSignal('reg', 'signal', size=1)
    sens_1 = HDLSensitivityDescriptor(sens_type='rise', sig=some_signal)

    sens_list = HDLSensitivityList()
    sens_list.add(sens_1)

    ass_sig = HDLSignal('reg', 'counter', size=2)
    ass_expr = HDLExpression(ass_sig) + 1
    assign = HDLAssignment(ass_sig, ass_expr)

    seq = HDLSequentialBlock(sens_list)
    seq.add(assign)

    print(seq.dumps())
<commit_msg>increase assignment coverage<commit_after>from hdltools.verilog.parser import (VerilogModuleParser,
                                     verilog_bitstring_to_int)
from hdltools.abshdl.vector import HDLVectorDescriptor
from hdltools.abshdl.module import (HDLModulePort,
                                    HDLModule,
                                    HDLModuleParameter)
from hdltools.abshdl.expr import HDLExpression
from hdltools.abshdl.signal import HDLSignal, HDLSignalSlice
from hdltools.abshdl.const import HDLIntegerConstant
from hdltools.abshdl.sens import HDLSensitivityList, HDLSensitivityDescriptor
from hdltools.abshdl.seq import HDLSequentialBlock
from hdltools.abshdl.assign import HDLAssignment
import os
import ast

def test_constants():

    fit = HDLIntegerConstant.value_fits_width(8, 256)
    if fit is True:
        raise Exception
    fit = HDLIntegerConstant.value_fits_width(8, 255)
    if fit is False:
        raise Exception

# test HDL primitives
def test_vector_descriptor():

    # basic testing
    vec = HDLVectorDescriptor(0, 0)
    print(vec.dumps())
    if len(vec) != 1:
        raise Exception

    vec = HDLVectorDescriptor(7)

    # test failure modes
    try:
        vec = HDLVectorDescriptor(-1, 0)
        raise Exception
    except ValueError:
        pass

    try:
        vec = HDLVectorDescriptor('1', 0)
        raise Exception
    except TypeError:
        pass

    try:
        vec = HDLVectorDescriptor(left_size=1, right_size='1')
        raise Exception
    except TypeError:
        pass

    try:
        vec = HDLVectorDescriptor(7, stored_value='a')
        raise Exception
    except TypeError:
        pass

    vec = HDLVectorDescriptor(8, stored_value=256)
    left, right = vec.evaluate()

    try:
        HDLVectorDescriptor(7, stored_value=256)
        raise Exception
    except ValueError:
        pass

def test_module_port():

    port = HDLModulePort('in', 'myport', 3)
    port = HDLModulePort('out', 'myport', (2, 0))
    port = HDLModulePort('inout', 'myport', HDLVectorDescriptor(2, 0))
    print(port.dumps())

    # fail cases
    try:
        port = HDLModulePort('unknown', 'myport', 0)
        raise Exception
    except ValueError:
        pass

    try:
        port = HDLModulePort('in', 'myport', -1)
        raise Exception
    except ValueError:
        pass

    try:
        port = HDLModulePort('in', 'myport', (2, 3, 0))
        raise Exception
    except ValueError:
        pass

    try:
        port = HDLModulePort('in', 'myport', 'INVALID')
        raise Exception
    except TypeError:
        pass

def test_hdl_parameter():

    param = HDLModuleParameter('myparam', 'integer', param_default=0)
    print(param.dumps())

def test_hdl_module():

    mod = HDLModule('my_module')
    mod = HDLModule('my_module', [HDLModulePort('in', 'myport', 8)])
    mod = HDLModule('my_module', params=[HDLModuleParameter('myparam',
                                                            'integer',
                                                            0)])

    expr = ast.parse('myparam-1', mode='eval')
    vec = HDLVectorDescriptor(left_size=HDLExpression(expr),
                              right_size=0)
    mod = HDLModule('my_module',
                    ports=[HDLModulePort('in',
                                         'myport',
                                         vec)],
                    params=HDLModuleParameter('myparam',
                                              'integer',
                                              0))
    print(mod.dumps(evaluate=True))

    param_scope = mod.get_parameter_scope()
    full_scope = mod.get_full_scope()
    params = mod.get_param_names()
    ports = mod.get_port_names()

    # failures
    try:
        mod = HDLModule('my_module', 0)
        raise Exception
    except TypeError:
        pass

    try:
        mod = HDLModule('my_module', [0])
        raise Exception
    except TypeError:
        pass

    try:
        mod = HDLModule('my_module', params=[0])
        raise Exception
    except TypeError:
        pass

    try:
        mod = HDLModule('my_module', params=0)
        raise Exception
    except TypeError:
        pass

def test_hdl_expression():

    expr_1 = 'PARAM-2'
    expr_2 = 'PARAM_X+1'
    hdl_expr_1 = HDLExpression(ast.parse(expr_1, mode='eval'))
    hdl_expr_2 = HDLExpression(ast.parse(expr_2, mode='eval'))
    sum = hdl_expr_1 + hdl_expr_2
    print(sum.dumps())

    my_signal = HDLSignal('reg', 'signal_a', size=2)
    _ = HDLExpression(HDLIntegerConstant(1))
    _ = HDLExpression(1)
    _ = HDLExpression(my_signal)
    _ = HDLExpression(HDLSignalSlice(my_signal, 1))
    _ = HDLExpression(my_signal[1:0])

def test_hdl_signal():

    my_sig = HDLSignal('reg', 'signal_x', size=(7, 0))
    print(my_sig.dumps())
    my_sliced_sig = my_sig[3:1]
    other_slice = my_sig[7]
    yet_another = my_sig[2:]
    another = my_sig[:2]
    print(yet_another.dumps())
    _ = HDLSignal('reg', 'sig', HDLVectorDescriptor(1, 0))

    # exceptions
    try:
        _ = HDLSignal('unknown', 'sig', 1)
        raise Exception
    except ValueError:
        pass

    try:
        _ = HDLSignal('reg', 'sig', -1)
        raise Exception
    except ValueError:
        pass

    try:
        _ = HDLSignal('reg', 'sig', (1, 2, 3))
        raise Exception
    except ValueError:
        pass

    try:
        _ = HDLSignal('reg', 'sig', 'invalid')
        raise Exception
    except TypeError:
        pass

    _ = HDLSignalSlice(my_sig, HDLVectorDescriptor(1, 0))

    try:
        _ = HDLSignalSlice(my_sig, 'invalid')
        raise Exception
    except TypeError:
        pass

def test_sens():

    some_signal = HDLSignal('reg', 'signal', size=1)
    sens_1 = HDLSensitivityDescriptor(sens_type='rise', sig=some_signal)

    sens_list = HDLSensitivityList()
    sens_list.add(sens_1)

    print(sens_list.dumps())

def test_seq():

    some_signal = HDLSignal('reg', 'signal', size=1)
    sens_1 = HDLSensitivityDescriptor(sens_type='rise', sig=some_signal)

    sens_list = HDLSensitivityList()
    sens_list.add(sens_1)

    ass_sig = HDLSignal('reg', 'counter', size=2)
    ass_expr = HDLExpression(ass_sig) + 1
    assign = HDLAssignment(ass_sig, ass_expr)

    seq = HDLSequentialBlock(sens_list)
    seq.add(assign)

    print(seq.dumps())

def test_assign():

    # this module is extensively tested already, being used as a support
    # class for many others. here we test whatever is missing

    sig = HDLSignal('comb', 'my_signal')
    assign = HDLAssignment(signal=sig, value=0)
    print(assign.dumps())

    # test fail cases
    try:
        _ = HDLAssignment('not_allowed', 0)
        raise Exception
    except TypeError:
        pass
<|endoftext|>


<commit_before>import afnumpy
import numpy
from asserts import *

def test_copy():
    b = numpy.random.random((2,3))
    a = afnumpy.array(b)
    c = afnumpy.copy(a)
    d = numpy.copy(b)
    a[:] = 0
    b[:] = 0
    iassert(c,d)

def test_meshgrid():
    nx, ny = (3, 2)
    x2 = numpy.linspace(0, 1, nx)
    y2 = numpy.linspace(0, 1, ny)
    x1 = afnumpy.array(x2)
    y1 = afnumpy.array(y2)

    iassert(afnumpy.meshgrid(x1, y1), numpy.meshgrid(x2, y2))

def test_broadcast_arrays():
    # Currently arrayfire is missing support for int64
    x2 = numpy.array([[1,2,3]], dtype=numpy.float32)
    y2 = numpy.array([[1],[2],[3]], dtype=numpy.float32)
    x1 = afnumpy.array(x2)
    y1 = afnumpy.array(y2)
    iassert(afnumpy.broadcast_arrays(x1, y1), numpy.broadcast_arrays(x2, y2))

def test_tile():
    # Currently arrayfire is missing support for int64
    b = numpy.array([0, 1, 2], dtype=numpy.float32)
    a = afnumpy.array(b)
    iassert(afnumpy.tile(a, 2), numpy.tile(b, 2))
    iassert(afnumpy.tile(a, (2,2)), numpy.tile(b, (2,2)))
    iassert(afnumpy.tile(a, (2,1,2)), numpy.tile(b, (2,1,2)))

def test_arccos():
    a = afnumpy.random.random((2,3))
    b = numpy.array(a)
    fassert(afnumpy.arccos(a), numpy.arccos(b))
    c = afnumpy.random.random((2,3))
    d = numpy.array(a)
    fassert(afnumpy.arccos(a, out=c), numpy.arccos(b, out=d))
    fassert(c, d)

def test_arcsin():
    a = afnumpy.random.random((2,3))
    b = numpy.array(a)
    fassert(afnumpy.arcsin(a), numpy.arcsin(b))
    c = afnumpy.random.random((2,3))
    d = numpy.array(a)
    fassert(afnumpy.arcsin(a, out=c), numpy.arcsin(b, out=d))
    fassert(c, d)

def test_arctan():
    a = afnumpy.random.random((2,3))
    b = numpy.array(a)
    fassert(afnumpy.arctan(a), numpy.arctan(b))
    c = afnumpy.random.random((2,3))
    d = numpy.array(a)
    fassert(afnumpy.arctan(a, out=c), numpy.arctan(b, out=d))
    fassert(c, d)

def test_arccosh():
    # Domain for arccosh starts at 1
    a = afnumpy.random.random((2,3))+1
    b = numpy.array(a)
    fassert(afnumpy.arccosh(a), numpy.arccosh(b))
    c = afnumpy.random.random((2,3))
    d = numpy.array(a)
    fassert(afnumpy.arccosh(a, out=c), numpy.arccosh(b, out=d))
    fassert(c, d)

def test_arcsinh():
    a = afnumpy.random.random((2,3))
    b = numpy.array(a)
    fassert(afnumpy.arcsinh(a), numpy.arcsinh(b))
    c = afnumpy.random.random((2,3))
    d = numpy.array(a)
    fassert(afnumpy.arcsinh(a, out=c), numpy.arcsinh(b, out=d))
    fassert(c, d)

def test_arctanh():
    a = afnumpy.random.random((2,3))
    b = numpy.array(a)
    fassert(afnumpy.arctanh(a), numpy.arctanh(b))
    c = afnumpy.random.random((2,3))
    d = numpy.array(a)
    fassert(afnumpy.arctanh(a, out=c), numpy.arctanh(b, out=d))
    fassert(c, d)

<commit_msg>Add more trigonometric functions<commit_after>import afnumpy
import numpy
from asserts import *

def test_copy():
    b = numpy.random.random((2,3))
    a = afnumpy.array(b)
    c = afnumpy.copy(a)
    d = numpy.copy(b)
    a[:] = 0
    b[:] = 0
    iassert(c,d)

def test_meshgrid():
    nx, ny = (3, 2)
    x2 = numpy.linspace(0, 1, nx)
    y2 = numpy.linspace(0, 1, ny)
    x1 = afnumpy.array(x2)
    y1 = afnumpy.array(y2)

    iassert(afnumpy.meshgrid(x1, y1), numpy.meshgrid(x2, y2))

def test_broadcast_arrays():
    # Currently arrayfire is missing support for int64
    x2 = numpy.array([[1,2,3]], dtype=numpy.float32)
    y2 = numpy.array([[1],[2],[3]], dtype=numpy.float32)
    x1 = afnumpy.array(x2)
    y1 = afnumpy.array(y2)
    iassert(afnumpy.broadcast_arrays(x1, y1), numpy.broadcast_arrays(x2, y2))

def test_tile():
    # Currently arrayfire is missing support for int64
    b = numpy.array([0, 1, 2], dtype=numpy.float32)
    a = afnumpy.array(b)
    iassert(afnumpy.tile(a, 2), numpy.tile(b, 2))
    iassert(afnumpy.tile(a, (2,2)), numpy.tile(b, (2,2)))
    iassert(afnumpy.tile(a, (2,1,2)), numpy.tile(b, (2,1,2)))

def test_arccos():
    a = afnumpy.random.random((2,3))
    b = numpy.array(a)
    fassert(afnumpy.arccos(a), numpy.arccos(b))
    c = afnumpy.random.random((2,3))
    d = numpy.array(a)
    fassert(afnumpy.arccos(a, out=c), numpy.arccos(b, out=d))
    fassert(c, d)

def test_arcsin():
    a = afnumpy.random.random((2,3))
    b = numpy.array(a)
    fassert(afnumpy.arcsin(a), numpy.arcsin(b))
    c = afnumpy.random.random((2,3))
    d = numpy.array(a)
    fassert(afnumpy.arcsin(a, out=c), numpy.arcsin(b, out=d))
    fassert(c, d)

def test_arctan():
    a = afnumpy.random.random((2,3))
    b = numpy.array(a)
    fassert(afnumpy.arctan(a), numpy.arctan(b))
    c = afnumpy.random.random((2,3))
    d = numpy.array(a)
    fassert(afnumpy.arctan(a, out=c), numpy.arctan(b, out=d))
    fassert(c, d)

def test_arccosh():
    # Domain for arccosh starts at 1
    a = afnumpy.random.random((2,3))+1
    b = numpy.array(a)
    fassert(afnumpy.arccosh(a), numpy.arccosh(b))
    c = afnumpy.random.random((2,3))
    d = numpy.array(a)
    fassert(afnumpy.arccosh(a, out=c), numpy.arccosh(b, out=d))
    fassert(c, d)

def test_arcsinh():
    a = afnumpy.random.random((2,3))
    b = numpy.array(a)
    fassert(afnumpy.arcsinh(a), numpy.arcsinh(b))
    c = afnumpy.random.random((2,3))
    d = numpy.array(a)
    fassert(afnumpy.arcsinh(a, out=c), numpy.arcsinh(b, out=d))
    fassert(c, d)

def test_arctanh():
    a = afnumpy.random.random((2,3))
    b = numpy.array(a)
    fassert(afnumpy.arctanh(a), numpy.arctanh(b))
    c = afnumpy.random.random((2,3))
    d = numpy.array(a)
    fassert(afnumpy.arctanh(a, out=c), numpy.arctanh(b, out=d))
    fassert(c, d)

def test_cos():
    a = afnumpy.random.random((2,3))
    b = numpy.array(a)
    fassert(afnumpy.cos(a), numpy.cos(b))
    c = afnumpy.random.random((2,3))
    d = numpy.array(a)
    fassert(afnumpy.cos(a, out=c), numpy.cos(b, out=d))
    fassert(c, d)

def test_sin():
    a = afnumpy.random.random((2,3))
    b = numpy.array(a)
    fassert(afnumpy.sin(a), numpy.sin(b))
    c = afnumpy.random.random((2,3))
    d = numpy.array(a)
    fassert(afnumpy.sin(a, out=c), numpy.sin(b, out=d))
    fassert(c, d)

def test_tan():
    a = afnumpy.random.random((2,3))
    b = numpy.array(a)
    fassert(afnumpy.tan(a), numpy.tan(b))
    c = afnumpy.random.random((2,3))
    d = numpy.array(a)
    fassert(afnumpy.tan(a, out=c), numpy.tan(b, out=d))
    fassert(c, d)

def test_cosh():
    a = afnumpy.random.random((2,3))
    b = numpy.array(a)
    fassert(afnumpy.cosh(a), numpy.cosh(b))
    c = afnumpy.random.random((2,3))
    d = numpy.array(a)
    fassert(afnumpy.cosh(a, out=c), numpy.cosh(b, out=d))
    fassert(c, d)

def test_sinh():
    a = afnumpy.random.random((2,3))
    b = numpy.array(a)
    fassert(afnumpy.sinh(a), numpy.sinh(b))
    c = afnumpy.random.random((2,3))
    d = numpy.array(a)
    fassert(afnumpy.sinh(a, out=c), numpy.sinh(b, out=d))
    fassert(c, d)

def test_tanh():
    a = afnumpy.random.random((2,3))
    b = numpy.array(a)
    fassert(afnumpy.tanh(a), numpy.tanh(b))
    c = afnumpy.random.random((2,3))
    d = numpy.array(a)
    fassert(afnumpy.tanh(a, out=c), numpy.tanh(b, out=d))
    fassert(c, d)

<|endoftext|>


<commit_before>from unittest import TestCase
import shutil
import os
import tempfile
import hashlib

from mar.mar import MarFile, BZ2MarFile, read_file, safe_join

TEST_MAR = os.path.join(os.path.dirname(__file__), 'test.mar')

def test_read_file():
    data = []
    for block in read_file(open(__file__, 'rb')):
        data.append(block)
    assert b''.join(data) == open(__file__, 'rb').read()

class TestSafeJoin(TestCase):
    def test_normal(self):
        self.assertEquals(safe_join("/a/b/c", "foo/bar"), "/a/b/c/foo/bar")

    def test_absolute(self):
        self.assertEquals(safe_join("/a/b/c", "/foo/bar"), "/a/b/c/foo/bar")
        # TODO: Test windows support. os.path.isabs returns False for C:/ foo
        # on linux

    def test_unsafe(self):
        self.assertRaises(IOError, safe_join, "/a/b/c", "foo/../../bar")

def sha1sum(b):
    """Returns the sha1sum of a byte string"""
    h = hashlib.new('sha1')
    h.update(b)
    return h.hexdigest()

def test_list():
    with MarFile(TEST_MAR) as m:
        assert repr(m.members[0]) == "<update.manifest 664 141 bytes starting at 392>", m.members[0]
        assert repr(m.members[1]) == "<defaults/pref/channel-prefs.js 664 76 bytes starting at 533>", m.members[1]

    with BZ2MarFile(TEST_MAR) as m:
        assert repr(m.members[0]) == "<update.manifest 664 141 bytes starting at 392>", m.members[0]
        assert repr(m.members[1]) == "<defaults/pref/channel-prefs.js 664 76 bytes starting at 533>", m.members[1]

class TestReadingMar(TestCase):
    def setUp(self):
        self.tmpdir = tempfile.mkdtemp()
        self.marfile = MarFile(TEST_MAR)

    def tearDown(self):
        shutil.rmtree(self.tmpdir)

    def test_extract(self):
        m = self.marfile.members[0]
        self.marfile.extract(m, self.tmpdir)
        fn = os.path.join(self.tmpdir, m.name)

        # Check that the size matches what's in the manifest
        self.assertEquals(os.path.getsize(fn), m.size)

        # Check that the contents match
        data = open(fn, 'rb').read()
        h = sha1sum(data)
        self.assertEquals("6a7890e740f1e18a425b51fefbde2f6b86f91a12", h)

class TestReadingBZ2Mar(TestCase):
    def setUp(self):
        self.tmpdir = tempfile.mkdtemp()
        self.marfile = BZ2MarFile(TEST_MAR)

    def tearDown(self):
        shutil.rmtree(self.tmpdir)

    def test_extract_bz2(self):
        m = self.marfile.members[0]
        self.marfile.extract(m, self.tmpdir)
        fn = os.path.join(self.tmpdir, m.name)

        # The size in the manifest is of the compressed data, so we need to
        # check that we've extracted the correct number of uncompressed bytes
        # here
        self.assertEquals(os.path.getsize(fn), 308)

        # Check that the contents match
        data = open(fn, 'rb').read()
        h = sha1sum(data)
        self.assertEquals("5177f5938923e94820d8565a1a0f25d19b4821d1", h)

class TestWritingMar(TestCase):
    def setUp(self):
        self.tmpdir = tempfile.mkdtemp()

    def tearDown(self):
        shutil.rmtree(self.tmpdir)

    def test_add(self):
        marfile = os.path.join(self.tmpdir, 'test.mar')
        with MarFile(marfile, 'w') as m:
            m.add(__file__)

        with MarFile(marfile) as m:
            self.assertEquals(len(m.members), 1)
            self.assertEquals(m.members[0].size, os.path.getsize(__file__))
            #assert False, os.path.join(self.tmpdir, m.members[0].name)
            #assert False, m.members[0]
            extracted = m.extract(m.members[0], self.tmpdir)
            self.assertEquals(
                open(extracted, 'rb').read(),
                open(__file__, 'rb').read()
            )

class TestExceptions(TestCase):
    def test_badmar(self):
        self.assertRaises(ValueError, MarFile, __file__)
<commit_msg>removing debugging code<commit_after>from unittest import TestCase
import shutil
import os
import tempfile
import hashlib

from mar.mar import MarFile, BZ2MarFile, read_file, safe_join

TEST_MAR = os.path.join(os.path.dirname(__file__), 'test.mar')

def test_read_file():
    data = []
    for block in read_file(open(__file__, 'rb')):
        data.append(block)
    assert b''.join(data) == open(__file__, 'rb').read()

class TestSafeJoin(TestCase):
    def test_normal(self):
        self.assertEquals(safe_join("/a/b/c", "foo/bar"), "/a/b/c/foo/bar")

    def test_absolute(self):
        self.assertEquals(safe_join("/a/b/c", "/foo/bar"), "/a/b/c/foo/bar")
        # TODO: Test windows support. os.path.isabs returns False for C:/ foo
        # on linux

    def test_unsafe(self):
        self.assertRaises(IOError, safe_join, "/a/b/c", "foo/../../bar")

def sha1sum(b):
    """Returns the sha1sum of a byte string"""
    h = hashlib.new('sha1')
    h.update(b)
    return h.hexdigest()

def test_list():
    with MarFile(TEST_MAR) as m:
        assert repr(m.members[0]) == "<update.manifest 664 141 bytes starting at 392>", m.members[0]
        assert repr(m.members[1]) == "<defaults/pref/channel-prefs.js 664 76 bytes starting at 533>", m.members[1]

    with BZ2MarFile(TEST_MAR) as m:
        assert repr(m.members[0]) == "<update.manifest 664 141 bytes starting at 392>", m.members[0]
        assert repr(m.members[1]) == "<defaults/pref/channel-prefs.js 664 76 bytes starting at 533>", m.members[1]

class TestReadingMar(TestCase):
    def setUp(self):
        self.tmpdir = tempfile.mkdtemp()
        self.marfile = MarFile(TEST_MAR)

    def tearDown(self):
        shutil.rmtree(self.tmpdir)

    def test_extract(self):
        m = self.marfile.members[0]
        self.marfile.extract(m, self.tmpdir)
        fn = os.path.join(self.tmpdir, m.name)

        # Check that the size matches what's in the manifest
        self.assertEquals(os.path.getsize(fn), m.size)

        # Check that the contents match
        data = open(fn, 'rb').read()
        h = sha1sum(data)
        self.assertEquals("6a7890e740f1e18a425b51fefbde2f6b86f91a12", h)

class TestReadingBZ2Mar(TestCase):
    def setUp(self):
        self.tmpdir = tempfile.mkdtemp()
        self.marfile = BZ2MarFile(TEST_MAR)

    def tearDown(self):
        shutil.rmtree(self.tmpdir)

    def test_extract_bz2(self):
        m = self.marfile.members[0]
        self.marfile.extract(m, self.tmpdir)
        fn = os.path.join(self.tmpdir, m.name)

        # The size in the manifest is of the compressed data, so we need to
        # check that we've extracted the correct number of uncompressed bytes
        # here
        self.assertEquals(os.path.getsize(fn), 308)

        # Check that the contents match
        data = open(fn, 'rb').read()
        h = sha1sum(data)
        self.assertEquals("5177f5938923e94820d8565a1a0f25d19b4821d1", h)

class TestWritingMar(TestCase):
    def setUp(self):
        self.tmpdir = tempfile.mkdtemp()

    def tearDown(self):
        shutil.rmtree(self.tmpdir)

    def test_add(self):
        marfile = os.path.join(self.tmpdir, 'test.mar')
        with MarFile(marfile, 'w') as m:
            m.add(__file__)

        with MarFile(marfile) as m:
            self.assertEquals(len(m.members), 1)
            self.assertEquals(m.members[0].size, os.path.getsize(__file__))
            extracted = m.extract(m.members[0], self.tmpdir)
            self.assertEquals(
                open(extracted, 'rb').read(),
                open(__file__, 'rb').read()
            )

class TestExceptions(TestCase):
    def test_badmar(self):
        self.assertRaises(ValueError, MarFile, __file__)
<|endoftext|>