# Copyright 2012-2013 Ravello Systems, Inc.
# 
# 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.

import os
import sys
import tempfile
import shutil
import argparse

from nose import SkipTest
from testmill.ravello import RavelloClient
from testmill.state import env, _Environment

testenv = _Environment()
from testmill.test import networkblocker, sudo
from testmill.test.fileops import *

if sys.version_info[0] == 3:
    import configparser
else:
    import ConfigParser as configparser


__all__ = ('testenv', 'require_sudo', 'require_network_blocking',
           'TestSuite', 'unittest', 'integrationtest', 'systemtest',
           'tempdir', 'get_common_args', 'parse_ps_output', 'environ')


testdir, _ = os.path.split(os.path.abspath(__file__))
parent = testdir
for i in range(3):
    parent, _ = os.path.split(parent)
topdir = parent


def setup_package():
    # Have nose capture stderr too.
    testenv._nose_saved_stderr = sys.stderr
    sys.stderr = sys.stdout

def teardown_package():
    sys.stderr = testenv._nose_saved_stderr
    testenv._nose_saved_stderr = None


# Create an environment based on ~/test.cfg.

def create_test_environment():
    """Create at test environment based on $topdir/test.cfg."""
    fname = os.path.join(topdir, 'test.cfg')
    if not os.access(fname, os.R_OK):
        m = 'Tests need to be run from a checked out source repository.'
        raise RuntimeError(m)
    config = configparser.ConfigParser()
    config.read([fname])
    def config_var(name, default=None):
        try:
            return config.get('test', name)
        except (configparser.NoSectionError, configparser.NoOptionError):
            return default