<commit_before>from __future__ import print_function
import boto3
import sys
import time
import botocore.exceptions

class Runner(object):
    def __init__(self, template, stack_name, params=[], iam_capability=False, session=None):
        self.stack_name = stack_name
        self.iam_capability = iam_capability
        self.params = params
        self.session = session if session else boto3.session.Session()
        self.client = session.client('cloudformation')
        self.template_output = template.to_json()

    def find_stack(self):
        stacks = []
        try:
            stacks = self.client.describe_stacks(StackName=self.stack_name)["Stacks"]
        except botocore.exceptions.ClientError:
            pass
        return stacks

    def perform(self):
        stacks = self.find_stack()
        if len(stacks) == 0:
            self.create()
        else:
            self.update()
        self.wait()

    def processed_params(self):
        res = []
        for key, value in self.params.iteritems():
            param_struct = {
                    "ParameterKey": key,
                    "ParameterValue": value,
                    "UsePreviousValue": False
            }
            res.append(param_struct)
        return res

    def capabilities(self):
        if self.iam_capability:
            return ["CAPABILITY_IAM"]
        else:
            return []

    def stack_operation_args(self):
        return {
                "StackName": self.stack_name,
                "TemplateBody": self.template_output,
                "Parameters": self.processed_params(),
                "Capabilities": self.capabilities()
                }

    def create(self):
        print(self.stack_operation_args())
        self.client.create_stack(**self.stack_operation_args())

    def update(self):
        self.client.update_stack(**self.stack_operation_args())

    def wait(self):
        stack_status = ""
        count = 0
        while stack_status not in ["UPDATE_COMPLETE", "CREATE_COMPLETE"] and count < 10:
            count += 1
            print(".", end="")
            sys.stdout.flush()
            time.sleep(5)
            stacks = self.client.describe_stacks(StackName=self.stack_name)
            stack_status = stacks["Stacks"][0]["StackStatus"]
        if count == 20:
            print("\nError: {0}".format(stack_status))
            return
        print("\nSuccess: {0}".format(stack_status))
<commit_msg>Don't fail if no update are needed<commit_after>from __future__ import print_function
import boto3
import sys
import time
import botocore.exceptions

class Runner(object):
    def __init__(self, template, stack_name, params=[], iam_capability=False, session=None):
        self.stack_name = stack_name
        self.iam_capability = iam_capability
        self.params = params
        self.session = session if session else boto3.session.Session()
        self.client = session.client('cloudformation')
        self.template_output = template.to_json()

    def find_stack(self):
        stacks = []
        try:
            stacks = self.client.describe_stacks(StackName=self.stack_name)["Stacks"]
        except botocore.exceptions.ClientError:
            pass
        return stacks

    def perform(self):
        stacks = self.find_stack()
        if len(stacks) == 0:
            self.create()
        else:
            self.update()
        self.wait()

    def processed_params(self):
        res = []
        for key, value in self.params.iteritems():
            param_struct = {
                    "ParameterKey": key,
                    "ParameterValue": value,
                    "UsePreviousValue": False
            }
            res.append(param_struct)
        return res

    def capabilities(self):
        if self.iam_capability:
            return ["CAPABILITY_IAM"]
        else:
            return []

    def stack_operation_args(self):
        return {
                "StackName": self.stack_name,
                "TemplateBody": self.template_output,
                "Parameters": self.processed_params(),
                "Capabilities": self.capabilities()
                }

    def create(self):
        print(self.stack_operation_args())
        self.client.create_stack(**self.stack_operation_args())

    def update(self):
        try:
            self.client.update_stack(**self.stack_operation_args())
        except botocore.exceptions.ClientError, e:
            if "No updates are to be performed" not in str(e):
                raise

    def wait(self):
        stack_status = ""
        count = 0
        while stack_status not in ["UPDATE_COMPLETE", "CREATE_COMPLETE"] and count < 10:
            count += 1
            print(".", end="")
            sys.stdout.flush()
            time.sleep(5)
            stacks = self.client.describe_stacks(StackName=self.stack_name)
            stack_status = stacks["Stacks"][0]["StackStatus"]
        if count == 20:
            print("\nError: {0}".format(stack_status))
            return
        print("\nSuccess: {0}".format(stack_status))
<|endoftext|>


<commit_before>from __future__ import absolute_import, unicode_literals

import json

from django.template.loader import render_to_string
from django.utils.translation import ugettext_lazy as _

from wagtail.wagtailadmin.widgets import AdminChooser

from wagtailmedia.models import get_media_model

class AdminMediaChooser(AdminChooser):
    choose_one_text = _('Choose a media')
    choose_another_text = _('Choose another media')
    link_to_chosen_text = _('Edit this media')

    def __init__(self, **kwargs):
        super(AdminMediaChooser, self).__init__(**kwargs)
        self.media_model = get_media_model()

    def render_html(self, name, value, attrs):
        instance, value = self.get_instance_and_id(self.media_model, value)
        original_field_html = super(AdminMediaChooser, self).render_html(name, value, attrs)

        return render_to_string('wagtailmedia/widgets/media_chooser.html', {
            'widget': self,
            'original_field_html': original_field_html,
            'attrs': attrs,
            'value': value,
            'media': instance,
        })

    def render_js_init(self, id_, name, value):
        return "createMediaChooser({0});".format(json.dumps(id_))
<commit_msg>Changes texts of chooser buttons<commit_after>from __future__ import absolute_import, unicode_literals

import json

from django.template.loader import render_to_string
from django.utils.translation import ugettext_lazy as _

from wagtail.wagtailadmin.widgets import AdminChooser

from wagtailmedia.models import get_media_model

class AdminMediaChooser(AdminChooser):
    choose_one_text = _('Choose a media item')
    choose_another_text = _('Choose another media item')
    link_to_chosen_text = _('Edit this media item')

    def __init__(self, **kwargs):
        super(AdminMediaChooser, self).__init__(**kwargs)
        self.media_model = get_media_model()

    def render_html(self, name, value, attrs):
        instance, value = self.get_instance_and_id(self.media_model, value)
        original_field_html = super(AdminMediaChooser, self).render_html(name, value, attrs)

        return render_to_string('wagtailmedia/widgets/media_chooser.html', {
            'widget': self,
            'original_field_html': original_field_html,
            'attrs': attrs,
            'value': value,
            'media': instance,
        })

    def render_js_init(self, id_, name, value):
        return "createMediaChooser({0});".format(json.dumps(id_))
<|endoftext|>


<commit_before>from __future__ import absolute_import

import sys
import threading
import collections

from . import idiokit, timer, _time, _selectloop

class ThreadPool(object):
    _Event = idiokit.Event
    _sleep = staticmethod(timer.sleep)
    _deque = staticmethod(collections.deque)
    _Thread = staticmethod(threading.Thread)
    _Lock = staticmethod(threading.Lock)
    _exc_info = staticmethod(sys.exc_info)
    _asap = staticmethod(_selectloop.asap)
    _selectloop_sleep = staticmethod(_selectloop.sleep)
    _monotonic = _time.monotonic

    def __init__(self, idle_time=1.0):
        self.idle_time = idle_time

        self.lock = self._Lock()
        self.supervisor = None

        self.alive = 0
        self.threads = self._deque()
        self.queue = self._deque()

    def run(self, func, *args, **keys):
        event = self._Event()

        with self.lock:
            if self.threads:
                _, lock, queue = self.threads.pop()
                queue.append((event, func, args, keys))
                lock.release()
            else:
                lock = self._Lock()
                queue = [(event, func, args, keys)]

                thread = self._Thread(target=self._thread, args=(lock, queue))
                thread.daemon = True
                thread.start()

                self.alive += 1

            if self.supervisor is None:
                self.supervisor = self._supervisor()

        return event

    @idiokit.stream
    def _supervisor(self):
        while True:
            while True:
                yield self._sleep(self.idle_time / 2.0)

                with self.lock:
                    if self.alive == 0:
                        break

                    cut = self._monotonic() - self.idle_time
                    while self.threads and self.threads[0][0] < cut:
                        _, lock, queue = self.threads.popleft()
                        queue.append(None)
                        lock.release()

            yield self._sleep(self.idle_time)
            with self.lock:
                if self.alive == 0:
                    self.supervisor = None
                    return

    def _thread(self, lock, queue):
        while True:
            lock.acquire()

            item = queue.pop()
            if item is None:
                with self.lock:
                    self.alive -= 1
                return

            event, func, args, keys = item

            try:
                throw = False
                args = (func(*args, **keys),)
            except:
                throw = True
                args = self._exc_info()

            with self.lock:
                self.threads.append((self._monotonic(), lock, queue))

            if throw:
                self._asap(event.throw, *args)
            else:
                self._asap(event.succeed, *args)

global_threadpool = ThreadPool()

def thread(func, *args, **keys):
    return global_threadpool.run(func, *args, **keys)
<commit_msg>new-selectloop / idiokit.threadpool: Remove cruft from the previous commit.<commit_after>from __future__ import absolute_import

import sys
import threading
import collections

from . import idiokit, timer, _time, _selectloop

class ThreadPool(object):
    _Event = idiokit.Event
    _sleep = staticmethod(timer.sleep)
    _deque = staticmethod(collections.deque)
    _Thread = staticmethod(threading.Thread)
    _Lock = staticmethod(threading.Lock)
    _exc_info = staticmethod(sys.exc_info)
    _asap = staticmethod(_selectloop.asap)
    _monotonic = _time.monotonic

    def __init__(self, idle_time=1.0):
        self.idle_time = idle_time

        self.lock = self._Lock()
        self.supervisor = None

        self.alive = 0
        self.threads = self._deque()
        self.queue = self._deque()

    def run(self, func, *args, **keys):
        event = self._Event()

        with self.lock:
            if self.threads:
                _, lock, queue = self.threads.pop()
                queue.append((event, func, args, keys))
                lock.release()
            else:
                lock = self._Lock()
                queue = [(event, func, args, keys)]

                thread = self._Thread(target=self._thread, args=(lock, queue))
                thread.daemon = True
                thread.start()

                self.alive += 1

            if self.supervisor is None:
                self.supervisor = self._supervisor()

        return event

    @idiokit.stream
    def _supervisor(self):
        while True:
            while True:
                yield self._sleep(self.idle_time / 2.0)

                with self.lock:
                    if self.alive == 0:
                        break

                    cut = self._monotonic() - self.idle_time
                    while self.threads and self.threads[0][0] < cut:
                        _, lock, queue = self.threads.popleft()
                        queue.append(None)
                        lock.release()

            yield self._sleep(self.idle_time)
            with self.lock:
                if self.alive == 0:
                    self.supervisor = None
                    return

    def _thread(self, lock, queue):
        while True:
            lock.acquire()

            item = queue.pop()
            if item is None:
                with self.lock:
                    self.alive -= 1
                return

            event, func, args, keys = item

            try:
                throw = False
                args = (func(*args, **keys),)
            except:
                throw = True
                args = self._exc_info()

            with self.lock:
                self.threads.append((self._monotonic(), lock, queue))

            if throw:
                self._asap(event.throw, *args)
            else:
                self._asap(event.succeed, *args)

global_threadpool = ThreadPool()

def thread(func, *args, **keys):
    return global_threadpool.run(func, *args, **keys)
<|endoftext|>


<commit_before>import string

class Query(object):
    """
    Models a Query object for use with ifind's search interface.

    """
    def __init__(self, terms, top=10, lang="", result_type=""):
        """
        Query constructor.

        Args:
            terms (str): query terms to search for.

        Kwargs:
            top (int): maximum number of results to return
            lang (str): preferred language of returned results (engine specific)
            result_type (str): type of query (engine specific)

        Attributes:
            skip (int): offset of starting point for results returned

        Usage:
            query = Query("hello world")
            query = Query("hello world", top=20)

        """
        self.terms = Query.check_input(terms)
        self.parsed_terms = None
        self.result_type = result_type.lower()
        self.lang = lang
        self.top = top
        self.skip = 0

    def __str__(self):
        """
        Returns human-readable string representation of query object.

        Returns:
            str: formatted new-lined list of query attributes

        Usage:
            query = Query("hello world", top=5, lang='en)
            print query -- > Lang: en
                             Skip: 0
                             Top: 5
                             Terms: hello world
                             Result_Type:

        """
        return '\n'.join(['{0}: {1}'.format(key.title(), value)
                          for (key, value) in self.__dict__.items()])

    def __eq__(self, other):
        """
        Overrides '==' operator, returns True if both querys hash to the same value.

        Usage:
            query = Query("hello world", top=30)
            query2 = Query("hello world")
            print query == query2 --> False

            query2.top = 30
            print query == query2 --> True

        """
        return hash(self) == hash(other)

    def __hash__(self):
        """
        Overrides hash() method, hashes tupled attributes of query.

        Returns:
            int: large unique integer, representing hashed value of query

        Usage:
            query = Query("court", top=25)
            print hash(query) --> 9160469348640922505

        """
        return hash(tuple(self.__dict__.items()))

    @staticmethod
    def check_input(input_string):
        """
        Takes a unicode string, encodes it to ascii
        whilst stripping out the punctuation.

        Returns cleaned string or None if string
        contains nothing/spaces.

        """
        PUNCTUATION = '!"#$%&\'()*+,-/;<=>?@[\\]^_`{|}~'

        # encode to ascii, ignoring non ascii chars
        s = input_string.encode('ascii', 'ignore')

        # remove all punctuation
        s = s.translate(string.maketrans(PUNCTUATION, ' '*len(PUNCTUATION)))

        # set to None if just spaces
        if s.isspace():
            s = None

        return s

    def __unicode__(self):
        """
        Unicode method - returns the query.
        """
        if isinstance(self.parsed_terms, unicode):
            return self.parsed_terms

        return_str = u""

        for term in self.parsed_terms:
            return_str = "{0} {1}".format(return_str, term.text)

        return return_str.strip()<commit_msg>Added a method to set the skip paramater<commit_after>import string

class Query(object):
    """
    Models a Query object for use with ifind's search interface.

    """
    def __init__(self, terms, top=10, lang="", result_type=""):
        """
        Query constructor.

        Args:
            terms (str): query terms to search for.

        Kwargs:
            top (int): maximum number of results to return
            lang (str): preferred language of returned results (engine specific)
            result_type (str): type of query (engine specific)

        Attributes:
            skip (int): offset of starting point for results returned

        Usage:
            query = Query("hello world")
            query = Query("hello world", top=20)

        """
        self.terms = Query.check_input(terms)
        self.parsed_terms = None
        self.result_type = result_type.lower()
        self.lang = lang
        self.top = top
        self.skip = 0

    def set_skip(self, skip):
        self.skip = skip

    def __str__(self):
        """
        Returns human-readable string representation of query object.

        Returns:
            str: formatted new-lined list of query attributes

        Usage:
            query = Query("hello world", top=5, lang='en)
            print query -- > Lang: en
                             Skip: 0
                             Top: 5
                             Terms: hello world
                             Result_Type:

        """
        return '\n'.join(['{0}: {1}'.format(key.title(), value)
                          for (key, value) in self.__dict__.items()])

    def __eq__(self, other):
        """
        Overrides '==' operator, returns True if both querys hash to the same value.

        Usage:
            query = Query("hello world", top=30)
            query2 = Query("hello world")
            print query == query2 --> False

            query2.top = 30
            print query == query2 --> True

        """
        return hash(self) == hash(other)

    def __hash__(self):
        """
        Overrides hash() method, hashes tupled attributes of query.

        Returns:
            int: large unique integer, representing hashed value of query

        Usage:
            query = Query("court", top=25)
            print hash(query) --> 9160469348640922505

        """
        return hash(tuple(self.__dict__.items()))

    @staticmethod
    def check_input(input_string):
        """
        Takes a unicode string, encodes it to ascii
        whilst stripping out the punctuation.

        Returns cleaned string or None if string
        contains nothing/spaces.

        """
        PUNCTUATION = '!"#$%&\'()*+,-/;<=>?@[\\]^_`{|}~'

        # encode to ascii, ignoring non ascii chars
        s = input_string.encode('ascii', 'ignore')

        # remove all punctuation
        s = s.translate(string.maketrans(PUNCTUATION, ' '*len(PUNCTUATION)))

        # set to None if just spaces
        if s.isspace():
            s = None

        return s

    def __unicode__(self):
        """
        Unicode method - returns the query.
        """
        if isinstance(self.parsed_terms, unicode):
            return self.parsed_terms

        return_str = u""

        for term in self.parsed_terms:
            return_str = "{0} {1}".format(return_str, term.text)

        return return_str.strip()<|endoftext|>


<commit_before>#!/usr/bin/env python
# -*- coding: utf8 -*-

import os
import glob
import time
import datetime
import collections

"""
Setting up  is described in
https://github.com/NelisW/myOpenHab/blob/master/docs/021-1wire-RPi.md
https://github.com/NelisW/myOpenHab/blob/master/docs/050-DS18B20-temperature.md

the driver expects the 1-wire device on GPIO4
"""

# load the 1-wire interface driver, unless already loaded during boot
#ideally it must be done at boot, commented out here
#os.system('modprobe w1-gpio')
#adds temperature support
#os.system('modprobe w1-therm')

#set up the path to device and get list of all devices
base_dir = '/sys/bus/w1/devices/'
device_folders = glob.glob(base_dir + '28*')

#print(device_folders)

def read_temp_raw(device):
    f = open(device + '/w1_slave', 'r')
    lines = f.readlines()
    f.close()
    return lines

def read_temp(device_folders, device_key):
    dicmeasure = {}
    for device in device_folders:
        devID = device[device.rfind('/')+1:]
        lines = read_temp_raw(device)
        while lines[0].strip()[-3:] != 'YES':
            time.sleep(0.2)
            lines = read_temp_raw(device)
        equals_pos = lines[1].find('t=')
        if equals_pos != -1:
            temp_c = float(lines[1][equals_pos+2:]) / 1000.0
            ctime = datetime.datetime.now().isoformat(' ')
            dicmeasure[devID]= [ctime, temp_c]
	if device_key in dicmeasure.keys():
		rtnTemp = dicmeasure[device_key]
	else:
		rtnTemp = -100.0
    return rtnTemp

lastTime = datetime.datetime.now()

while True:

    #for i,key in enumerate(dicmeasure):
        #print('{}: {} {:.1f} C'.format(key,dicmeasure[key][0], dicmeasure[key][1]))

    # RPi CPU temperature
    tempCPU = int(open('/sys/class/thermal/thermal_zone0/temp').read()) / 1e3
    #print('CPU temperature {} '.format(tempCPU))

    #publish regular status meassages to openHAB via mqtt
    #os.system("mosquitto_pub -t 'home/garage/PVTemperatureMid' -m '{}'".format(dicmeasure['28-000004d0250c'][1]))
    #os.system("mosquitto_pub -t 'home/garage/PVTemperatureFar' -m '{}'".format(dicmeasure['28-021582d1d0ff'][1]))
    #os.system("mosquitto_pub -t 'home/garage/PVTemperatureNer' -m '{}'".format(dicmeasure['28-021582f6a5ff'][1]))
    #os.system("mosquitto_pub -t 'home/study/RoomTemperature' -m '{}'".format(dicmeasure['28-021582d26eff'][1]))

    os.system("mosquitto_pub -t 'home/garage/PVTemperatureMid' -m '{}'".format(read_temp(device_folders, '28-000004d0250c')))
    os.system("mosquitto_pub -t 'home/garage/PVTemperatureFar' -m '{}'".format(read_temp(device_folders, '28-021582d1d0ff')))
    os.system("mosquitto_pub -t 'home/garage/PVTemperatureNer' -m '{}'".format(read_temp(device_folders, '28-021582f6a5ff')))
    os.system("mosquitto_pub -t 'home/study/RoomTemperature' -m '{}'".format(read_temp(device_folders, '28-021582d26eff')))
    os.system("mosquitto_pub -t 'home/study/CPUTemperature' -m '{}'".format(tempCPU))

    #publish mqtt warnings when the CPU temperature rises above some threshold
    #the message can be used to trigger a pushover and/or email notification
    thresholdTempCPU = 50.
    if tempCPU > thresholdTempCPU:
		now = datetime.datetime.now()
		#this warning must only be issued between 0600 and 2200
		if now.hour > 6 and now.hour < 22:
			#get day of year to ensure only one warning per day
			lastDay = (lastTime.year - 2000) * 356 + lastTime.timetuple().tm_yday
			nowDay = (now.year - 2000) * 356 + now.timetuple().tm_yday
			#this warning must only be issued once per day
			if nowDay > lastDay:
				os.system("mosquitto_pub -t 'pushover/warnCPU' -m 'CPU temperature is {} C'".format(tempCPU))
				lastTime = now

    time.sleep(10)

<commit_msg>bugfix in DS18B20 python code<commit_after>#!/usr/bin/env python
# -*- coding: utf8 -*-

import os
import glob
import time
import datetime
import collections

"""
Setting up  is described in
https://github.com/NelisW/myOpenHab/blob/master/docs/021-1wire-RPi.md
https://github.com/NelisW/myOpenHab/blob/master/docs/050-DS18B20-temperature.md

the driver expects the 1-wire device on GPIO4
"""

# load the 1-wire interface driver, unless already loaded during boot
#ideally it must be done at boot, commented out here
#os.system('modprobe w1-gpio')
#adds temperature support
#os.system('modprobe w1-therm')

#set up the path to device and get list of all devices
base_dir = '/sys/bus/w1/devices/'
device_folders = glob.glob(base_dir + '28*')

#print(device_folders)

def read_temp_raw(device):
    f = open(device + '/w1_slave', 'r')
    lines = f.readlines()
    f.close()
    return lines

def read_temp(device_folders, device_key):
    dicmeasure = {}
    for device in device_folders:
        devID = device[device.rfind('/')+1:]
        #return devID
        lines = read_temp_raw(device)
        while lines[0].strip()[-3:] != 'YES':
            time.sleep(0.2)
            lines = read_temp_raw(device)
        equals_pos = lines[1].find('t=')
        if equals_pos != -1:
            #print(lines[1])
            #print(lines[1][equals_pos+2:])
            temp_c = float(lines[1][equals_pos+2:]) / 1000.0
            ctime = datetime.datetime.now().isoformat(' ')
            dicmeasure[devID]= [ctime, temp_c]
        else:
            rtnTemp = -200.
	if device_key in dicmeasure.keys():
		rtnTemp = dicmeasure[device_key]
	else:
		rtnTemp = -100.0
    return rtnTemp

lastTime = datetime.datetime.now()

while True:

    #for i,key in enumerate(dicmeasure):
        #print('{}: {} {:.1f} C'.format(key,dicmeasure[key][0], dicmeasure[key][1]))

    # RPi CPU temperature
    tempCPU = int(open('/sys/class/thermal/thermal_zone0/temp').read()) / 1e3
    #print('CPU temperature {} '.format(tempCPU))

    ##publish regular status meassages to openHAB via mqtt
    ##os.system("mosquitto_pub -t 'home/solar/PVTemperatureMid' -m '{}'".format(dicmeasure['28-000004d0250c'][1]))
    ##os.system("mosquitto_pub -t 'home/solar/PVTemperatureFar' -m '{}'".format(dicmeasure['28-021582d1d0ff'][1]))
    ##os.system("mosquitto_pub -t 'home/solar/PVTemperatureNer' -m '{}'".format(dicmeasure['28-021582f6a5ff'][1]))
    ##os.system("mosquitto_pub -t 'home/study/RoomTemperature' -m '{}'".format(dicmeasure['28-021582d26eff'][1]))

    #os.system("mosquitto_pub -t 'home/solar/PVTemperatureMid' -m '{}'".format(read_temp(device_folders, '28-000004d0250c')[1]))
    #os.system("mosquitto_pub -t 'home/solar/PVTemperatureFar' -m '{}'".format(read_temp(device_folders, '28-021582d1d0ff')[1]))
    #os.system("mosquitto_pub -t 'home/solar/PVTemperatureNer' -m '{}'".format(read_temp(device_folders, '28-021582f6a5ff')[1]))

    #print(read_temp(device_folders, '28-000005043944'))
    #print(read_temp(device_folders, '28-000005043944')[1])
    os.system("mosquitto_pub -t 'home/study/RoomTemperature' -m '{}'".format(read_temp(device_folders, '28-000005043944')[1]))

    os.system("mosquitto_pub -t 'home/study/CPUTemperature' -m '{}'".format(tempCPU))

    #publish mqtt warnings when the CPU temperature rises above some threshold
    #the message can be used to trigger a pushover and/or email notification
    thresholdTempCPU = 50.
    if tempCPU > thresholdTempCPU:
		now = datetime.datetime.now()
		#this warning must only be issued between 0600 and 2200
		if now.hour > 6 and now.hour < 22:
			#get day of year to ensure only one warning per day
			lastDay = (lastTime.year - 2000) * 356 + lastTime.timetuple().tm_yday
			nowDay = (now.year - 2000) * 356 + now.timetuple().tm_yday
			#this warning must only be issued once per day
			if nowDay > lastDay:
				os.system("mosquitto_pub -t 'pushover/warnCPU' -m 'CPU temperature is {} C'".format(tempCPU))
				lastTime = now

    time.sleep(10)

<|endoftext|>


<commit_before>import unittest
import sys
from io import StringIO
import inspect

from classes import Paladin
from spells import PaladinSpell
from models.spells.loader import load_paladin_spells_for_level

class PaladinTests(unittest.TestCase):
    def setUp(self):
        self.name = "Netherblood"
        self.level = 3
        self.dummy = Paladin(name=self.name, level=self.level, health=100, mana=100, strength=10)

    def test_init(self):
        """ The __init__ should load/save all the spells for the Paladin"""
        spells = [spell for level in range(1,self.level+1) for spell in load_paladin_spells_for_level(level)]

        self.assertNotEqual(len(self.dummy.learned_spells), 0)
        for spell in spells:
            self.assertIn(spell.name, self.dummy.learned_spells)
            char_spell = self.dummy.learned_spells[spell.name]
            # find the largest rank in our spells list (the char has the highest rank only)
            max_rank = list(sorted(filter(lambda x: x.name == spell.name, spells), key=lambda x: x.rank))[-1].rank

            self.assertEqual(char_spell.rank, max_rank)

    def test_leave_combat(self):
        """
        Except the normal behaviour, leave_combat should remove the SOR buff from the pally
        and reset his spell cds
        """
        self.dummy._in_combat = True
        self.dummy.SOR_ACTIVE = True
        for spell in self.dummy.learned_spells.values():
            spell._cooldown_counter = 100

        self.assertTrue(self.dummy.is_in_combat())

        self.dummy.leave_combat()

        self.assertFalse(self.dummy.is_in_combat())
        self.assertFalse(self.dummy.SOR_ACTIVE)
        # All cooldowns should be reset
        self.assertTrue(all([spell._cooldown_counter == 0 for spell in self.dummy.learned_spells.values()]))

    def test_reset_spell_cooldowns(self):
        """ The reset_spell_cooldowns goes through every spell and resets its CD"""
        for spell in self.dummy.learned_spells.values():
            spell._cooldown_counter = 100
        self.assertTrue(all([spell._cooldown_counter != 0 for spell in self.dummy.learned_spells.values()]))

        self.dummy.reset_spell_cooldowns()

        self.assertTrue(all([spell._cooldown_counter == 0 for spell in self.dummy.learned_spells.values()]))

    def test_level_up(self):
        """ Except the normal behaviour, it should learn new spells for the character """
        # empty the learned spells, it's stored as a static variable, which is not good practice but doesn't hurt in the game
        Paladin.learned_spells = {}
        pl = Paladin(name="fuck a nine to five")

        spells_to_learn = [spell.name for spell in load_paladin_spells_for_level(pl.level + 1)]
        for spell in spells_to_learn:
            self.assertNotIn(spell, pl.learned_spells)
        pl._level_up()
        for spell in spells_to_learn:
            self.assertIn(spell, pl.learned_spells)

    def test_level_up_to_level(self):
        """ Except the normal behaviour, it should learn new spells for the character """
        # empty the learned spells, it's stored as a static variable, which is not good practice but doesn't hurt in the game
        Paladin.learned_spells = {}
        pl = Paladin(name="fuck a nine to five")
        to_level = 4

        spells_to_learn = [spell for level in range(2, to_level + 1) for spell in load_paladin_spells_for_level(level)]
        for spell in spells_to_learn:
            has_not_learned_spell = spell.name not in pl.learned_spells
            has_smaller_rank = spell.rank > pl.learned_spells[spell.name].rank if not has_not_learned_spell else False
            self.assertTrue(has_not_learned_spell or has_smaller_rank)
        pl._level_up(to_level=to_level)
        for spell in spells_to_learn:
            self.assertIn(spell.name, pl.learned_spells)

    def test_lookup_and_handle_new_spells(self):
        """ Should look up the available spells for our level and learn them or update our existing ones"""
        Paladin.learned_spells = {}
        pl = Paladin(name="fuck a nine to five")
        print(pl.learned_spells)
        pl.level = 3
        spells_to_learn = [spell for spell in load_paladin_spells_for_level(pl.level)]
        for spell in spells_to_learn:
            has_not_learned_spell = spell.name not in pl.learned_spells
            has_smaller_rank = spell.rank > pl.learned_spells[spell.name].rank if not has_not_learned_spell else False
            self.assertTrue(has_not_learned_spell or has_smaller_rank)

        pl._lookup_and_handle_new_spells()

        for spell in spells_to_learn:
            self.assertIn(spell.name, pl.learned_spells)

    def test_learn_new_spell(self):
        """ Given a PaladinSpell, add it to the learned_spells dictionary"""
        spell = PaladinSpell(name="Too_Alive", rank=5)
        expected_message = f'You have learned a new spell - {spell.name}'

        self.assertNotIn(spell.name, self.dummy.learned_spells)
        try:
            output = StringIO()
            sys.stdout = output

            self.dummy.learn_new_spell(spell)

            self.assertIn(expected_message, output.getvalue())
        finally:
            sys.stdout = sys.__stdout__
        self.assertIn(spell.name, self.dummy.learned_spells)

    def test_lookup_available_spells_to_learn(self):
        """ It's a generator function returning a spell that can be learnt for the level """
        lev = 3
        expected_spells = load_paladin_spells_for_level(lev)
        generator = self.dummy._lookup_available_spells_to_learn(lev)

        self.assertTrue(inspect.isgenerator(generator))
        for spell in expected_spells:
            self.assertEqual(vars(next(generator)), vars(spell))

    def test_update_spell(self):
        """ The update_spell() function updates a spell we already have learned"""
        f_spell = PaladinSpell('Spell', rank=1)
        s_spell = PaladinSpell('Spell', rank=2)
        expected_message = f'Spell {f_spell.name} has been updated to rank {s_spell.rank}!'
        self.dummy.learn_new_spell(f_spell)

        try:
            output = StringIO()
            sys.stdout = output

            self.dummy.update_spell(s_spell)

            self.assertIn(expected_message, output.getvalue())
        finally:
            sys.stdout = sys.__stdout__

        # assert that it updated the rank
        self.assertEqual(self.dummy.learned_spells[s_spell.name].rank, s_spell.rank)
        self.assertGreater(self.dummy.learned_spells[s_spell.name].rank, f_spell.rank)

    def test_spell_handler_sor(self):
        """
        The spell handler takes spell names and casts the appropriate function
        It might work in a bad way since it's not too testable
        """
        unsuccessful_message = 'Unsuccessful cast'
        sor_success_msg = 'SOR_CASTED'
        sor_command_name = 'sor'
        # Mock the function that should get called
        self.dummy.spell_seal_of_righteousness = lambda x: sor_success_msg

        try:
            output = StringIO()
            sys.stdout = output
            result = self.dummy.spell_handler(sor_command_name, None)

            self.assertNotIn(unsuccessful_message, output.getvalue())
        finally:
            sys.stdout = sys.__stdout__

        # Assert that it called the spell_seal_of_righteousness function
        self.assertEqual(result, sor_success_msg)

    def test_spell_handler_fol(self):
        unsuccessful_message = 'Unsuccessful cast'
        fol_success_msg = 'FOL_CASTED'
        fol_command_name = 'fol'
        # Mock the function that should get called
        self.dummy.spell_flash_of_light = lambda x: fol_success_msg

        try:
            output = StringIO()
            sys.stdout = output
            result = self.dummy.spell_handler(fol_command_name, None)

            self.assertNotIn(unsuccessful_message, output.getvalue())
        finally:
            sys.stdout = sys.__stdout__

        # Assert that it called the spell_seal_of_righteousness function
        self.assertEqual(result, fol_success_msg)

    def test_spell_handler_ms(self):
        unsuccessful_message = 'Unsuccessful cast'
        ms_success_msg = 'MS_CASTED'
        ms_command_name = 'ms'
        # Mock the function that should get called
        self.dummy.spell_melting_strike = lambda target=None, spell=None: ms_success_msg

        try:
            output = StringIO()
            sys.stdout = output
            result = self.dummy.spell_handler(ms_command_name, None)

            self.assertNotIn(unsuccessful_message, output.getvalue())
        finally:
            sys.stdout = sys.__stdout__

        # Assert that it called the spell_seal_of_righteousness function
        self.assertEqual(result, ms_success_msg)

    def test_spell_handler_invalid_spell(self):
        unsuccessful_message = 'Unsuccessful cast'
        invalid_command = 'WooHoo'

        try:
            output = StringIO()
            sys.stdout = output
            result = self.dummy.spell_handler(invalid_command, None)

            self.assertIn(unsuccessful_message, output.getvalue())
        finally:
            sys.stdout = sys.__stdout__

        self.assertFalse(result)

    def test_spell_seal_of_righteousness(self):
        sor: PaladinSpell = self.dummy.learned_spells[Paladin.KEY_SEAL_OF_RIGHTEOUSNESS]
        expected_message = f'{self.dummy.name} activates {Paladin.KEY_SEAL_OF_RIGHTEOUSNESS}!'
        expected_mana = self.dummy.mana - sor.mana_cost
        self.assertFalse(self.dummy.SOR_ACTIVE)
        self.assertEqual(self.dummy.SOR_TURNS, 0)

        try:
            output = StringIO()
            sys.stdout = output

            self.dummy.spell_seal_of_righteousness(sor)

            self.assertIn(expected_message, output.getvalue())
        finally:
            sys.stdout = sys.__stdout__

        self.assertTrue(self.dummy.SOR_ACTIVE)
        self.assertEqual(self.dummy.SOR_TURNS, 3)
        self.assertEqual(self.dummy.mana, expected_mana)

if __name__ == '__main__':
    unittest.main()
<commit_msg>Test for the _spell_seal_of_righteousness_attack()<commit_after>import unittest
import sys
from io import StringIO
import inspect

from classes import Paladin
from spells import PaladinSpell
from models.spells.loader import load_paladin_spells_for_level

class PaladinTests(unittest.TestCase):
    def setUp(self):
        self.name = "Netherblood"
        self.level = 3
        self.dummy = Paladin(name=self.name, level=self.level, health=100, mana=100, strength=10)

    def test_init(self):
        """ The __init__ should load/save all the spells for the Paladin"""
        spells = [spell for level in range(1,self.level+1) for spell in load_paladin_spells_for_level(level)]

        self.assertNotEqual(len(self.dummy.learned_spells), 0)
        for spell in spells:
            self.assertIn(spell.name, self.dummy.learned_spells)
            char_spell = self.dummy.learned_spells[spell.name]
            # find the largest rank in our spells list (the char has the highest rank only)
            max_rank = list(sorted(filter(lambda x: x.name == spell.name, spells), key=lambda x: x.rank))[-1].rank

            self.assertEqual(char_spell.rank, max_rank)

    def test_leave_combat(self):
        """
        Except the normal behaviour, leave_combat should remove the SOR buff from the pally
        and reset his spell cds
        """
        self.dummy._in_combat = True
        self.dummy.SOR_ACTIVE = True
        for spell in self.dummy.learned_spells.values():
            spell._cooldown_counter = 100

        self.assertTrue(self.dummy.is_in_combat())

        self.dummy.leave_combat()

        self.assertFalse(self.dummy.is_in_combat())
        self.assertFalse(self.dummy.SOR_ACTIVE)
        # All cooldowns should be reset
        self.assertTrue(all([spell._cooldown_counter == 0 for spell in self.dummy.learned_spells.values()]))

    def test_reset_spell_cooldowns(self):
        """ The reset_spell_cooldowns goes through every spell and resets its CD"""
        for spell in self.dummy.learned_spells.values():
            spell._cooldown_counter = 100
        self.assertTrue(all([spell._cooldown_counter != 0 for spell in self.dummy.learned_spells.values()]))

        self.dummy.reset_spell_cooldowns()

        self.assertTrue(all([spell._cooldown_counter == 0 for spell in self.dummy.learned_spells.values()]))

    def test_level_up(self):
        """ Except the normal behaviour, it should learn new spells for the character """
        # empty the learned spells, it's stored as a static variable, which is not good practice but doesn't hurt in the game
        Paladin.learned_spells = {}
        pl = Paladin(name="fuck a nine to five")

        spells_to_learn = [spell.name for spell in load_paladin_spells_for_level(pl.level + 1)]
        for spell in spells_to_learn:
            self.assertNotIn(spell, pl.learned_spells)
        pl._level_up()
        for spell in spells_to_learn:
            self.assertIn(spell, pl.learned_spells)

    def test_level_up_to_level(self):
        """ Except the normal behaviour, it should learn new spells for the character """
        # empty the learned spells, it's stored as a static variable, which is not good practice but doesn't hurt in the game
        Paladin.learned_spells = {}
        pl = Paladin(name="fuck a nine to five")
        to_level = 4

        spells_to_learn = [spell for level in range(2, to_level + 1) for spell in load_paladin_spells_for_level(level)]
        for spell in spells_to_learn:
            has_not_learned_spell = spell.name not in pl.learned_spells
            has_smaller_rank = spell.rank > pl.learned_spells[spell.name].rank if not has_not_learned_spell else False
            self.assertTrue(has_not_learned_spell or has_smaller_rank)
        pl._level_up(to_level=to_level)
        for spell in spells_to_learn:
            self.assertIn(spell.name, pl.learned_spells)

    def test_lookup_and_handle_new_spells(self):
        """ Should look up the available spells for our level and learn them or update our existing ones"""
        Paladin.learned_spells = {}
        pl = Paladin(name="fuck a nine to five")
        print(pl.learned_spells)
        pl.level = 3
        spells_to_learn = [spell for spell in load_paladin_spells_for_level(pl.level)]
        for spell in spells_to_learn:
            has_not_learned_spell = spell.name not in pl.learned_spells
            has_smaller_rank = spell.rank > pl.learned_spells[spell.name].rank if not has_not_learned_spell else False
            self.assertTrue(has_not_learned_spell or has_smaller_rank)

        pl._lookup_and_handle_new_spells()

        for spell in spells_to_learn:
            self.assertIn(spell.name, pl.learned_spells)

    def test_learn_new_spell(self):
        """ Given a PaladinSpell, add it to the learned_spells dictionary"""
        spell = PaladinSpell(name="Too_Alive", rank=5)
        expected_message = f'You have learned a new spell - {spell.name}'

        self.assertNotIn(spell.name, self.dummy.learned_spells)
        try:
            output = StringIO()
            sys.stdout = output

            self.dummy.learn_new_spell(spell)

            self.assertIn(expected_message, output.getvalue())
        finally:
            sys.stdout = sys.__stdout__
        self.assertIn(spell.name, self.dummy.learned_spells)

    def test_lookup_available_spells_to_learn(self):
        """ It's a generator function returning a spell that can be learnt for the level """
        lev = 3
        expected_spells = load_paladin_spells_for_level(lev)
        generator = self.dummy._lookup_available_spells_to_learn(lev)

        self.assertTrue(inspect.isgenerator(generator))
        for spell in expected_spells:
            self.assertEqual(vars(next(generator)), vars(spell))

    def test_update_spell(self):
        """ The update_spell() function updates a spell we already have learned"""
        f_spell = PaladinSpell('Spell', rank=1)
        s_spell = PaladinSpell('Spell', rank=2)
        expected_message = f'Spell {f_spell.name} has been updated to rank {s_spell.rank}!'
        self.dummy.learn_new_spell(f_spell)

        try:
            output = StringIO()
            sys.stdout = output

            self.dummy.update_spell(s_spell)

            self.assertIn(expected_message, output.getvalue())
        finally:
            sys.stdout = sys.__stdout__

        # assert that it updated the rank
        self.assertEqual(self.dummy.learned_spells[s_spell.name].rank, s_spell.rank)
        self.assertGreater(self.dummy.learned_spells[s_spell.name].rank, f_spell.rank)

    def test_spell_handler_sor(self):
        """
        The spell handler takes spell names and casts the appropriate function
        It might work in a bad way since it's not too testable
        """
        unsuccessful_message = 'Unsuccessful cast'
        sor_success_msg = 'SOR_CASTED'
        sor_command_name = 'sor'
        # Mock the function that should get called
        self.dummy.spell_seal_of_righteousness = lambda x: sor_success_msg

        try:
            output = StringIO()
            sys.stdout = output
            result = self.dummy.spell_handler(sor_command_name, None)

            self.assertNotIn(unsuccessful_message, output.getvalue())
        finally:
            sys.stdout = sys.__stdout__

        # Assert that it called the spell_seal_of_righteousness function
        self.assertEqual(result, sor_success_msg)

    def test_spell_handler_fol(self):
        unsuccessful_message = 'Unsuccessful cast'
        fol_success_msg = 'FOL_CASTED'
        fol_command_name = 'fol'
        # Mock the function that should get called
        self.dummy.spell_flash_of_light = lambda x: fol_success_msg

        try:
            output = StringIO()
            sys.stdout = output
            result = self.dummy.spell_handler(fol_command_name, None)

            self.assertNotIn(unsuccessful_message, output.getvalue())
        finally:
            sys.stdout = sys.__stdout__

        # Assert that it called the spell_seal_of_righteousness function
        self.assertEqual(result, fol_success_msg)

    def test_spell_handler_ms(self):
        unsuccessful_message = 'Unsuccessful cast'
        ms_success_msg = 'MS_CASTED'
        ms_command_name = 'ms'
        # Mock the function that should get called
        self.dummy.spell_melting_strike = lambda target=None, spell=None: ms_success_msg

        try:
            output = StringIO()
            sys.stdout = output
            result = self.dummy.spell_handler(ms_command_name, None)

            self.assertNotIn(unsuccessful_message, output.getvalue())
        finally:
            sys.stdout = sys.__stdout__

        # Assert that it called the spell_seal_of_righteousness function
        self.assertEqual(result, ms_success_msg)

    def test_spell_handler_invalid_spell(self):
        unsuccessful_message = 'Unsuccessful cast'
        invalid_command = 'WooHoo'

        try:
            output = StringIO()
            sys.stdout = output
            result = self.dummy.spell_handler(invalid_command, None)

            self.assertIn(unsuccessful_message, output.getvalue())
        finally:
            sys.stdout = sys.__stdout__

        self.assertFalse(result)

    def test_spell_seal_of_righteousness(self):
        sor: PaladinSpell = self.dummy.learned_spells[Paladin.KEY_SEAL_OF_RIGHTEOUSNESS]
        expected_message = f'{self.dummy.name} activates {Paladin.KEY_SEAL_OF_RIGHTEOUSNESS}!'
        expected_mana = self.dummy.mana - sor.mana_cost
        self.assertFalse(self.dummy.SOR_ACTIVE)
        self.assertEqual(self.dummy.SOR_TURNS, 0)

        try:
            output = StringIO()
            sys.stdout = output

            self.dummy.spell_seal_of_righteousness(sor)

            self.assertIn(expected_message, output.getvalue())
        finally:
            sys.stdout = sys.__stdout__

        self.assertTrue(self.dummy.SOR_ACTIVE)
        self.assertEqual(self.dummy.SOR_TURNS, 3)
        self.assertEqual(self.dummy.mana, expected_mana)

    def test_spell_seal_of_righteousness_attack(self):
        sor: PaladinSpell = self.dummy.learned_spells[Paladin.KEY_SEAL_OF_RIGHTEOUSNESS]
        expected_damage = sor.damage1
        self.dummy.spell_seal_of_righteousness(sor)
        self.assertTrue(self.dummy.SOR_ACTIVE)
        self.assertEqual(self.dummy.SOR_TURNS, 3)

        result = self.dummy._spell_seal_of_righteousness_attack()

        self.assertEqual(result, expected_damage)
        self.assertEqual(self.dummy.SOR_TURNS, 2)

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


<commit_before>import unittest
import numpy.testing as testing
import numpy as np
import fitsio

from esutil.cosmology import Cosmo
from redmapper.catalog import Entry
from redmapper.cluster import Cluster
from redmapper.galaxy import GalaxyCatalog
from redmapper.background import Background
from redmapper.redsequence import RedSequenceColorPar

class BackgroundStub(Background):

    def __init__(self, filename):
        obkg = Entry.from_fits_file(filename)
        self.refmagbins = obkg.refmagbins
        self.chisqbins = obkg.chisqbins
        self.lnchisqbins = obkg.lnchisqbins
        self.zbins = obkg.zbins
        self.sigma_g = obkg.sigma_g
        self.sigma_lng = obkg.sigma_lng

class ClusterFiltersTestCase(unittest.TestCase):

    def test_nfw_filter(self):
        test_indices = np.array([46, 38,  1,  1, 11, 24, 25, 16])
        py_nfw = self.cluster._calc_radial_profile()[test_indices]
        idl_nfw = np.array([0.29360449, 0.14824243, 0.14721203, 0.14721203,
                            0.23459411, 0.31615007, 0.29307860, 0.29737136])
        testing.assert_almost_equal(py_nfw, idl_nfw)

    def test_lum_filter(self):
        test_indices = np.array([47, 19,  0, 30, 22, 48, 34, 19])
        zred_file_name = 'test_dr8_pars.fit'
        zredstr = RedSequenceColorPar(self.file_path + '/' + zred_file_name)
        maxmag = 0
        py_lum = self.cluster._calc_luminosity(zredstr, maxmag)
        idl_lum = np.array([])
        testing.assert_almost_equal(py_lum, idl_lum)

    def test_bkg_filter(self):
        test_indices = np.array([29, 16, 27,  5, 38, 35, 25, 43])
        bkg_file_name = 'test_bkg.fit'
        bkg = BackgroundStub(self.file_path + '/' + bkg_file_name)
        py_bkg = self.cluster._calc_bkg_density(bkg, Cosmo())
        idl_bkg = np.array([])
        testing.assert_almost_equal(py_bkg, idl_bkg)

    def setUp(self):
        self.cluster = Cluster(np.empty(1))
        self.file_path, file_name = 'data', 'test_cluster_members.fit'
        self.cluster.members = GalaxyCatalog.from_fits_file(self.file_path
                                                            + '/' + file_name)
        self.cluster.z = self.cluster.members.z[0]

class ClusterMembersTestCase(unittest.TestCase):

    def test_member_finding(self): pass
    def test_richness(self): pass

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

<commit_msg>All three tests fail, but there are now no errors.<commit_after>import unittest
import numpy.testing as testing
import numpy as np
import fitsio

from esutil.cosmology import Cosmo
from redmapper.catalog import Entry
from redmapper.cluster import Cluster
from redmapper.galaxy import GalaxyCatalog
from redmapper.background import Background
from redmapper.redsequence import RedSequenceColorPar

class BackgroundStub(Background):

    def __init__(self, filename):
        obkg = Entry.from_fits_file(filename)
        self.refmagbins = obkg.refmagbins
        self.chisqbins = obkg.chisqbins
        self.lnchisqbins = obkg.lnchisqbins
        self.zbins = obkg.zbins
        self.sigma_g = obkg.sigma_g
        self.sigma_lng = obkg.sigma_lng

class ClusterFiltersTestCase(unittest.TestCase):

    def test_nfw_filter(self):
        test_indices = np.array([46, 38,  1,  1, 11, 24, 25, 16])
        py_nfw = self.cluster._calc_radial_profile()[test_indices]
        idl_nfw = np.array([0.29360449, 0.14824243, 0.14721203, 0.14721203,
                            0.23459411, 0.31615007, 0.29307860, 0.29737136])
        testing.assert_almost_equal(py_nfw, idl_nfw)

    def test_lum_filter(self):
        test_indices = np.array([47, 19,  0, 30, 22, 48, 34, 19])
        zred_file_name = 'test_dr8_pars.fit'
        zredstr = RedSequenceColorPar(self.file_path + '/' + zred_file_name)
        maxmag = 1
        py_lum = self.cluster._calc_luminosity(zredstr, maxmag)
        idl_lum = np.array([])
        testing.assert_almost_equal(py_lum, idl_lum)

    def test_bkg_filter(self):
        test_indices = np.array([29, 16, 27,  5, 38, 35, 25, 43])
        bkg_file_name = 'test_bkg.fit'
        bkg = BackgroundStub(self.file_path + '/' + bkg_file_name)
        py_bkg = self.cluster._calc_bkg_density(bkg, Cosmo())
        idl_bkg = np.array([])
        testing.assert_almost_equal(py_bkg, idl_bkg)

    def setUp(self):
        self.cluster = Cluster(np.empty(1))
        self.file_path, file_name = 'data', 'test_cluster_members.fit'
        self.cluster.members = GalaxyCatalog.from_fits_file(self.file_path
                                                            + '/' + file_name)
        self.cluster.z = self.cluster.members.z[0]

class ClusterMembersTestCase(unittest.TestCase):

    def test_member_finding(self): pass
    def test_richness(self): pass

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

<|endoftext|>


<commit_before>from __future__ import print_function
import sys
import os
from os.path import realpath, dirname

try:
    import command
except ImportError:
    print('Unable to import command.  Is it installed?')
    sys.exit(1)

try:
    import py.test
except ImportError:
    print('Unable to import py.test.  Is py.test installed?')
    sys.exit(1)

# figure out the base path to use for file include
test_path = realpath(dirname(__file__))

class TestCommand:
    def test_which_bin_sleep(self):
        command.which('/bin/sleep')

    def test_which_bin_sleep2(self):
        assert command.which('sleep') == '/bin/sleep'

    def test_which_foo(self):
        with py.test.raises(command.CommandException):
            command.which('foo')

    def test_which_full_foo(self):
        with py.test.raises(command.CommandException):
            command.which('/bin/foo')

    def test_which_not_x(self):
        with py.test.raises(command.CommandException):
            command.which('/etc/hosts')

    def test_which_relative_false(self):
        command.which('false')

    def test_which_none(self):
        with py.test.raises(command.CommandException):
            command.which(None)

    def test_run_ls(self):
        response = command.run(['ls', test_path])
        assert response.exit == 0
        assert response.output == """\
__pycache__
test_command.py"""

    def test_run_failure(self):
        with py.test.raises(command.CommandException):
            command.run(['ls', 'blahblah'])

    def test_run_timeout_successs(self):
        command.run(['sleep', '1'], timeout=10)

    def test_run_timeout_failure(self):
        with py.test.raises(command.CommandException):
            command.run(['sleep', '2'], timeout=1)

<commit_msg>Add tests for the debug functionality<commit_after>from __future__ import print_function
import sys
import os
from os.path import realpath, dirname

try:
    import command
except ImportError:
    print('Unable to import command.  Is it installed?')
    sys.exit(1)

try:
    import py.test
except ImportError:
    print('Unable to import py.test.  Is py.test installed?')
    sys.exit(1)

# figure out the base path to use for file include
test_path = realpath(dirname(__file__))

class TestCommand:
    def test_which_bin_sleep(self):
        command.which('/bin/sleep')

    def test_which_bin_sleep2(self):
        assert command.which('sleep') == '/bin/sleep'

    def test_which_foo(self):
        with py.test.raises(command.CommandException):
            command.which('foo')

    def test_which_full_foo(self):
        with py.test.raises(command.CommandException):
            command.which('/bin/foo')

    def test_which_not_x(self):
        with py.test.raises(command.CommandException):
            command.which('/etc/hosts')

    def test_which_relative_false(self):
        command.which('false')

    def test_which_none(self):
        with py.test.raises(command.CommandException):
            command.which(None)

    def test_run_ls(self):
        response = command.run(['ls', test_path])
        assert response.exit == 0
        assert response.output == """\
__pycache__
test_command.py"""

    def test_run_failure(self):
        with py.test.raises(command.CommandException):
            command.run(['ls', 'blahblah'])

    def test_run_timeout_successs(self):
        command.run(['sleep', '1'], timeout=10)

    def test_run_timeout_failure(self):
        with py.test.raises(command.CommandException):
            command.run(['sleep', '2'], timeout=1)

    def test_run_debug(self, capsys):
        def debug_print(line):
            print(line)

        response = command.run(['ls', test_path], debug=debug_print)
        out, err = capsys.readouterr()

        assert response.exit == 0
        assert response.output == """\
__pycache__
test_command.py"""
        assert out == """\
__pycache__
test_command.py
"""
        assert err == ''<|endoftext|>


<commit_before># -*- encoding: utf-8 -*-
import sys

import pytest

def test_simple():
    """
    # Basic formatting

    Simple positional formatting is probably the most common use-case. Use it
    if the order of your arguments is not likely to change and you only have
    very few elements you want to concatenate.

    Since the elements are not represented by something as descriptive as a
    name this simple style should only be used to format a relatively small
    number of elements.
    """
    old_result = '%s %s' % ('one', 'two', )
    new_result = '{} {}'.format('one', 'two')

    assert old_result == new_result
    assert old_result == 'one two'  # output

def test_simple_2():
    old_result = '%d %d' % (1, 2)
    new_result = '{} {}'.format(1, 2)

    assert old_result == new_result
    assert new_result == "1 2"  # output

def test_simple_3():
    """
    With new style formatting it is possible (and in Python 2.6 even mandatory)
    to give placeholders an explicit positional index.

    This allows for re-arranging the order of display without changing the
    arguments.
    """
    new_result = '{1} {0}'.format('one', 'two')

    assert new_result == 'two one'  # output

def test_conversion_flags():
    """
    # Value conversion

    The new-style simple formatter calls by default the [`__format__()`][1]
    method of an object for its representation. If you just want to render the
    output of `str(...)` or `repr(...)` you can use the `!s` or `!r` conversion
    flags.

    In %-style you usually use `%s` for the string representation but there is
    `%r` for a `repr(...)` conversion.

    [1]: https://docs.python.org/3/reference/datamodel.html#object.__format__

    """
    class Data(object):
        def __str__(self):
            return 'str'

        def __repr__(self):
            return 'repr'

    old_result = '%s %r' % (Data(), Data())
    new_result = '{0!s} {0!r}'.format(Data())

    assert new_result == 'str repr'  # output
    assert new_result == old_result

@pytest.mark.xfail(sys.version_info < (3,), reason="!a not available in Python 2")
def test_ascii_conversion():
    """
    In Python 3 there exists an additional conversion flag that uses the output
    of `repr(...)` but uses `ascii(...)` instead.
    """
    class Data(object):
        def __repr__(self):
            return 'räpr'

    new_result = '{0!r} {0!a}'.format(Data())

    assert new_result == 'räpr r\\xe4pr'  # output

def test_string_pad_align():
    """
    # Padding and aligning strings

    By default values are formatted to take up only as many characters as
    needed to represent the content. It is however also possible to define that
    a value should be padded to a specific length.

    Unfortunately the default alignment differs between old and new style
    formatting. The old style defaults to right aligned while for new style
    it's left.

    Align right:
    """
    old_result = '%10s' % ('test', )
    new_result = '{:>10}'.format('test')

    assert old_result == new_result
    assert old_result == '      test'  # output

def test_string_pad_align_2():
    """
    Align left:
    """

    old_result = '%-10s' % ('test', )
    new_result = '{:10}'.format('test')

    assert old_result == new_result
    assert old_result == 'test      '  # output

def test_string_variable_pad_align():
    """
    By argument:

    In the previous example, the value '10' is encoded as part of the format
    string.  However, it is possible to also supply such values as an
    argument.
    """
    old_result = '%*s' % (-8, 'test')
    new_result = '{:<{}s}'.format('test', 8)

    assert old_result == new_result
    assert old_result == 'test    '  # output

def test_string_pad_align_3():
    """
    Again, new style formatting surpasses the old variant by providing more
    control over how values are padded and aligned.

    You are able to choose the padding character:
    """

    new_result = '{:_<10}'.format('test')

    assert new_result == 'test______'  # output

def test_string_pad_align_4():
    """
    And also center align values:
    """

    new_result = '{:^10}'.format('test')

    assert new_result == '   test   '  # output

def test_string_truncating():
    """
    # Truncating long strings

    Inverse to padding it is also possible to truncate overly long values
    to a specific number of characters.

    The number behind a `.` in the format specifies the precision of the
    output. For strings that means that the output is truncated to the
    specified length. In our example this would be 5 characters.
    """
    old_result = '%.5s' % ('xylophone', )
    new_result = '{:.5}'.format('xylophone')

    assert old_result == new_result
    assert old_result == 'xylop'  # output

def test_string_truncate_2():
    """
    By argument:
    """
    old_result = '%.*s' % (7, 'xylophone', )
    new_result = '{:.{}}'.format('xylophone', 7)

    assert old_result == new_result
    assert old_result == 'xylopho'  # output

def test_string_trunc_pad():
    """
    # Combining truncating and padding

    It is also possible to combine truncating and padding:
    """

    old_result = '%-10.5s' % ('xylophone', )
    new_result = '{:10.5}'.format('xylophone')

    assert old_result == new_result
    assert new_result == 'xylop     '  # output

def test_number():
    """
    # Numbers

    Of course it is also possible to format numbers.

    Integers:
    """
    old_result = '%d' % (42, )
    new_result = '{:d}'.format(42)

    assert old_result == new_result
    assert old_result == '42'  # output

def test_number_2():
    """
    Floats:
    """
    old_result = '%f' % (3.141592653589793, )
    new_result = '{:f}'.format(3.141592653589793)

    assert old_result == new_result
    assert old_result == '3.141593'  # output

def test_number_padding():
    """
    # Padding numbers

    Similar to strings numbers can also be constrained to a specific width.
    """
    old_result = '%4d' % (42, )
    new_result = '{:4d}'.format(42)

    assert old_result == new_result
    assert old_result == '  42'  # output

def test_number_padding_2():
    """
    Again similar to truncating strings the precision for floating point
    numbers limits the number of positions after the decimal point.

    For floating points the padding value represents the length of the complete
    output. In the example below we want our output to have at least 6
    characters with 2 after the decimal point.
    """
    old_result = '%06.2f' % (3.141592653589793, )
    new_result = '{:06.2f}'.format(3.141592653589793)

    assert old_result == new_result
    assert old_result == '003.14'  # output

def test_number_padding_3():
    """
    For integer values providing a precision doesn't make much sense and is
    actually forbidden in the new style (it will result in a ValueError).
    """
    old_result = '%04d' % (42, )
    new_result = '{:04d}'.format(42)

    with pytest.raises(ValueError):
        '{:04.2d}'.format(42)

    assert old_result == new_result
    assert old_result == '0042'  # output

def test_number_sign():
    """
    # Signed numbers

    By default only negative numbers are prefixed with a sign. This can be
    changed of course.
    """

    old_result = '%+d' % (42, )
    new_result = '{:+d}'.format(42)

    assert old_result == new_result
    assert old_result == '+42'  # output

def test_number_sign_2():
    """
    Use a space character to indicate that negative numbers should be prefixed
    with a minus symbol and a leading space should be used for positive ones.
    """
    old_result = '% d' % (-23, )
    new_result = '{: d}'.format(-23)

    assert old_result == new_result
    assert old_result == '-23'  # output

def test_number_sign_3():
    old_result = '% d' % (42, )
    new_result = '{: d}'.format(42)

    assert old_result == new_result
    assert old_result == ' 42'  # output

def test_number_sign_4():
    """
    New style formatting is also able to control the position of the sign
    symbol relative to the padding.
    """

    new_result = '{:=5d}'.format(-23)

    assert new_result == '-  23'  # output

def test_named_placeholders():
    """
    # Named placeholders

    Both formatting styles support named placeholders.
    """
    data = {
        'first': 'Hodor',
        'last': 'Hodor!',
    }

    old_result = '%(first)s %(last)s' % data
    new_result = '{first} {last}'.format(**data)

    assert old_result == new_result
    assert old_result == 'Hodor Hodor!'  # output

def test_named_placeholders_2():
    """
    `.format()` also accepts keyword arguments.
    """

    new_result = '{first} {last}'.format(first="Hodor", last="Hodor!")

    assert new_result == 'Hodor Hodor!'  # output

def test_getitem_and_getattr():
    """
    # Getitem and Getattr

    New style formatting allows even greater flexibility in accessing nested
    data structures.

    It supports accessing containers that support `__getitem__` like for
    example dictionaries and lists:

    """
    person = {
        'first': 'Jean-Luc',
        'last': 'Picard',
    }

    new_result = '{p[first]} {p[last]}'.format(p=person)

    assert new_result == 'Jean-Luc Picard'  # output

def test_getitem_and_getattr_2():
    data = [4, 8, 15, 16, 23, 42]

    new_result = '{d[4]} {d[5]}'.format(d=data)

    assert new_result == '23 42'  # output

def test_getitem_and_getattr_3():
    """
    As well as accessing attributes on objects via `getattr()`:
    """

    class Plant(object):
        type = "tree"

    new_result = '{p.type}'.format(p=Plant())

    assert new_result == 'tree'  # output

def test_getitem_and_getattr_4():
    """
    Both type of access can be freely mixed and arbitrarily nested:
    """

    class Plant(object):
        type = "tree"
        kinds = [{
            'name': "oak",
        }, {
            'name': "maple"
        }]

    new_result = '{p.type}: {p.kinds[0][name]}'.format(p=Plant())

    assert new_result == 'tree: oak'  # output

def test_datetime():
    """
    # Datetime

    New style formatting also allows objects to control their own
    rendering. This for example allows datetime objects to be formatted inline:
    """

    from datetime import datetime

    new_result = '{:%Y-%m-%d %H:%M}'.format(datetime(2001, 2, 3, 4, 5))

    assert new_result == '2001-02-03 04:05'  # output

def test_nested_align():
    """
    # Nested Formats

    Additionally, new style formatting allows all of the components of
    the format to be specified dynamically using nested formats.

    Nested formats can be applied to every portion of the format after
    the colon. Variable names can not be set dynamically because double
    braces are the escape characters for braces, so something like
    `'{{which}}'.format(0.1, 0.2, which=1)` would result in `'{which}'`,
    not in `'0.2'`. Braces are not allowed in attribute names and item
    indices are passed literally, so nested formats can not be used
    anywhere before the colon in a format.

    Dynamically select alignment:
    """

    new_result = '{:{align}{width}}'.format('test', align='^', width='10')

    assert new_result == '   test   '  # output

def test_nested_prec():
    """
    Dynamically selected precision:
    """

    new_result = '{:.{prec}} = {:.{prec}}'.format('Gibberish', 2.7182818284, prec=3)

    assert new_result = 'Gib = 2.72'  # output

def test_nested_prec_2():
    """
    The nested format can be used to replace *any* part of the format
    spec, so the precision example above could be rewritten as:
    """

    new_result = '{:{prec}} = {:{prec}}'.format('Gibberish', 2.7182818284, prec='.3')

    assert new_result = 'Gib = 2.72'  # output

def test_nested_date():
    """
    The components of a date-time can be set separately:
    """

    from datetime import datetime

    new_result = '{:{dfmt} {tfmt}}'.format(datetime(2001, 2, 3, 4, 5), dfmt='%Y-%m-%d', tfmt='%H:%M')

    assert new_result = '2001-02-03 04:05'  # output

def test_nested_order_1():
    """
    The nested formats can be positional arguments. Position depends
    on the order of the opening curly braces:
    """

    new_result = '{:{}{}{}.{}}'.format(2.7182818284, '>', '+', 10, 3)

    assert new_result = '     +2.72'  # output

def test_nested_order_2():
    """
    And of course keyword arguments can be added to the mix as before:
    """

    new_result = '{:{}{sign}{}.{}}'.format(2.7182818284, '>', 10, 3, sign='+')

    assert new_result = '     +2.72'  # output

def test_custom_1():
    """
    # Custom objects

    The above example works through the use of the `__format__()` magic method.
    You can define custom format handling in your own objects by overriding
    this method. This gives you complete control over the format syntax used.
    """

    class HAL9000(object):
        def __format__(self, format):
            if format == "open-the-pod-bay-doors":
                return "I'm afraid I can't do that."
            return "HAL 9000"

    new_result = '{:open-the-pod-bay-doors}'.format(HAL9000())

    assert new_result == "I'm afraid I can't do that."  # output
<commit_msg>Fixed double equals signs.<commit_after># -*- encoding: utf-8 -*-
import sys

import pytest

def test_simple():
    """
    # Basic formatting

    Simple positional formatting is probably the most common use-case. Use it
    if the order of your arguments is not likely to change and you only have
    very few elements you want to concatenate.

    Since the elements are not represented by something as descriptive as a
    name this simple style should only be used to format a relatively small
    number of elements.
    """
    old_result = '%s %s' % ('one', 'two', )
    new_result = '{} {}'.format('one', 'two')

    assert old_result == new_result
    assert old_result == 'one two'  # output

def test_simple_2():
    old_result = '%d %d' % (1, 2)
    new_result = '{} {}'.format(1, 2)

    assert old_result == new_result
    assert new_result == "1 2"  # output

def test_simple_3():
    """
    With new style formatting it is possible (and in Python 2.6 even mandatory)
    to give placeholders an explicit positional index.

    This allows for re-arranging the order of display without changing the
    arguments.
    """
    new_result = '{1} {0}'.format('one', 'two')

    assert new_result == 'two one'  # output

def test_conversion_flags():
    """
    # Value conversion

    The new-style simple formatter calls by default the [`__format__()`][1]
    method of an object for its representation. If you just want to render the
    output of `str(...)` or `repr(...)` you can use the `!s` or `!r` conversion
    flags.

    In %-style you usually use `%s` for the string representation but there is
    `%r` for a `repr(...)` conversion.

    [1]: https://docs.python.org/3/reference/datamodel.html#object.__format__

    """
    class Data(object):
        def __str__(self):
            return 'str'

        def __repr__(self):
            return 'repr'

    old_result = '%s %r' % (Data(), Data())
    new_result = '{0!s} {0!r}'.format(Data())

    assert new_result == 'str repr'  # output
    assert new_result == old_result

@pytest.mark.xfail(sys.version_info < (3,), reason="!a not available in Python 2")
def test_ascii_conversion():
    """
    In Python 3 there exists an additional conversion flag that uses the output
    of `repr(...)` but uses `ascii(...)` instead.
    """
    class Data(object):
        def __repr__(self):
            return 'räpr'

    new_result = '{0!r} {0!a}'.format(Data())

    assert new_result == 'räpr r\\xe4pr'  # output

def test_string_pad_align():
    """
    # Padding and aligning strings

    By default values are formatted to take up only as many characters as
    needed to represent the content. It is however also possible to define that
    a value should be padded to a specific length.

    Unfortunately the default alignment differs between old and new style
    formatting. The old style defaults to right aligned while for new style
    it's left.

    Align right:
    """
    old_result = '%10s' % ('test', )
    new_result = '{:>10}'.format('test')

    assert old_result == new_result
    assert old_result == '      test'  # output

def test_string_pad_align_2():
    """
    Align left:
    """

    old_result = '%-10s' % ('test', )
    new_result = '{:10}'.format('test')

    assert old_result == new_result
    assert old_result == 'test      '  # output

def test_string_variable_pad_align():
    """
    By argument:

    In the previous example, the value '10' is encoded as part of the format
    string.  However, it is possible to also supply such values as an
    argument.
    """
    old_result = '%*s' % (-8, 'test')
    new_result = '{:<{}s}'.format('test', 8)

    assert old_result == new_result
    assert old_result == 'test    '  # output

def test_string_pad_align_3():
    """
    Again, new style formatting surpasses the old variant by providing more
    control over how values are padded and aligned.

    You are able to choose the padding character:
    """

    new_result = '{:_<10}'.format('test')

    assert new_result == 'test______'  # output

def test_string_pad_align_4():
    """
    And also center align values:
    """

    new_result = '{:^10}'.format('test')

    assert new_result == '   test   '  # output

def test_string_truncating():
    """
    # Truncating long strings

    Inverse to padding it is also possible to truncate overly long values
    to a specific number of characters.

    The number behind a `.` in the format specifies the precision of the
    output. For strings that means that the output is truncated to the
    specified length. In our example this would be 5 characters.
    """
    old_result = '%.5s' % ('xylophone', )
    new_result = '{:.5}'.format('xylophone')

    assert old_result == new_result
    assert old_result == 'xylop'  # output

def test_string_truncate_2():
    """
    By argument:
    """
    old_result = '%.*s' % (7, 'xylophone', )
    new_result = '{:.{}}'.format('xylophone', 7)

    assert old_result == new_result
    assert old_result == 'xylopho'  # output

def test_string_trunc_pad():
    """
    # Combining truncating and padding

    It is also possible to combine truncating and padding:
    """

    old_result = '%-10.5s' % ('xylophone', )
    new_result = '{:10.5}'.format('xylophone')

    assert old_result == new_result
    assert new_result == 'xylop     '  # output

def test_number():
    """
    # Numbers

    Of course it is also possible to format numbers.

    Integers:
    """
    old_result = '%d' % (42, )
    new_result = '{:d}'.format(42)

    assert old_result == new_result
    assert old_result == '42'  # output

def test_number_2():
    """
    Floats:
    """
    old_result = '%f' % (3.141592653589793, )
    new_result = '{:f}'.format(3.141592653589793)

    assert old_result == new_result
    assert old_result == '3.141593'  # output

def test_number_padding():
    """
    # Padding numbers

    Similar to strings numbers can also be constrained to a specific width.
    """
    old_result = '%4d' % (42, )
    new_result = '{:4d}'.format(42)

    assert old_result == new_result
    assert old_result == '  42'  # output

def test_number_padding_2():
    """
    Again similar to truncating strings the precision for floating point
    numbers limits the number of positions after the decimal point.

    For floating points the padding value represents the length of the complete
    output. In the example below we want our output to have at least 6
    characters with 2 after the decimal point.
    """
    old_result = '%06.2f' % (3.141592653589793, )
    new_result = '{:06.2f}'.format(3.141592653589793)

    assert old_result == new_result
    assert old_result == '003.14'  # output

def test_number_padding_3():
    """
    For integer values providing a precision doesn't make much sense and is
    actually forbidden in the new style (it will result in a ValueError).
    """
    old_result = '%04d' % (42, )
    new_result = '{:04d}'.format(42)

    with pytest.raises(ValueError):
        '{:04.2d}'.format(42)

    assert old_result == new_result
    assert old_result == '0042'  # output

def test_number_sign():
    """
    # Signed numbers

    By default only negative numbers are prefixed with a sign. This can be
    changed of course.
    """

    old_result = '%+d' % (42, )
    new_result = '{:+d}'.format(42)

    assert old_result == new_result
    assert old_result == '+42'  # output

def test_number_sign_2():
    """
    Use a space character to indicate that negative numbers should be prefixed
    with a minus symbol and a leading space should be used for positive ones.
    """
    old_result = '% d' % (-23, )
    new_result = '{: d}'.format(-23)

    assert old_result == new_result
    assert old_result == '-23'  # output

def test_number_sign_3():
    old_result = '% d' % (42, )
    new_result = '{: d}'.format(42)

    assert old_result == new_result
    assert old_result == ' 42'  # output

def test_number_sign_4():
    """
    New style formatting is also able to control the position of the sign
    symbol relative to the padding.
    """

    new_result = '{:=5d}'.format(-23)

    assert new_result == '-  23'  # output

def test_named_placeholders():
    """
    # Named placeholders

    Both formatting styles support named placeholders.
    """
    data = {
        'first': 'Hodor',
        'last': 'Hodor!',
    }

    old_result = '%(first)s %(last)s' % data
    new_result = '{first} {last}'.format(**data)

    assert old_result == new_result
    assert old_result == 'Hodor Hodor!'  # output

def test_named_placeholders_2():
    """
    `.format()` also accepts keyword arguments.
    """

    new_result = '{first} {last}'.format(first="Hodor", last="Hodor!")

    assert new_result == 'Hodor Hodor!'  # output

def test_getitem_and_getattr():
    """
    # Getitem and Getattr

    New style formatting allows even greater flexibility in accessing nested
    data structures.

    It supports accessing containers that support `__getitem__` like for
    example dictionaries and lists:

    """
    person = {
        'first': 'Jean-Luc',
        'last': 'Picard',
    }

    new_result = '{p[first]} {p[last]}'.format(p=person)

    assert new_result == 'Jean-Luc Picard'  # output

def test_getitem_and_getattr_2():
    data = [4, 8, 15, 16, 23, 42]

    new_result = '{d[4]} {d[5]}'.format(d=data)

    assert new_result == '23 42'  # output

def test_getitem_and_getattr_3():
    """
    As well as accessing attributes on objects via `getattr()`:
    """

    class Plant(object):
        type = "tree"

    new_result = '{p.type}'.format(p=Plant())

    assert new_result == 'tree'  # output

def test_getitem_and_getattr_4():
    """
    Both type of access can be freely mixed and arbitrarily nested:
    """

    class Plant(object):
        type = "tree"
        kinds = [{
            'name': "oak",
        }, {
            'name': "maple"
        }]

    new_result = '{p.type}: {p.kinds[0][name]}'.format(p=Plant())

    assert new_result == 'tree: oak'  # output

def test_datetime():
    """
    # Datetime

    New style formatting also allows objects to control their own
    rendering. This for example allows datetime objects to be formatted inline:
    """

    from datetime import datetime

    new_result = '{:%Y-%m-%d %H:%M}'.format(datetime(2001, 2, 3, 4, 5))

    assert new_result == '2001-02-03 04:05'  # output

def test_nested_align():
    """
    # Nested Formats

    Additionally, new style formatting allows all of the components of
    the format to be specified dynamically using nested formats.

    Nested formats can be applied to every portion of the format after
    the colon. Variable names can not be set dynamically because double
    braces are the escape characters for braces, so something like
    `'{{which}}'.format(0.1, 0.2, which=1)` would result in `'{which}'`,
    not in `'0.2'`. Braces are not allowed in attribute names and item
    indices are passed literally, so nested formats can not be used
    anywhere before the colon in a format.

    Dynamically select alignment:
    """

    new_result = '{:{align}{width}}'.format('test', align='^', width='10')

    assert new_result == '   test   '  # output

def test_nested_prec():
    """
    Dynamically selected precision:
    """

    new_result = '{:.{prec}} = {:.{prec}}'.format('Gibberish', 2.7182818284, prec=3)

    assert new_result == 'Gib = 2.72'  # output

def test_nested_prec_2():
    """
    The nested format can be used to replace *any* part of the format
    spec, so the precision example above could be rewritten as:
    """

    new_result = '{:{prec}} = {:{prec}}'.format('Gibberish', 2.7182818284, prec='.3')

    assert new_result == 'Gib = 2.72'  # output

def test_nested_date():
    """
    The components of a date-time can be set separately:
    """

    from datetime import datetime

    new_result = '{:{dfmt} {tfmt}}'.format(datetime(2001, 2, 3, 4, 5), dfmt='%Y-%m-%d', tfmt='%H:%M')

    assert new_result == '2001-02-03 04:05'  # output

def test_nested_order_1():
    """
    The nested formats can be positional arguments. Position depends
    on the order of the opening curly braces:
    """

    new_result = '{:{}{}{}.{}}'.format(2.7182818284, '>', '+', 10, 3)

    assert new_result == '     +2.72'  # output

def test_nested_order_2():
    """
    And of course keyword arguments can be added to the mix as before:
    """

    new_result = '{:{}{sign}{}.{}}'.format(2.7182818284, '>', 10, 3, sign='+')

    assert new_result == '     +2.72'  # output

def test_custom_1():
    """
    # Custom objects

    The above example works through the use of the `__format__()` magic method.
    You can define custom format handling in your own objects by overriding
    this method. This gives you complete control over the format syntax used.
    """

    class HAL9000(object):
        def __format__(self, format):
            if format == "open-the-pod-bay-doors":
                return "I'm afraid I can't do that."
            return "HAL 9000"

    new_result = '{:open-the-pod-bay-doors}'.format(HAL9000())

    assert new_result == "I'm afraid I can't do that."  # output
<|endoftext|>


<commit_before># coding:utf-8
from base import TestBase

class TestDefault(TestBase):
    """Default tests"""

    # for debug
    # def tearDown(self):
    #     pass

    insert_position_text = \
"""
# Heading 0

# Heading 1

...

## Heading 2

...

## Heading 3

...

# Heading with anchor [with-anchor]

...
"""
    def test_before_than_TOC_should_be_ignored(self):
        toc_txt = self.commonSetup(self.insert_position_text, 13)
        self.assert_NotIn('Heading 0', toc_txt)

    def test_after_than_TOC_should_be_included(self):
        toc_txt = self.commonSetup(self.insert_position_text, 13)
        self.assert_In('Heading 1', toc_txt)
        self.assert_In('Heading 2', toc_txt)
        self.assert_In('Heading 3', toc_txt)
        self.assert_In('Heading with anchor', toc_txt)

    def test_ignore_inside_codeblock(self):
        text = \
"""

# Outside1

```
# Inseide
```

# Outside2

```

# Inseide2
# Inseide3

```
"""
        toc_txt = self.commonSetup(text)
        self.assert_In('Outside1', toc_txt)
        self.assert_In('Outside2', toc_txt)
        self.assert_NotIn('Inside1', toc_txt)
        self.assert_NotIn('Inside2', toc_txt)
        self.assert_NotIn('Inside3', toc_txt)

    def test_escape_link(self):
        text = \
"""

# This [link](http://sample.com/) is cool
"""
        toc_txt = self.commonSetup(text)
        self.assert_In('This link is cool', toc_txt)

    def test_escape_brackets(self):
        """Broken reference when header has square brackets
        https://github.com/naokazuterada/MarkdownTOC/issues/57
        """
        text = \
"""

# function(foo[, bar])
"""
        toc_txt = self.commonSetup(text)
        self.assert_In('function\(foo\[, bar\]\)', toc_txt)

    def test_spaces_in_atx_heading(self):
        text = \
"""

#Heading 0

#       Heading 1
"""
        toc_txt = self.commonSetup(text)
        self.assert_In('- Heading 0', toc_txt)
        self.assert_In('- Heading 1', toc_txt)

    def test_remove_atx_closing_seq(self):
        """ Remove closing sequence of # characters
        """
        text = \
"""

# Heading 0 #

## Heading 1       ###

# Heading 2 ##########

## Heading 3
"""
        toc_txt = self.commonSetup(text)
        self.assert_In('Heading 0\n', toc_txt)
        self.assert_In('Heading 1\n', toc_txt)
        self.assert_In('Heading 2\n', toc_txt)

    def test_id_replacement(self):
        """ Reoplace chars(or string) in id_replacements object in id string
        """
        text = \
"""

<!-- MarkdownTOC autolink=true -->

<!-- /MarkdownTOC -->

# Heading ! 0

# Heading # 1

# Heading !! 2

# Heading &and&and& 3

# <element1>

# <element2>
"""
        toc_txt = self.commonSetup(text)
        self.assert_In('- [Heading ! 0][heading--0]', toc_txt)
        self.assert_In('- [Heading # 1][heading--1]', toc_txt)
        self.assert_In('- [Heading !! 2][heading--2]', toc_txt)
        self.assert_In('- [Heading &and&and& 3][heading-andand-3]', toc_txt)
        self.assert_In('- [<element1>][element1]', toc_txt)
        self.assert_In('- [<element2>][element2]', toc_txt)

    def test_no_escape_in_code(self):
        text = \
"""

<!-- MarkdownTOC autolink=true -->

<!-- /MarkdownTOC -->

## `function(param, [optional])`
## (a static function) `greet([name])` (original, right?)
# `add(keys, command[, args][, context])`
# `get_context(key[, operator][, operand][, match_all])`
"""
        toc_txt = self.commonSetup(text)
        self.assert_In('- [`function(param, [optional])`]'
                       '[functionparam-optional', toc_txt)
        self.assert_In('- [\\(a static function\\) `greet([name])` \\(original, right?\\)]'
                       '[a-static-function-greetname-original-right]', toc_txt)
        self.assert_In('- [`add(keys, command[, args][, context])`][addkeys-command-args-context]', toc_txt)
        self.assert_In('- [`get_context(key[, operator][, operand][, match_all])`][getcontextkey-operator-operand-matchall]', toc_txt)<commit_msg>Cleanup: Remove needless line breaks<commit_after># coding:utf-8
from base import TestBase

class TestDefault(TestBase):
    """Default tests"""

    # for debug
    # def tearDown(self):
    #     pass

    insert_position_text = \
"""
# Heading 0

# Heading 1

...

## Heading 2

...

## Heading 3

...

# Heading with anchor [with-anchor]

...
"""
    def test_before_than_TOC_should_be_ignored(self):
        toc_txt = self.commonSetup(self.insert_position_text, 13)
        self.assert_NotIn('Heading 0', toc_txt)

    def test_after_than_TOC_should_be_included(self):
        toc_txt = self.commonSetup(self.insert_position_text, 13)
        self.assert_In('Heading 1', toc_txt)
        self.assert_In('Heading 2', toc_txt)
        self.assert_In('Heading 3', toc_txt)
        self.assert_In('Heading with anchor', toc_txt)

    def test_ignore_inside_codeblock(self):
        text = \
"""

# Outside1

```
# Inseide
```

# Outside2

```

# Inseide2
# Inseide3

```
"""
        toc_txt = self.commonSetup(text)
        self.assert_In('Outside1', toc_txt)
        self.assert_In('Outside2', toc_txt)
        self.assert_NotIn('Inside1', toc_txt)
        self.assert_NotIn('Inside2', toc_txt)
        self.assert_NotIn('Inside3', toc_txt)

    def test_escape_link(self):
        text = \
"""

# This [link](http://sample.com/) is cool
"""
        toc_txt = self.commonSetup(text)
        self.assert_In('This link is cool', toc_txt)

    def test_escape_brackets(self):
        """Broken reference when header has square brackets
        https://github.com/naokazuterada/MarkdownTOC/issues/57
        """
        text = \
"""

# function(foo[, bar])
"""
        toc_txt = self.commonSetup(text)
        self.assert_In('function\(foo\[, bar\]\)', toc_txt)

    def test_spaces_in_atx_heading(self):
        text = \
"""

#Heading 0

#       Heading 1
"""
        toc_txt = self.commonSetup(text)
        self.assert_In('- Heading 0', toc_txt)
        self.assert_In('- Heading 1', toc_txt)

    def test_remove_atx_closing_seq(self):
        """ Remove closing sequence of # characters"""
        text = \
"""

# Heading 0 #

## Heading 1       ###

# Heading 2 ##########

## Heading 3
"""
        toc_txt = self.commonSetup(text)
        self.assert_In('Heading 0\n', toc_txt)
        self.assert_In('Heading 1\n', toc_txt)
        self.assert_In('Heading 2\n', toc_txt)

    def test_id_replacement(self):
        """ Reoplace chars(or string) in id_replacements object in id string"""
        text = \
"""

<!-- MarkdownTOC autolink=true -->

<!-- /MarkdownTOC -->

# Heading ! 0

# Heading # 1

# Heading !! 2

# Heading &and&and& 3

# <element1>

# <element2>
"""
        toc_txt = self.commonSetup(text)
        self.assert_In('- [Heading ! 0][heading--0]', toc_txt)
        self.assert_In('- [Heading # 1][heading--1]', toc_txt)
        self.assert_In('- [Heading !! 2][heading--2]', toc_txt)
        self.assert_In('- [Heading &and&and& 3][heading-andand-3]', toc_txt)
        self.assert_In('- [<element1>][element1]', toc_txt)
        self.assert_In('- [<element2>][element2]', toc_txt)

    def test_no_escape_in_code(self):
        text = \
"""

<!-- MarkdownTOC autolink=true -->

<!-- /MarkdownTOC -->

## `function(param, [optional])`
## (a static function) `greet([name])` (original, right?)
# `add(keys, command[, args][, context])`
# `get_context(key[, operator][, operand][, match_all])`
"""
        toc_txt = self.commonSetup(text)
        self.assert_In('- [`function(param, [optional])`]'
                       '[functionparam-optional', toc_txt)
        self.assert_In('- [\\(a static function\\) `greet([name])` \\(original, right?\\)]'
                       '[a-static-function-greetname-original-right]', toc_txt)
        self.assert_In('- [`add(keys, command[, args][, context])`][addkeys-command-args-context]', toc_txt)
        self.assert_In('- [`get_context(key[, operator][, operand][, match_all])`][getcontextkey-operator-operand-matchall]', toc_txt)<|endoftext|>


<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-

import unittest
import re
from mecabwrap.domecab import do_mecab
from mecabwrap.domecab import do_mecab_vec
from mecabwrap.domecab import do_mecab_iter

class TestDomecab(unittest.TestCase):
    def test_wakati(self):
        out = do_mecab(u'すもももももももものうち', '-Owakati')
        self.assertEqual(out.strip(), u'すもも も もも も もも の うち')

    def test_default(self):
        out = do_mecab(u'メロンパンを食べる')
        lbs = re.findall(r'\n', out)
        self.assertEqual(len(lbs), 5)

        words = re.findall(r'[^\t\n]+\t', out)
        words = [w[:-1] for w in words]
        self.assertEqual(words, [u'メロン', u'パン', u'を', u'食べる'])

class TestDomecabVec(unittest.TestCase):
    def test_vec(self):
        ins = [u'春はあけぼの', u'やうやう白くなりゆく山際']
        out = do_mecab_vec(ins, outpath=None)
        lbs = re.findall(r'\n', out)
        self.assertEqual(len(lbs), 10)

        words = re.findall(r'[^\t\n]+\t', out)
        words = [w[:-1] for w in words]
        self.assertEqual(
            words,
            [u'春', u'は', u'あけぼの', u'やうやう',
             u'白く', u'なり', u'ゆく', u'山際']
        )

        lines = out.split('\n')
        lines = [line.strip() for line in lines]
        self.assertEqual(lines[3], 'EOS')
        self.assertEqual(lines[9], 'EOS')

class TestDomecabIter(unittest.TestCase):
    def test_iter(self):
        ins = [u'となりの客はよく柿食う客だ', u'バスガス爆発']
        ct = 0
        for line in do_mecab_iter(ins, byline=False):
            ct += 1
        self.assertEqual(ct, 2)

        ct = 0
        for line in do_mecab_iter(ins, '-Owakati', byline=True):
            ct += 1
        self.assertEqual(ct, 2)

class TestMultipleOptions(unittest.TestCase):
    def test_multiple_options(self):
        out = do_mecab(u"すもももももももものうち", '-Bbegin\n', '-Eend\n')
        out = out.strip().split('\n')
        self.assertEqual(out[0] , 'begin')
        self.assertEqual(out[-1], 'end')

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

<commit_msg>CR or LF+CR case considered in test<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-

import unittest
import re
from mecabwrap.domecab import do_mecab
from mecabwrap.domecab import do_mecab_vec
from mecabwrap.domecab import do_mecab_iter

class TestDomecab(unittest.TestCase):
    def test_wakati(self):
        out = do_mecab(u'すもももももももものうち', '-Owakati')
        self.assertEqual(out.strip(), u'すもも も もも も もも の うち')

    def test_default(self):
        out = do_mecab(u'メロンパンを食べる')
        lbs = re.findall(r'\n', out)
        self.assertEqual(len(lbs), 5)

        words = re.findall(r'[^\t\n]+\t', out)
        words = [w[:-1] for w in words]
        self.assertEqual(words, [u'メロン', u'パン', u'を', u'食べる'])

class TestDomecabVec(unittest.TestCase):
    def test_vec(self):
        ins = [u'春はあけぼの', u'やうやう白くなりゆく山際']
        out = do_mecab_vec(ins, outpath=None)
        lbs = re.findall(r'\n', out)
        self.assertEqual(len(lbs), 10)

        words = re.findall(r'[^\t\n]+\t', out)
        words = [w[:-1] for w in words]
        self.assertEqual(
            words,
            [u'春', u'は', u'あけぼの', u'やうやう',
             u'白く', u'なり', u'ゆく', u'山際']
        )

        lines = out.split('\n')
        lines = [line.strip() for line in lines]
        self.assertEqual(lines[3], 'EOS')
        self.assertEqual(lines[9], 'EOS')

class TestDomecabIter(unittest.TestCase):
    def test_iter(self):
        ins = [u'となりの客はよく柿食う客だ', u'バスガス爆発']
        ct = 0
        for line in do_mecab_iter(ins, byline=False):
            ct += 1
        self.assertEqual(ct, 2)

        ct = 0
        for line in do_mecab_iter(ins, '-Owakati', byline=True):
            ct += 1
        self.assertEqual(ct, 2)

class TestMultipleOptions(unittest.TestCase):
    def test_multiple_options(self):
        out = do_mecab(u"すもももももももものうち", '-Bbegin\n', '-Eend\n')
        out = out.strip()
        out = re.split('(\r\n)|(\n)|(\r)', out)
        self.assertEqual(out[0], 'begin')
        self.assertEqual(out[-1], 'end')

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

<|endoftext|>


<commit_before>import unittest
import lxml.etree as etree
import urllib
import subprocess

from tests.common import validate, URL

class SayHello(unittest.TestCase):

    def setUp(self):

        self.url = URL + '?service=wps&request=execute&identifier=say_hello&version=1.0.0&datainputs=name=ahoj'
        self.schema_url = 'http://schemas.opengis.net/wps/1.0.0/wpsExecute_response.xsd'

    def test_valid(self):

        assert validate(self.url, self.schema_url)

def load_tests(loader=None, tests=None, pattern=None):
    if not loader:
        loader = unittest.TestLoader()
    suite_list = [
        loader.loadTestsFromTestCase(SayHello),
    ]
    return unittest.TestSuite(suite_list)
<commit_msg>adding execute lineage test<commit_after>"""Test various processes
"""
import unittest

from tests.common import validate, URL

class SayHello(unittest.TestCase):
    """Test sayhello process
    """

    def setUp(self):

        self.schema_url = 'http://schemas.opengis.net/wps/1.0.0/wpsExecute_response.xsd'

    def test_valid(self):
        "GET Execute request"

        url = URL + '?service=wps&request=execute&identifier=say_hello&version=1.0.0&datainputs=name=ahoj'
        assert validate(url, self.schema_url)

    def test_valid_lineage(self):
        "GET Execute request, lineage=true"

        url = URL + '?service=wps&request=execute&identifier=say_hello&version=1.0.0&datainputs=name=ahoj&lineage=true'
        assert validate(url, self.schema_url)

def load_tests(loader=None, tests=None, pattern=None):
    if not loader:
        loader = unittest.TestLoader()
    suite_list = [
        loader.loadTestsFromTestCase(SayHello),
    ]
    return unittest.TestSuite(suite_list)
<|endoftext|>