<commit_before>#-------------------------------------------------------------------------------
# Name:        sample_template.py
#
# Purpose:     Testing GitHub as well as to show how to manage arguments to
#              a script
#
# Author:      Hal Watson (hal.watson@state.mn.us)
#
# Created:     12/20/2013
#
# Requires:    Python 2.7
#
#
#-------------------------------------------------------------------------------

def main():

    import sys
    #import os
    #import arcpy

    # ---------- Incoming Arguments/Parameters ----------

    # If no arguments were passed from command line, print the usage and exit
    if len(sys.argv[1:]) < 1:
        print "python_script.py <arg1>"
        exit(1)

    # Get the incoming argument(s)  argv[0] is the script name by default
    #                               argv[1] is first real argument/parameter
    arg1 = sys.argv[1]

    # ---------------------------------------------------

    # Adding some changes so I can commit again
    # One more time, another change, another change

if __name__ == '__main__':
    main()
<commit_msg>test change<commit_after>#-------------------------------------------------------------------------------
# Name:        sample_template.py
#
# Purpose:     Testing GitHub as well as to show how to manage arguments to
#              a script
#
# Author:      Hal Watson (hal.watson@state.mn.us)
#
# Created:     12/20/2013
#
# Requires:    Python 2.7
#
#
#-------------------------------------------------------------------------------

def main():

    import sys
    #import os
    #import arcpy

    # ---------- Incoming Arguments/Parameters ----------

    # If no arguments were passed from command line, print the usage and exit
    if len(sys.argv[1:]) < 1:
        print "python_script.py <arg1>"
        exit(1)

    # Get the incoming argument(s)  argv[0] is the script name by default
    #                               argv[1] is first real argument/parameter
    arg1 = sys.argv[1]

    # ---------------------------------------------------

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


<commit_before>from django.test import TestCase
from django.db.models.fields import NOT_PROVIDED
from app.models import FieldsWithOptionsModel
from google.appengine.api.datastore import Get
from google.appengine.ext.db import Key
from google.appengine.api.datastore_types import Text, Category, Email, Link, \
    PhoneNumber, PostalAddress, Text, Blob, ByteString, GeoPt, IM, Key, \
    Rating, BlobKey
from google.appengine.api import users
import datetime

class FieldOptionsTest(TestCase):
    def testOptions(self):
        entity = FieldsWithOptionsModel()
        # try to save the entity with non-nullable field time set to None, should
        # raise an exception
        self.assertRaises(ValueError, entity.save)

        time = datetime.datetime.now().time()
        entity.time = time
        try:
            entity.save()
        except:
            self.fail()

        # check if primary_key=True is set correct for the saved entity
        self.assertEquals(entity.pk, u'app-engine@scholardocs.com')
        gae_entity = Get(Key.from_path(FieldsWithOptionsModel._meta.db_table,
            entity.pk))
        self.assertTrue(gae_entity is not None)
        self.assertEquals(gae_entity.key().name(), u'app-engine@scholardocs.com')

        # check if default values are set correct on the db level
        for field in FieldsWithOptionsModel._meta.local_fields:
            if field.default and field.default != NOT_PROVIDED:
                self.assertEquals(gae_entity[field.column], field.default)
            elif field.column == 'time':
                self.assertEquals(gae_entity[field.column], datetime.datetime(
                    1970, 1, 1, time.hour, time.minute, time.second, time.microsecond))
            elif field.null:
                self.assertEquals(gae_entity[field.column], None)

        # check if default values are set correct on the model instance level
        entity = FieldsWithOptionsModel.objects.get()
        for field in FieldsWithOptionsModel._meta.local_fields:
            if field.default and field.default != NOT_PROVIDED:
                self.assertEquals(getattr(entity, field.column), field.default)
            elif field.column == 'time':
                self.assertEquals(getattr(entity, field.column), time)
            elif field.null:
                self.assertEquals(getattr(entity, field.column), None)

        # check if nullable field with default values can be set to None
        entity.slug = None
        entity.positiv_small_integer = None
        try:
            entity.save()
        except:
            self.fail()

        # check if slug and positiv_small_integer will be retrieved with values
        # set to None (on db level and model instance level)
        gae_entity = Get(Key.from_path(FieldsWithOptionsModel._meta.db_table,
            entity.pk))
        self.assertEquals(gae_entity[FieldsWithOptionsModel._meta.get_field_by_name(
            'slug')[0].column], None)
        self.assertEquals(gae_entity[FieldsWithOptionsModel._meta.get_field_by_name(
            'positiv_small_integer')[0].column], None)

        # on the model instance level
        entity = FieldsWithOptionsModel.objects.get()
        self.assertEquals(getattr(entity, FieldsWithOptionsModel._meta.get_field_by_name(
            'slug')[0].column), None)
        self.assertEquals(getattr(entity, FieldsWithOptionsModel._meta.get_field_by_name(
            'positiv_small_integer')[0].column), None)

        # TODO: check db_column option
        # TODO: change the primary key and check if a new instance with the
        # changed primary key will be saved (not in this test class)
        <commit_msg>testing for primary_key field now works correctly<commit_after>from django.test import TestCase
from django.db.models.fields import NOT_PROVIDED
from app.models import FieldsWithOptionsModel
from google.appengine.api.datastore import Get
from google.appengine.ext.db import Key
from google.appengine.api.datastore_types import Text, Category, Email, Link, \
    PhoneNumber, PostalAddress, Text, Blob, ByteString, GeoPt, IM, Key, \
    Rating, BlobKey
from google.appengine.api import users
import datetime

class FieldOptionsTest(TestCase):
    def testOptions(self):
        entity = FieldsWithOptionsModel()
        # try to save the entity with non-nullable field time set to None, should
        # raise an exception
        self.assertRaises(ValueError, entity.save)

        time = datetime.datetime.now().time()
        entity.time = time
        try:
            entity.save()
        except:
            self.fail()

        # check if primary_key=True is set correct for the saved entity
        self.assertEquals(entity.pk, u'app-engine@scholardocs.com')
        gae_entity = Get(Key.from_path(FieldsWithOptionsModel._meta.db_table,
            entity.pk))
        self.assertTrue(gae_entity is not None)
        self.assertEquals(gae_entity.key().name(), u'app-engine@scholardocs.com')

        # check if default values are set correct on the db level, primary_key field
        # is not stored at the db level
        for field in FieldsWithOptionsModel._meta.local_fields:
            if field.default and field.default != NOT_PROVIDED and not \
                    field.primary_key:
                self.assertEquals(gae_entity[field.column], field.default)
            elif field.column == 'time':
                self.assertEquals(gae_entity[field.column], datetime.datetime(
                    1970, 1, 1, time.hour, time.minute, time.second, time.microsecond))
            elif field.null:
                self.assertEquals(gae_entity[field.column], None)

        # check if default values are set correct on the model instance level
        entity = FieldsWithOptionsModel.objects.get()
        for field in FieldsWithOptionsModel._meta.local_fields:
            if field.default and field.default != NOT_PROVIDED:
                self.assertEquals(getattr(entity, field.column), field.default)
            elif field.column == 'time':
                self.assertEquals(getattr(entity, field.column), time)
            elif field.null:
                self.assertEquals(getattr(entity, field.column), None)

        # check if nullable field with default values can be set to None
        entity.slug = None
        entity.positiv_small_integer = None
        try:
            entity.save()
        except:
            self.fail()

        # check if slug and positiv_small_integer will be retrieved with values
        # set to None (on db level and model instance level)
        gae_entity = Get(Key.from_path(FieldsWithOptionsModel._meta.db_table,
            entity.pk))
        self.assertEquals(gae_entity[FieldsWithOptionsModel._meta.get_field_by_name(
            'slug')[0].column], None)
        self.assertEquals(gae_entity[FieldsWithOptionsModel._meta.get_field_by_name(
            'positiv_small_integer')[0].column], None)

        # on the model instance level
        entity = FieldsWithOptionsModel.objects.get()
        self.assertEquals(getattr(entity, FieldsWithOptionsModel._meta.get_field_by_name(
            'slug')[0].column), None)
        self.assertEquals(getattr(entity, FieldsWithOptionsModel._meta.get_field_by_name(
            'positiv_small_integer')[0].column), None)

        # TODO: check db_column option
        # TODO: change the primary key and check if a new instance with the
        # changed primary key will be saved (not in this test class)
        <|endoftext|>


<commit_before># -*- coding: utf-8 -*-
# pylint: disable=unused-variable
"""These test the natcmp() function.

Note that these tests are only relevant for Python version < 3.
"""
import sys
from functools import partial

import pytest
from hypothesis import given
from hypothesis.strategies import floats, integers, lists

from natsort import ns

from natsort.compat.py23 import py23_cmp

PY_VERSION = float(sys.version[:3])

if PY_VERSION < 3:
    from natsort import natcmp

class Comparable(object):
    """Stub class for testing natcmp functionality."""
    def __init__(self, value):
        self.value = value

    def __cmp__(self, other):
        return natcmp(self.value, other.value)

@pytest.mark.skipif(PY_VERSION >= 3.0, reason='cmp() deprecated in Python 3')
def test__classes_can_be_compared():
    one = Comparable("1")
    two = Comparable("2")
    another_two = Comparable("2")
    ten = Comparable("10")

    assert ten > two == another_two > one

@pytest.mark.skipif(PY_VERSION >= 3.0, reason='cmp() deprecated in Python 3')
def test__classes_can_utilize_max_or_min():
    comparables = [Comparable(i) for i in range(10)]

    assert max(comparables) == comparables[-1]
    assert min(comparables) == comparables[0]

@pytest.mark.skipif(PY_VERSION >= 3.0, reason='cmp() deprecated in Python 3')
@given(integers(), integers())
def test__natcmp_works_the_same_for_integers_as_cmp(x, y):
    assert py23_cmp(x, y) == natcmp(x, y)

@pytest.mark.skipif(PY_VERSION >= 3.0, reason='cmp() deprecated in Python 3')
@given(floats(allow_nan=False), floats(allow_nan=False))
def test__natcmp_works_the_same_for_floats_as_cmp(x, y):
    assert py23_cmp(x, y) == natcmp(x, y)

@pytest.mark.skipif(PY_VERSION >= 3.0, reason='cmp() deprecated in Python 3')
@given(lists(elements=integers()))
def test_sort_strings_with_numbers(a_list):
    strings = [str(var) for var in a_list]
    natcmp_sorted = sorted(strings, cmp=partial(natcmp, alg=ns.REAL))

    assert sorted(a_list) == [int(var) for var in natcmp_sorted]
<commit_msg>Added coverage to the caching mechanism.<commit_after># -*- coding: utf-8 -*-
# pylint: disable=unused-variable
"""These test the natcmp() function.

Note that these tests are only relevant for Python version < 3.
"""
import sys
from functools import partial

import pytest
from hypothesis import given
from hypothesis.strategies import floats, integers, lists

from natsort import ns

from natsort.compat.py23 import py23_cmp

PY_VERSION = float(sys.version[:3])

if PY_VERSION < 3:
    from natsort import natcmp

class Comparable(object):
    """Stub class for testing natcmp functionality."""
    def __init__(self, value):
        self.value = value

    def __cmp__(self, other):
        return natcmp(self.value, other.value)

@pytest.mark.skipif(PY_VERSION >= 3.0, reason='cmp() deprecated in Python 3')
def test__classes_can_be_compared():
    one = Comparable("1")
    two = Comparable("2")
    another_two = Comparable("2")
    ten = Comparable("10")

    assert ten > two == another_two > one

@pytest.mark.skipif(PY_VERSION >= 3.0, reason='cmp() deprecated in Python 3')
def test__keys_are_being_cached():
    natcmp.cached_keys = {}
    assert len(natcmp.cached_keys) == 0
    natcmp(0, 0)
    assert len(natcmp.cached_keys) == 1
    natcmp(0, 0)
    assert len(natcmp.cached_keys) == 1
    natcmp(0, 0, alg=ns.FLOAT | ns.IGNORECASE | ns.LOCALEALPHA)
    assert len(natcmp.cached_keys) == 2
    natcmp(0, 0, alg=ns.FLOAT | ns.IGNORECASE | ns.LOCALEALPHA)
    assert len(natcmp.cached_keys) == 2

@pytest.mark.skipif(PY_VERSION >= 3.0, reason='cmp() deprecated in Python 3')
def test__classes_can_utilize_max_or_min():
    comparables = [Comparable(i) for i in range(10)]

    assert max(comparables) == comparables[-1]
    assert min(comparables) == comparables[0]

@pytest.mark.skipif(PY_VERSION >= 3.0, reason='cmp() deprecated in Python 3')
@given(integers(), integers())
def test__natcmp_works_the_same_for_integers_as_cmp(x, y):
    assert py23_cmp(x, y) == natcmp(x, y)

@pytest.mark.skipif(PY_VERSION >= 3.0, reason='cmp() deprecated in Python 3')
@given(floats(allow_nan=False), floats(allow_nan=False))
def test__natcmp_works_the_same_for_floats_as_cmp(x, y):
    assert py23_cmp(x, y) == natcmp(x, y)

@pytest.mark.skipif(PY_VERSION >= 3.0, reason='cmp() deprecated in Python 3')
@given(lists(elements=integers()))
def test_sort_strings_with_numbers(a_list):
    strings = [str(var) for var in a_list]
    natcmp_sorted = sorted(strings, cmp=partial(natcmp, alg=ns.REAL))

    assert sorted(a_list) == [int(var) for var in natcmp_sorted]
<|endoftext|>


<commit_before>from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import os
import re
import logging
import operator
import itertools
import collections
import xml.etree.ElementTree as ET
from indra.util import read_unicode_csv
from indra.statements import *
import indra.databases.hgnc_client as hgnc_client
import indra.databases.uniprot_client as up_client
from indra.util import UnicodeXMLTreeBuilder as UTB

logger = logging.getLogger('cwms')

class CWMSProcessor(object):
    """The CWMSProcessor currently extracts causal relationships between
    terms (nouns) in EKB. In the future, this processor can be extended to
    extract other types of relations, or to extract relations involving
    events.

    For more details on the TRIPS EKB XML format, see
    http://trips.ihmc.us/parser/cgi/drum

    Parameters
    ----------
    xml_string : str
        A TRIPS extraction knowledge base (EKB) in XML format as a string.

    Attributes
    ----------
    tree : xml.etree.ElementTree.Element
        An ElementTree object representation of the TRIPS EKB XML.
    doc_id: str
        Document ID
    statements : list[indra.statements.Statement]
        A list of INDRA Statements that were extracted from the EKB.
    sentences : dict[str: str]
        The list of all sentences in the EKB with their IDs
    paragraphs : dict[str: str]
        The list of all paragraphs in the EKB with their IDs
    par_to_sec : dict[str: str]
        A map from paragraph IDs to their associated section types
    """
    def __init__(self, xml_string):
        # Parse XML
        try:
            self.tree = ET.XML(xml_string, parser=UTB())
        except ET.ParseError:
            logger.error('Could not parse XML string')
            self.tree = None
            return

        # Get the document ID from the EKB tag.
        self.doc_id = self.tree.attrib.get('id')

        # Store all paragraphs and store all sentences in a data structure
        paragraph_tags = self.tree.findall('input/paragraphs/paragraph')
        sentence_tags = self.tree.findall('input/sentences/sentence')
        self.paragraphs = {p.attrib['id']: p.text for p in paragraph_tags}
        self.sentences = {s.attrib['id']: s.text for s in sentence_tags}
        self.par_to_sec = {p.attrib['id']: p.attrib.get('sec-type')
                           for p in paragraph_tags}

        # Extract statements
        self.statements = []
        self.extract_noun_causal_relations()
        self.extract_noun_inhibit_relations()
        self.extract_noun_influence_relations()

    def extract_noun_causal_relations(self):
        """Extracts causal relationships between two nouns/terms (as opposed to
        events)
        """
        # Search for causal connectives of type ONT::CAUSE
        ccs = self.tree.findall("CC/[type='ONT::CAUSE']")
        for cc in ccs:
            # Each cause should involve a factor term and an outcome term
            factor = cc.find("arg/[@role=':FACTOR']")
            outcome = cc.find("arg/[@role=':OUTCOME']")

            self.make_statement_noun_cause_effect(cc, factor, outcome,
                                                  Influence)

    def extract_noun_inhibit_relations(self):
        """Extracts relationships involving one term/noun inhibiting another
        term/noun"""
        events = self.tree.findall("EVENT/[type='ONT::INHIBIT']")
        for event in events:
            # Each inhibit event should involve an agent and an affected
            agent = event.find("*[@role=':AGENT']")
            affected = event.find("*[@role=':AFFECTED']")

            self.make_statement_noun_cause_effect(event, agent, affected,
                                                  Inhibition)

    def extract_noun_influence_relations(self):
        """Extracts relationships with one term influencing another term."""
        ccs = self.tree.findall("CC/[type='ONT::INFLUENCE']")
        for cc in ccs:
            # Each cause should involve a factor term and an outcome term
            factor = cc.find("arg/[@role=':FACTOR']")
            outcome = cc.find("arg/[@role=':OUTCOME']")

            self.make_statement_noun_cause_effect(cc, factor, outcome,
                                                  Influence)

    def make_statement_noun_cause_effect(self, event_element,
                                         cause, affected, statement_type):

        # Only process if both the cause and affected are present
        if cause is None or affected is None:
            return

        # Get the term with the given cause id
        cause_id = cause.attrib.get('id')
        cause_term = self.tree.find("TERM/[@id='%s']" % cause_id)
        if cause_term is None:
            return

        # Get the cause's text and use it to construct an Agent
        cause_text_element = cause_term.find('text')
        if cause_text_element is None:
            return
        cause_text = cause_text_element.text
        cause_agent = Agent(cause_text, db_refs={'TEXT': cause_text})

        # Get the term with the given affected id
        affected_id = affected.attrib.get('id')
        affected_term = self.tree.find("TERM/[@id='%s']" % affected_id)
        if affected_term is None:
            return

        # Get the affected's text and use it to construct an Agent
        affected_text_element = affected_term.find('text')
        if affected_text_element is None:
            return
        affected_text = affected_text_element.text
        affected_agent = Agent(affected_text, db_refs={'TEXT': affected_text})

        # Construct evidence
        ev = self._get_evidence(event_element)
        ev.epistemics['direct'] = False

        # Make statement
        st = statement_type(cause_agent, affected_agent, evidence=[ev])
        self.statements.append(st)

    def _get_evidence(self, event_tag):
        text = self._get_evidence_text(event_tag)
        sec = self._get_section(event_tag)
        epi = {}
        if sec:
            epi['section_type'] = sec
        ev = Evidence(source_api='cwmsreader', text=text, pmid=self.doc_id,
                      epistemics=epi)
        return ev

    def _get_evidence_text(self, event_tag):
        """Extract the evidence for an event.

        Pieces of text linked to an EVENT are fragments of a sentence. The
        EVENT refers to the paragraph ID and the "uttnum", which corresponds
        to a sentence ID. Here we find and return the full sentence from which
        the event was taken.
        """
        par_id = event_tag.attrib.get('paragraph')
        uttnum = event_tag.attrib.get('uttnum')
        event_text = event_tag.find('text')
        if self.sentences is not None and uttnum is not None:
            sentence = self.sentences[uttnum]
        elif event_text is not None:
            sentence = event_text.text
        else:
            sentence = None
        return sentence

    def _get_section(self, event_tag):
        par_id = event_tag.attrib.get('paragraph')
        sec = self.par_to_sec.get(par_id)
        return sec
<commit_msg>Bring statements initialization up front<commit_after>from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import os
import re
import logging
import operator
import itertools
import collections
import xml.etree.ElementTree as ET
from indra.util import read_unicode_csv
from indra.statements import *
import indra.databases.hgnc_client as hgnc_client
import indra.databases.uniprot_client as up_client
from indra.util import UnicodeXMLTreeBuilder as UTB

logger = logging.getLogger('cwms')

class CWMSProcessor(object):
    """The CWMSProcessor currently extracts causal relationships between
    terms (nouns) in EKB. In the future, this processor can be extended to
    extract other types of relations, or to extract relations involving
    events.

    For more details on the TRIPS EKB XML format, see
    http://trips.ihmc.us/parser/cgi/drum

    Parameters
    ----------
    xml_string : str
        A TRIPS extraction knowledge base (EKB) in XML format as a string.

    Attributes
    ----------
    tree : xml.etree.ElementTree.Element
        An ElementTree object representation of the TRIPS EKB XML.
    doc_id: str
        Document ID
    statements : list[indra.statements.Statement]
        A list of INDRA Statements that were extracted from the EKB.
    sentences : dict[str: str]
        The list of all sentences in the EKB with their IDs
    paragraphs : dict[str: str]
        The list of all paragraphs in the EKB with their IDs
    par_to_sec : dict[str: str]
        A map from paragraph IDs to their associated section types
    """
    def __init__(self, xml_string):
        self.statements = []
        # Parse XML
        try:
            self.tree = ET.XML(xml_string, parser=UTB())
        except ET.ParseError:
            logger.error('Could not parse XML string')
            self.tree = None
            return

        # Get the document ID from the EKB tag.
        self.doc_id = self.tree.attrib.get('id')

        # Store all paragraphs and store all sentences in a data structure
        paragraph_tags = self.tree.findall('input/paragraphs/paragraph')
        sentence_tags = self.tree.findall('input/sentences/sentence')
        self.paragraphs = {p.attrib['id']: p.text for p in paragraph_tags}
        self.sentences = {s.attrib['id']: s.text for s in sentence_tags}
        self.par_to_sec = {p.attrib['id']: p.attrib.get('sec-type')
                           for p in paragraph_tags}

        # Extract statements
        self.extract_noun_causal_relations()
        self.extract_noun_inhibit_relations()
        self.extract_noun_influence_relations()

    def extract_noun_causal_relations(self):
        """Extracts causal relationships between two nouns/terms (as opposed to
        events)
        """
        # Search for causal connectives of type ONT::CAUSE
        ccs = self.tree.findall("CC/[type='ONT::CAUSE']")
        for cc in ccs:
            # Each cause should involve a factor term and an outcome term
            factor = cc.find("arg/[@role=':FACTOR']")
            outcome = cc.find("arg/[@role=':OUTCOME']")

            self.make_statement_noun_cause_effect(cc, factor, outcome,
                                                  Influence)

    def extract_noun_inhibit_relations(self):
        """Extracts relationships involving one term/noun inhibiting another
        term/noun"""
        events = self.tree.findall("EVENT/[type='ONT::INHIBIT']")
        for event in events:
            # Each inhibit event should involve an agent and an affected
            agent = event.find("*[@role=':AGENT']")
            affected = event.find("*[@role=':AFFECTED']")

            self.make_statement_noun_cause_effect(event, agent, affected,
                                                  Inhibition)

    def extract_noun_influence_relations(self):
        """Extracts relationships with one term influencing another term."""
        ccs = self.tree.findall("CC/[type='ONT::INFLUENCE']")
        for cc in ccs:
            # Each cause should involve a factor term and an outcome term
            factor = cc.find("arg/[@role=':FACTOR']")
            outcome = cc.find("arg/[@role=':OUTCOME']")

            self.make_statement_noun_cause_effect(cc, factor, outcome,
                                                  Influence)

    def make_statement_noun_cause_effect(self, event_element,
                                         cause, affected, statement_type):

        # Only process if both the cause and affected are present
        if cause is None or affected is None:
            return

        # Get the term with the given cause id
        cause_id = cause.attrib.get('id')
        cause_term = self.tree.find("TERM/[@id='%s']" % cause_id)
        if cause_term is None:
            return

        # Get the cause's text and use it to construct an Agent
        cause_text_element = cause_term.find('text')
        if cause_text_element is None:
            return
        cause_text = cause_text_element.text
        cause_agent = Agent(cause_text, db_refs={'TEXT': cause_text})

        # Get the term with the given affected id
        affected_id = affected.attrib.get('id')
        affected_term = self.tree.find("TERM/[@id='%s']" % affected_id)
        if affected_term is None:
            return

        # Get the affected's text and use it to construct an Agent
        affected_text_element = affected_term.find('text')
        if affected_text_element is None:
            return
        affected_text = affected_text_element.text
        affected_agent = Agent(affected_text, db_refs={'TEXT': affected_text})

        # Construct evidence
        ev = self._get_evidence(event_element)
        ev.epistemics['direct'] = False

        # Make statement
        st = statement_type(cause_agent, affected_agent, evidence=[ev])
        self.statements.append(st)

    def _get_evidence(self, event_tag):
        text = self._get_evidence_text(event_tag)
        sec = self._get_section(event_tag)
        epi = {}
        if sec:
            epi['section_type'] = sec
        ev = Evidence(source_api='cwmsreader', text=text, pmid=self.doc_id,
                      epistemics=epi)
        return ev

    def _get_evidence_text(self, event_tag):
        """Extract the evidence for an event.

        Pieces of text linked to an EVENT are fragments of a sentence. The
        EVENT refers to the paragraph ID and the "uttnum", which corresponds
        to a sentence ID. Here we find and return the full sentence from which
        the event was taken.
        """
        par_id = event_tag.attrib.get('paragraph')
        uttnum = event_tag.attrib.get('uttnum')
        event_text = event_tag.find('text')
        if self.sentences is not None and uttnum is not None:
            sentence = self.sentences[uttnum]
        elif event_text is not None:
            sentence = event_text.text
        else:
            sentence = None
        return sentence

    def _get_section(self, event_tag):
        par_id = event_tag.attrib.get('paragraph')
        sec = self.par_to_sec.get(par_id)
        return sec
<|endoftext|>


<commit_before>if __name__ == "__main__":
    __version__ = "0.10.0"
else:
    from . import animatedsprite
    from . import tilemap
    from . import layers
    from . import camera
<commit_msg>release 0.10.1<commit_after>if __name__ == "__main__":
    __version__ = "0.10.1"
else:
    from . import animatedsprite
    from . import tilemap
    from . import layers
    from . import camera
<|endoftext|>


<commit_before>"""
Provides tests for the syncing functionalities in django entity.
"""
from django.contrib.contenttypes.models import ContentType
from django.core.management import call_command
from django.db.models.signals import post_delete, post_save
from entity.models import Entity, EntityRelationship, delete_entity_signal_handler, save_entity_signal_handler
from entity.sync import sync_entities

from test_project.models import Account, Team, EntityPointer, DummyModel, MultiInheritEntity
from .utils import EntityTestCase

class TestSyncAllEntities(EntityTestCase):
    """
    Tests that all entities can be synced at once and tests the management command to
    sync all entities.
    """
    def setUp(self):
        super(TestSyncAllEntities, self).setUp()
        # Disconnect signal handlers to test syncing all entities
        post_delete.disconnect(delete_entity_signal_handler)
        post_save.disconnect(save_entity_signal_handler)

    def test_sync_entities_management_command(self):
        """
        Tests that the management command for syncing entities works properly.
        """
        # Create five test accounts
        for i in range(5):
            Account.objects.create()

        # Test that the management command syncs all five entities
        self.assertEquals(Entity.objects.all().count(), 0)
        call_command('sync_entities')
        self.assertEquals(Entity.objects.all().count(), 5)

    def test_sync_dummy_data(self):
        """
        Tests that dummy data (i.e data that does not inherit EntityModelMixin) doesn't
        get synced.
        """
        # Create dummy data
        DummyModel.objects.create()
        # Sync all entities and verify that none were created
        sync_entities()
        self.assertEquals(Entity.objects.all().count(), 0)

    def test_sync_multi_inherited_data(self):
        """
        Test when models are synced that don't directly inherit EntityModelMixin.
        """
        # Create an entity that does not directly inherit EntityModelMixin
        MultiInheritEntity.objects.create()
        # Sync all entities and verify that one was created
        sync_entities()
        self.assertEquals(Entity.objects.all().count(), 1)

    def test_sync_all_account_no_teams(self):
        """
        Tests syncing all accounts with no super entities.
        """
        # Create five test accounts
        accounts = [Account.objects.create() for i in range(5)]

        # Sync all of the entities and verify that five Entity models were created for the Account model
        self.assertEquals(Entity.objects.all().count(), 0)
        sync_entities()
        self.assertEquals(Entity.objects.all().count(), 5)

        # Delete an account. When all entities are synced again,
        # there should only be four accounts
        accounts[0].delete()
        self.assertEquals(Entity.objects.all().count(), 5)
        sync_entities()
        self.assertEquals(Entity.objects.all().count(), 4)

    def test_sync_all_accounts_teams(self):
        """
        Tests syncing of all accounts when they have syper entities.
        """
        # Create five test accounts
        accounts = [Account.objects.create() for i in range(5)]
        # Create two teams to assign to some of the accounts
        teams = [Team.objects.create() for i in range(2)]
        accounts[0].team = teams[0]
        accounts[0].save()
        accounts[1].team = teams[0]
        accounts[1].save()
        accounts[2].team = teams[1]
        accounts[2].save()
        accounts[3].team = teams[1]
        accounts[3].save()

        # Sync all the entities. There should be 7 (5 accounts 2 teams)
        sync_entities()
        self.assertEquals(Entity.objects.filter(entity_type=ContentType.objects.get_for_model(Account)).count(), 5)
        self.assertEquals(Entity.objects.filter(entity_type=ContentType.objects.get_for_model(Team)).count(), 2)
        self.assertEquals(Entity.objects.all().count(), 7)

        # There should be four entity relationships since four accounts have teams
        self.assertEquals(EntityRelationship.objects.all().count(), 4)

class TestEntitySignalSync(EntityTestCase):
    """
    Tests that entities (from the test models) are properly synced upon post_save and
    post_delete calls.
    """
    def test_post_save_dummy_data(self):
        """
        Tests that dummy data that does not inherit from EntityModelMixin is not synced
        when saved.
        """
        DummyModel.objects.create()
        # Verify that no entities were created
        self.assertEquals(Entity.objects.all().count(), 0)

    def test_post_save_multi_inherit_model(self):
        """
        Tests that a model that does not directly inherit EntityModelMixin is still synced.
        """
        MultiInheritEntity.objects.create()
        # Verify that one entity was synced
        self.assertEquals(Entity.objects.all().count(), 1)

    def test_post_delete_no_entity(self):
        """
        Tests a post_delete on an account that has no current mirrored entity.
        """
        # Create an account
        account = Account.objects.create()
        # Clear out the Entity table since post_save will create an entry for it
        Entity.objects.all().delete()

        # Delete the created model. No errors should occur and nothing should
        # be in the entity table
        account.delete()
        self.assertEquals(Entity.objects.all().count(), 0)

    def test_post_delete_account(self):
        """
        Tests a post_delete on an account that has a current mirrored entity.
        """
        # Create accounts for the test
        main_account = Account.objects.create()
        other_account = Account.objects.create()
        # Clear out the Entity table since post_save will create an entry for it
        Entity.objects.all().delete()

        # Create entity entries for the account object and for another account
        self.create_entity(main_account)
        self.create_entity(other_account)

        # Delete the created model. No errors should occur and the other account
        # should still be an entity in the Entity table.
        main_account.delete()
        self.assertEquals(Entity.objects.all().count(), 1)
        self.assertEquals(Entity.objects.filter(entity_id=other_account.id).count(), 1)

    def test_post_delete_account_under_team(self):
        """
        Tests the deletion of an account that had a relationship with a team.
        """
        # Create a team
        team = Team.objects.create(name='Team')
        # Create an account under that team
        account = Account.objects.create(email='test@test.com', team=team)

        # There should be two entities and a relationship between them.
        self.assertEquals(Entity.objects.all().count(), 2)
        self.assertEquals(EntityRelationship.objects.all().count(), 1)

        # Delete the account. The team entity should still exist
        account.delete()
        self.assertEquals(Entity.objects.all().count(), 1)
        self.assertEquals(EntityRelationship.objects.all().count(), 0)
        Entity.objects.get(entity_type=ContentType.objects.get_for_model(team), entity_id=team.id)

    def test_post_create_account_no_relationships_active(self):
        """
        Tests that an Entity is created when the appropriate EntityModelMixin model is
        created. Tests the case where the entity has no relationships.
        """
        # Verify that there are no entities
        self.assertEquals(Entity.objects.all().count(), 0)

        # Create an account. An entity with no relationships should be created
        account = Account.objects.create(email='test@test.com')
        entity = Entity.objects.get(entity_type=ContentType.objects.get_for_model(account), entity_id=account.id)
        # Check that the metadata and is_active fields were set properly
        self.assertEquals(entity.entity_meta, {
            'email': 'test@test.com',
            'is_captain': False,
            'team': None,
        })
        self.assertEquals(entity.is_active, True)

        self.assertEquals(entity.sub_relationships.all().count(), 0)
        self.assertEquals(entity.super_relationships.all().count(), 0)

    def test_post_create_account_relationships(self):
        """
        Creates an account that has super relationships. Verifies that the entity table is updated
        properly.
        """
        # Verify that there are no entities
        self.assertEquals(Entity.objects.all().count(), 0)

        # Create a team
        team = Team.objects.create(name='Team')
        # Create an account under that team
        account = Account.objects.create(email='test@test.com', team=team)

        # There should be two entities. Test their existence and values
        self.assertEquals(Entity.objects.all().count(), 2)
        account_entity = Entity.objects.get(
            entity_type=ContentType.objects.get_for_model(account), entity_id=account.id)
        self.assertEquals(account_entity.entity_meta, {
            'email': 'test@test.com',
            'is_captain': False,
            'team': 'Team',
        })
        team_entity = Entity.objects.get(
            entity_type=ContentType.objects.get_for_model(team), entity_id=team.id)
        self.assertEquals(team_entity.entity_meta, None)

        # Check that the appropriate entity relationship was created
        self.assertEquals(EntityRelationship.objects.all().count(), 1)
        relationship = EntityRelationship.objects.first()
        self.assertEquals(relationship.sub_entity, account_entity)
        self.assertEquals(relationship.super_entity, team_entity)
        self.assertEquals(relationship.is_active, True)

    def test_post_updated_entity_no_cascade(self):
        """
        Verify that updating a mirrored entity does not cause the entity to be deleted (which
        results in a cascading delete for all pointers.
        """
        # Create a test account
        account = Account.objects.create(email='test@test.com')
        entity = Entity.objects.get(entity_type=ContentType.objects.get_for_model(account), entity_id=account.id)
        self.assertEquals(entity.entity_meta, {
            'email': 'test@test.com',
            'is_captain': False,
            'team': None,
        })
        old_entity_id = entity.id

        # Create an object that points to the entity. This object is created to verify that it isn't cascade
        # deleted when the entity is updated
        test_pointer = EntityPointer.objects.create(entity=entity)

        # Now update the account
        account.email = 'newemail@test.com'
        account.save()
        # Verify that the mirrored entity has the same ID
        entity = Entity.objects.get(entity_type=ContentType.objects.get_for_model(account), entity_id=account.id)
        self.assertEquals(entity.entity_meta, {
            'email': 'newemail@test.com',
            'is_captain': False,
            'team': None,
        })
        self.assertEquals(old_entity_id, entity.id)

        # Verify that the pointer still exists and wasn't cascade deleted
        test_pointer = EntityPointer.objects.get(id=test_pointer.id)
        self.assertEquals(test_pointer.entity, entity)

    def test_post_update_account_meta(self):
        """
        Verifies that an account's metadata is updated properly in the mirrored tables.
        """
        # Create an account and check it's mirrored metadata
        account = Account.objects.create(email='test@test.com')
        entity = Entity.objects.get(entity_type=ContentType.objects.get_for_model(account), entity_id=account.id)
        self.assertEquals(entity.entity_meta, {
            'email': 'test@test.com',
            'is_captain': False,
            'team': None,
        })

        # Update the account's metadata and check that it is mirrored
        account.email = 'newemail@test.com'
        account.save()
        entity = Entity.objects.get(entity_type=ContentType.objects.get_for_model(account), entity_id=account.id)
        self.assertEquals(entity.entity_meta, {
            'email': 'newemail@test.com',
            'is_captain': False,
            'team': None,
        })

    def test_post_update_account_relationship_activity(self):
        """
        Creates an account that has super relationships. Verifies that the entity table is updated
        properly when changing the activity of a relationship.
        """
        # Verify that there are no entities
        self.assertEquals(Entity.objects.all().count(), 0)

        # Create a team
        team = Team.objects.create(name='Team')
        # Create an account under that team
        account = Account.objects.create(email='test@test.com', team=team)

        # There should be two entities. Test their existence and values
        self.assertEquals(Entity.objects.all().count(), 2)
        account_entity = Entity.objects.get(
            entity_type=ContentType.objects.get_for_model(account), entity_id=account.id)
        self.assertEquals(account_entity.entity_meta, {
            'email': 'test@test.com',
            'is_captain': False,
            'team': 'Team',
        })
        team_entity = Entity.objects.get(
            entity_type=ContentType.objects.get_for_model(team), entity_id=team.id)
        self.assertEquals(team_entity.entity_meta, None)

        # Check that the appropriate entity relationship was created
        self.assertEquals(EntityRelationship.objects.all().count(), 1)
        relationship = EntityRelationship.objects.first()
        self.assertEquals(relationship.sub_entity, account_entity)
        self.assertEquals(relationship.super_entity, team_entity)
        self.assertEquals(relationship.is_active, True)

        # Update the account to be a team captain. According to our test project, this
        # means it no longer has an active relationship to a team
        account.is_captain = True
        account.save()

        # Verify that it no longer has an active relationship
        self.assertEquals(EntityRelationship.objects.all().count(), 1)
        relationship = EntityRelationship.objects.first()
        self.assertEquals(relationship.sub_entity, account_entity)
        self.assertEquals(relationship.super_entity, team_entity)
        self.assertEquals(relationship.is_active, False)
<commit_msg>added tests for filtering based on sub/super entities<commit_after>"""
Provides tests for the syncing functionalities in django entity.
"""
from django.contrib.contenttypes.models import ContentType
from django.core.management import call_command
from django.db.models.signals import post_delete, post_save
from entity.models import Entity, EntityRelationship, delete_entity_signal_handler, save_entity_signal_handler
from entity.sync import sync_entities

from test_project.models import Account, Team, EntityPointer, DummyModel, MultiInheritEntity
from .utils import EntityTestCase

class TestSyncAllEntities(EntityTestCase):
    """
    Tests that all entities can be synced at once and tests the management command to
    sync all entities.
    """
    def setUp(self):
        super(TestSyncAllEntities, self).setUp()
        # Disconnect signal handlers to test syncing all entities
        post_delete.disconnect(delete_entity_signal_handler)
        post_save.disconnect(save_entity_signal_handler)

    def test_sync_entities_management_command(self):
        """
        Tests that the management command for syncing entities works properly.
        """
        # Create five test accounts
        for i in range(5):
            Account.objects.create()

        # Test that the management command syncs all five entities
        self.assertEquals(Entity.objects.all().count(), 0)
        call_command('sync_entities')
        self.assertEquals(Entity.objects.all().count(), 5)

    def test_sync_dummy_data(self):
        """
        Tests that dummy data (i.e data that does not inherit EntityModelMixin) doesn't
        get synced.
        """
        # Create dummy data
        DummyModel.objects.create()
        # Sync all entities and verify that none were created
        sync_entities()
        self.assertEquals(Entity.objects.all().count(), 0)

    def test_sync_multi_inherited_data(self):
        """
        Test when models are synced that don't directly inherit EntityModelMixin.
        """
        # Create an entity that does not directly inherit EntityModelMixin
        MultiInheritEntity.objects.create()
        # Sync all entities and verify that one was created
        sync_entities()
        self.assertEquals(Entity.objects.all().count(), 1)

    def test_sync_all_account_no_teams(self):
        """
        Tests syncing all accounts with no super entities.
        """
        # Create five test accounts
        accounts = [Account.objects.create() for i in range(5)]

        # Sync all of the entities and verify that five Entity models were created for the Account model
        self.assertEquals(Entity.objects.all().count(), 0)
        sync_entities()
        self.assertEquals(Entity.objects.all().count(), 5)

        # Delete an account. When all entities are synced again,
        # there should only be four accounts
        accounts[0].delete()
        self.assertEquals(Entity.objects.all().count(), 5)
        sync_entities()
        self.assertEquals(Entity.objects.all().count(), 4)

    def test_sync_all_accounts_teams(self):
        """
        Tests syncing of all accounts when they have syper entities.
        """
        # Create five test accounts
        accounts = [Account.objects.create() for i in range(5)]
        # Create two teams to assign to some of the accounts
        teams = [Team.objects.create() for i in range(2)]
        accounts[0].team = teams[0]
        accounts[0].save()
        accounts[1].team = teams[0]
        accounts[1].save()
        accounts[2].team = teams[1]
        accounts[2].save()
        accounts[3].team = teams[1]
        accounts[3].save()

        # Sync all the entities. There should be 7 (5 accounts 2 teams)
        sync_entities()
        self.assertEquals(Entity.objects.filter(entity_type=ContentType.objects.get_for_model(Account)).count(), 5)
        self.assertEquals(Entity.objects.filter(entity_type=ContentType.objects.get_for_model(Team)).count(), 2)
        self.assertEquals(Entity.objects.all().count(), 7)

        # There should be four entity relationships since four accounts have teams
        self.assertEquals(EntityRelationship.objects.all().count(), 4)

class TestEntitySignalSync(EntityTestCase):
    """
    Tests that entities (from the test models) are properly synced upon post_save and
    post_delete calls.
    """
    def test_post_save_dummy_data(self):
        """
        Tests that dummy data that does not inherit from EntityModelMixin is not synced
        when saved.
        """
        DummyModel.objects.create()
        # Verify that no entities were created
        self.assertEquals(Entity.objects.all().count(), 0)

    def test_post_save_multi_inherit_model(self):
        """
        Tests that a model that does not directly inherit EntityModelMixin is still synced.
        """
        MultiInheritEntity.objects.create()
        # Verify that one entity was synced
        self.assertEquals(Entity.objects.all().count(), 1)

    def test_post_delete_no_entity(self):
        """
        Tests a post_delete on an account that has no current mirrored entity.
        """
        # Create an account
        account = Account.objects.create()
        # Clear out the Entity table since post_save will create an entry for it
        Entity.objects.all().delete()

        # Delete the created model. No errors should occur and nothing should
        # be in the entity table
        account.delete()
        self.assertEquals(Entity.objects.all().count(), 0)

    def test_post_delete_account(self):
        """
        Tests a post_delete on an account that has a current mirrored entity.
        """
        # Create accounts for the test
        main_account = Account.objects.create()
        other_account = Account.objects.create()
        # Clear out the Entity table since post_save will create an entry for it
        Entity.objects.all().delete()

        # Create entity entries for the account object and for another account
        self.create_entity(main_account)
        self.create_entity(other_account)

        # Delete the created model. No errors should occur and the other account
        # should still be an entity in the Entity table.
        main_account.delete()
        self.assertEquals(Entity.objects.all().count(), 1)
        self.assertEquals(Entity.objects.filter(entity_id=other_account.id).count(), 1)

    def test_post_delete_account_under_team(self):
        """
        Tests the deletion of an account that had a relationship with a team.
        """
        # Create a team
        team = Team.objects.create(name='Team')
        # Create an account under that team
        account = Account.objects.create(email='test@test.com', team=team)

        # There should be two entities and a relationship between them.
        self.assertEquals(Entity.objects.all().count(), 2)
        self.assertEquals(EntityRelationship.objects.all().count(), 1)

        # Delete the account. The team entity should still exist
        account.delete()
        self.assertEquals(Entity.objects.all().count(), 1)
        self.assertEquals(EntityRelationship.objects.all().count(), 0)
        Entity.objects.get(entity_type=ContentType.objects.get_for_model(team), entity_id=team.id)

    def test_post_create_account_no_relationships_active(self):
        """
        Tests that an Entity is created when the appropriate EntityModelMixin model is
        created. Tests the case where the entity has no relationships.
        """
        # Verify that there are no entities
        self.assertEquals(Entity.objects.all().count(), 0)

        # Create an account. An entity with no relationships should be created
        account = Account.objects.create(email='test@test.com')
        entity = Entity.objects.get(entity_type=ContentType.objects.get_for_model(account), entity_id=account.id)
        # Check that the metadata and is_active fields were set properly
        self.assertEquals(entity.entity_meta, {
            'email': 'test@test.com',
            'is_captain': False,
            'team': None,
        })
        self.assertEquals(entity.is_active, True)

        self.assertEquals(entity.sub_relationships.all().count(), 0)
        self.assertEquals(entity.super_relationships.all().count(), 0)

    def test_post_create_account_relationships(self):
        """
        Creates an account that has super relationships. Verifies that the entity table is updated
        properly.
        """
        # Verify that there are no entities
        self.assertEquals(Entity.objects.all().count(), 0)

        # Create a team
        team = Team.objects.create(name='Team')
        # Create an account under that team
        account = Account.objects.create(email='test@test.com', team=team)

        # There should be two entities. Test their existence and values
        self.assertEquals(Entity.objects.all().count(), 2)
        account_entity = Entity.objects.get(
            entity_type=ContentType.objects.get_for_model(account), entity_id=account.id)
        self.assertEquals(account_entity.entity_meta, {
            'email': 'test@test.com',
            'is_captain': False,
            'team': 'Team',
        })
        team_entity = Entity.objects.get(
            entity_type=ContentType.objects.get_for_model(team), entity_id=team.id)
        self.assertEquals(team_entity.entity_meta, None)

        # Check that the appropriate entity relationship was created
        self.assertEquals(EntityRelationship.objects.all().count(), 1)
        relationship = EntityRelationship.objects.first()
        self.assertEquals(relationship.sub_entity, account_entity)
        self.assertEquals(relationship.super_entity, team_entity)
        self.assertEquals(relationship.is_active, True)

    def test_post_updated_entity_no_cascade(self):
        """
        Verify that updating a mirrored entity does not cause the entity to be deleted (which
        results in a cascading delete for all pointers.
        """
        # Create a test account
        account = Account.objects.create(email='test@test.com')
        entity = Entity.objects.get(entity_type=ContentType.objects.get_for_model(account), entity_id=account.id)
        self.assertEquals(entity.entity_meta, {
            'email': 'test@test.com',
            'is_captain': False,
            'team': None,
        })
        old_entity_id = entity.id

        # Create an object that points to the entity. This object is created to verify that it isn't cascade
        # deleted when the entity is updated
        test_pointer = EntityPointer.objects.create(entity=entity)

        # Now update the account
        account.email = 'newemail@test.com'
        account.save()
        # Verify that the mirrored entity has the same ID
        entity = Entity.objects.get(entity_type=ContentType.objects.get_for_model(account), entity_id=account.id)
        self.assertEquals(entity.entity_meta, {
            'email': 'newemail@test.com',
            'is_captain': False,
            'team': None,
        })
        self.assertEquals(old_entity_id, entity.id)

        # Verify that the pointer still exists and wasn't cascade deleted
        test_pointer = EntityPointer.objects.get(id=test_pointer.id)
        self.assertEquals(test_pointer.entity, entity)

    def test_post_update_account_meta(self):
        """
        Verifies that an account's metadata is updated properly in the mirrored tables.
        """
        # Create an account and check it's mirrored metadata
        account = Account.objects.create(email='test@test.com')
        entity = Entity.objects.get(entity_type=ContentType.objects.get_for_model(account), entity_id=account.id)
        self.assertEquals(entity.entity_meta, {
            'email': 'test@test.com',
            'is_captain': False,
            'team': None,
        })

        # Update the account's metadata and check that it is mirrored
        account.email = 'newemail@test.com'
        account.save()
        entity = Entity.objects.get(entity_type=ContentType.objects.get_for_model(account), entity_id=account.id)
        self.assertEquals(entity.entity_meta, {
            'email': 'newemail@test.com',
            'is_captain': False,
            'team': None,
        })

    def test_post_update_account_relationship_activity(self):
        """
        Creates an account that has super relationships. Verifies that the entity table is updated
        properly when changing the activity of a relationship.
        """
        # Verify that there are no entities
        self.assertEquals(Entity.objects.all().count(), 0)

        # Create a team
        team = Team.objects.create(name='Team')
        # Create an account under that team
        account = Account.objects.create(email='test@test.com', team=team)

        # There should be two entities. Test their existence and values
        self.assertEquals(Entity.objects.all().count(), 2)
        account_entity = Entity.objects.get(
            entity_type=ContentType.objects.get_for_model(account), entity_id=account.id)
        self.assertEquals(account_entity.entity_meta, {
            'email': 'test@test.com',
            'is_captain': False,
            'team': 'Team',
        })
        team_entity = Entity.objects.get(
            entity_type=ContentType.objects.get_for_model(team), entity_id=team.id)
        self.assertEquals(team_entity.entity_meta, None)

        # Check that the appropriate entity relationship was created
        self.assertEquals(EntityRelationship.objects.all().count(), 1)
        relationship = EntityRelationship.objects.first()
        self.assertEquals(relationship.sub_entity, account_entity)
        self.assertEquals(relationship.super_entity, team_entity)
        self.assertEquals(relationship.is_active, True)

        # Update the account to be a team captain. According to our test project, this
        # means it no longer has an active relationship to a team
        account.is_captain = True
        account.save()

        # Verify that it no longer has an active relationship
        self.assertEquals(EntityRelationship.objects.all().count(), 1)
        relationship = EntityRelationship.objects.first()
        self.assertEquals(relationship.sub_entity, account_entity)
        self.assertEquals(relationship.super_entity, team_entity)
        self.assertEquals(relationship.is_active, False)

    def test_post_update_filter_super_entities(self):
        """
        Tests that accounts can filter their super entities based on a given entity type.
        """
        # Create an account that belongs to a team
        team = Team.objects.create(name='Team')
        account = Account.objects.create(email='test@test.com', team=team)

        # Get the entity related to the account
        account_entity = Entity.objects.get(
            entity_type=ContentType.objects.get_for_model(account), entity_id=account.id)
        team_entity = Entity.objects.get(
            entity_type=ContentType.objects.get_for_model(team), entity_id=team.id)
        # Check the filter of the super entity type
        self.assertEquals(
            account_entity.get_super_entities(entity_type=ContentType.objects.get_for_model(team)),
            [team_entity])
        # Check that the filter returns nothing for a different entity type
        self.assertEquals(
            account_entity.get_super_entities(entity_type=ContentType.objects.get_for_model(account)), [])

    def test_post_update_filter_sub_entities(self):
        """
        Tests that teams can filter their sub entities based on a given entity type.
        """
        # Create an account that belongs to a team
        team = Team.objects.create(name='Team')
        account = Account.objects.create(email='test@test.com', team=team)

        # Get the entity related to the account
        account_entity = Entity.objects.get(
            entity_type=ContentType.objects.get_for_model(account), entity_id=account.id)
        team_entity = Entity.objects.get(
            entity_type=ContentType.objects.get_for_model(team), entity_id=team.id)
        # Check the filter of the sub entity type
        self.assertEquals(
            team_entity.get_sub_entities(entity_type=ContentType.objects.get_for_model(account)),
            [account_entity])
        # Check that the filter returns nothing for a different entity type
        self.assertEquals(
            team_entity.get_sub_entities(entity_type=ContentType.objects.get_for_model(team)), [])
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
from posts.forms import PostCreateForm
from posts.models import Post, PUBLISHED
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from django.utils.decorators import method_decorator
from django.views.generic import View
from django.core.urlresolvers import reverse
from django.db.models import Q

class PostsDetailView(View):
    def get(self, req, username, pk):
        posts = Post.objects.filter(pk=pk)

        context = {
            'post_list': posts
        }
        return render(req, 'blogs/post_detail.html', context)

class PostsUserView(View):
    def get(self, req, username):
        posts = Post.objects.filter(owner__username=username)
        # posts = Post.objects.all()

        context = {
            'post_list': posts
        }
        return render(req, 'blogs/home.html', context)

class PostCreateView(View):
    @method_decorator(login_required())
    def get(self, req):
        """
        Muestra un form para crear un post y lo crea si la petición es POST
        :param req: HttpRequest
        :return: HttpResponse
        """
        error_messages = []
        form = PostCreateForm()

        context = {
            'form': form
        }
        return render(req, 'blogs/new_post.html', context)

    @method_decorator(login_required())
    def post(self, req):
        """
        Muestra un form para crear una foto y la crea si la peticion es POST
        :param req: HttpRequest
        :return: HttpResponse
        """
        error_messages = []
        success_message = ''

        # Creamos owner y se lo pasamos al form con un objeto pre-establecido
        post_with_owner = Post()
        post_with_owner.owner = req.user

        form = PostCreateForm(req.POST, instance=post_with_owner)
        if form.is_valid():
            new_post = form.save()
            form = PostCreateForm()
            success_message = u'Post guardado con éxito! '
            success_message += u''.format(reverse('post_detail', args=[req.user.username, new_post.pk]))
            success_message += u'(ver post)'
        else:
            error_messages.append(u'Formulario incompleto.')

        context = {
            'form': form,
            'success_message': success_message
        }
        return render(req, 'blogs/new_post.html', context)

# query sets
class PostQuerySet(object):
    def get_post_queryset(self, req):
        if not req.user.is_authenticated():
            posts = Post.objects.filter(state=PUBLISHED).order_by('-created_at')
        elif req.user.is_superuser:  # es super admin
            posts = Post.objects.all()
        else:
            posts = Post.objects.filter(Q(owner=req.user) | Q(state=PUBLISHED))

        return posts
<commit_msg>Fix bug POST model<commit_after># -*- coding: utf-8 -*-
from posts.forms import PostCreateForm
from posts.models import Post, PUBLISHED
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from django.utils.decorators import method_decorator
from django.views.generic import View
from django.core.urlresolvers import reverse
from django.db.models import Q

class PostsDetailView(View):
    def get(self, req, username, pk):
        posts = Post.objects.filter(pk=pk)

        context = {
            'post_list': posts
        }
        return render(req, 'blogs/post_detail.html', context)

class PostsUserView(View):
    def get(self, req, username):
        posts = Post.objects.filter(owner__username=username)
        # posts = Post.objects.all()

        context = {
            'post_list': posts
        }
        return render(req, 'blogs/home.html', context)

class PostCreateView(View):
    @method_decorator(login_required())
    def get(self, req):
        """
        Muestra un form para crear un post y lo crea si la petición es POST
        :param req: HttpRequest
        :return: HttpResponse
        """
        error_messages = []
        form = PostCreateForm()

        context = {
            'form': form
        }
        return render(req, 'blogs/new_post.html', context)

    @method_decorator(login_required())
    def post(self, req):
        """
        Muestra un form para crear una foto y la crea si la peticion es POST
        :param req: HttpRequest
        :return: HttpResponse
        """
        error_messages = []
        success_message = ''

        # Creamos owner y se lo pasamos al form con un objeto pre-establecido
        post_with_owner = Post()
        post_with_owner.owner = req.user

        form = PostCreateForm(req.POST, instance=post_with_owner)
        if form.is_valid():
            new_post = form.save()
            form = PostCreateForm()
            success_message = u'Post guardado con éxito! '
            success_message += u''.format(reverse('post_detail', args=[req.user.username, new_post.pk]))
            success_message += u'(ver post)'
        else:
            error_messages.append(u'Formulario incompleto.')

        context = {
            'form': form,
            'success_message': success_message
        }
        return render(req, 'blogs/new_post.html', context)

# query sets
class PostQuerySet(object):
    def get_post_queryset(self, req):
        if not req.user.is_authenticated():
            posts = Post.objects.filter(status=PUBLISHED).order_by('-created_at')
        elif req.user.is_superuser:  # es super admin
            posts = Post.objects.all()
        else:
            posts = Post.objects.filter(Q(owner=req.user) | Q(state=PUBLISHED))

        return posts
<|endoftext|>


<commit_before>"""
Django settings for inflation project.

Generated by 'django-admin startproject' using Django 1.8.6.

For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '0-9+ecl+%vt607c*=0y)@f&^1slfytjt6bu%!5+p5k06_lg_br'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'reports',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
)

ROOT_URLCONF = 'inflation.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'inflation.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/

STATIC_URL = '/static/'
<commit_msg>Remove secret file<commit_after><|endoftext|>


<commit_before>#!/usr/bin/env python3
from __future__ import unicode_literals

import cgi
import io
import os
import socket
import unittest
import sys

try:
    from http.server import BaseHTTPRequestHandler, HTTPServer
except ImportError:
    from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer

try:
    from urllib.parse import urlparse, parse_qs
except ImportError:
    from urlparse import urlparse, parse_qs

_WVS_ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

sys.path.append(_WVS_ROOT_DIR)
import webvulnscan

sitemap = {}

class WebRunnerHandler(BaseHTTPRequestHandler):
    def _write(self, s):
        return self.wfile.write(s.encode('utf-8'))

    def _default_page(self):
        self.send_response(200)
        self.send_header("Content-Type", "text/html")
        self.end_headers()
        w = self._write
        w("""<!DOCTYPE html>

                <meta charset="utf-8" />
                <title>webvulnscan tests</title>

webvulnscan tests

        """)

        for name in sorted(sitemap):
            w('
')
            w(cgi.escape(name))
            w('
')

        w("""

            """)

    def _serve_request(self):
        parsed_path = urlparse(self.path)
        current_path = parsed_path.path.split('/')[1]

        if parsed_path.path == "/":
            self._default_page()
        elif current_path in sitemap:
            extended_path = "".join(parsed_path.path.split('/')[2:])

            site = sitemap[current_path]
            client = site.client

            if parsed_path.query == "":
                url = "http://test.webvulnscan/" + extended_path
            else:
                url = "http://test.webvulnscan/" + extended_path +\
                    "?" + parsed_path.query

            request = webvulnscan.request.Request(url)

            if 'content-length' in self.headers:
                content_len = int(self.headers['content-length'])
                body = self.rfile.read(content_len)
                request.parameters = parse_qs(body)

                for value in request.parameters:
                    new_value = request.parameters[value][0].decode('utf-8')
                    request.parameters[value] = new_value

            _, status_code, response_data, headers = client._download(request)
            self.send_response(status_code)
            self.send_header('Content-Type', 'text/html')
            for header in headers:
                self.send_header(header[0], header[1])
            self.end_headers()

            self.wfile.write(response_data)
        else:
            self.send_error(404, "File not Found!")

    def handle_one_request(self):
        try:
            self.raw_requestline = self.rfile.readline(65537)
            if len(self.raw_requestline) > 65536:
                self.requestline = ''
                self.request_version = ''
                self.command = ''
                self.send_error(414)
                return
            if not self.raw_requestline:
                self.close_connection = 1
                return
            if not self.parse_request():
                return

            self._serve_request()
            self.wfile.flush()
        except socket.timeout as e:
            self.log_error("Request timed out: %r", e)
            self.close_connection = 1
            return

def discover():
    testloader = unittest.TestLoader()
    suites = testloader.discover(os.path.join(_WVS_ROOT_DIR, 'test'))
    for suite in suites:
        for klass in suite:
            for test in klass._tests:
                elements = dir(test)
                for subklass in elements:
                    func = getattr(test, subklass)
                    if hasattr(func, "client"):
                        yield func

def main():
    for test in discover():
        sitemap[test.__name__] = test

    server_class = HTTPServer
    httpd = server_class(("", 8000), WebRunnerHandler)
    httpd.serve_forever()

if __name__ == "__main__":
    main()
<commit_msg>[web_runner] Simplify hook for capturing all HTTP methods<commit_after>#!/usr/bin/env python3
from __future__ import unicode_literals

import cgi
import io
import os
import socket
import unittest
import sys

try:
    from http.server import BaseHTTPRequestHandler, HTTPServer
except ImportError:
    from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer

try:
    from urllib.parse import urlparse, parse_qs
except ImportError:
    from urlparse import urlparse, parse_qs

_WVS_ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

sys.path.append(_WVS_ROOT_DIR)
import webvulnscan

sitemap = {}

class WebRunnerHandler(BaseHTTPRequestHandler):
    def _write(self, s):
        return self.wfile.write(s.encode('utf-8'))

    def _default_page(self):
        self.send_response(200)
        self.send_header("Content-Type", "text/html")
        self.end_headers()
        w = self._write
        w("""<!DOCTYPE html>

                <meta charset="utf-8" />
                <title>webvulnscan tests</title>

webvulnscan tests

        """)

        for name in sorted(sitemap):
            w('
')
            w(cgi.escape(name))
            w('
')

        w("""

            """)

    def _serve_request(self):
        parsed_path = urlparse(self.path)
        current_path = parsed_path.path.split('/')[1]

        if parsed_path.path == "/":
            self._default_page()
        elif current_path in sitemap:
            extended_path = "".join(parsed_path.path.split('/')[2:])

            site = sitemap[current_path]
            client = site.client

            if parsed_path.query == "":
                url = "http://test.webvulnscan/" + extended_path
            else:
                url = "http://test.webvulnscan/" + extended_path +\
                    "?" + parsed_path.query

            request = webvulnscan.request.Request(url)

            if 'content-length' in self.headers:
                content_len = int(self.headers['content-length'])
                body = self.rfile.read(content_len)
                request.parameters = parse_qs(body)

                for value in request.parameters:
                    new_value = request.parameters[value][0].decode('utf-8')
                    request.parameters[value] = new_value

            _, status_code, response_data, headers = client._download(request)
            self.send_response(status_code)
            self.send_header('Content-Type', 'text/html')
            for header in headers:
                self.send_header(header[0], header[1])
            self.end_headers()

            self.wfile.write(response_data)
        else:
            self.send_error(404, "File not Found!")

    def __getattr__(self, name):
        if name.startswith('do_'):
            return self._serve_request
        raise AttributeError()

def discover():
    testloader = unittest.TestLoader()
    suites = testloader.discover(os.path.join(_WVS_ROOT_DIR, 'test'))
    for suite in suites:
        for klass in suite:
            for test in klass._tests:
                elements = dir(test)
                for subklass in elements:
                    func = getattr(test, subklass)
                    if hasattr(func, "client"):
                        yield func

def main():
    for test in discover():
        sitemap[test.__name__] = test

    server_class = HTTPServer
    httpd = server_class(("", 8000), WebRunnerHandler)
    httpd.serve_forever()

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


<commit_before>"""
homeassistant.components.demo
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Sets up a demo environment that mimics interaction with devices
"""
import random

import homeassistant as ha
import homeassistant.loader as loader
from homeassistant.helpers import extract_entity_ids
from homeassistant.const import (
    SERVICE_TURN_ON, SERVICE_TURN_OFF, STATE_ON, STATE_OFF,
    ATTR_ENTITY_PICTURE, ATTR_ENTITY_ID, CONF_LATITUDE, CONF_LONGITUDE)
from homeassistant.components.light import (
    ATTR_XY_COLOR, ATTR_BRIGHTNESS, GROUP_NAME_ALL_LIGHTS)
from homeassistant.util import split_entity_id

DOMAIN = "demo"

DEPENDENCIES = []

def setup(hass, config):
    """ Setup a demo environment. """
    group = loader.get_component('group')

    config.setdefault(ha.DOMAIN, {})
    config.setdefault(DOMAIN, {})

    if config[DOMAIN].get('hide_demo_state') != '1':
        hass.states.set('a.Demo_Mode', 'Enabled')

    light_colors = [
        [0.861, 0.3259],
        [0.6389, 0.3028],
        [0.1684, 0.0416]
    ]

    def mock_turn_on(service):
        """ Will fake the component has been turned on. """
        if service.data and ATTR_ENTITY_ID in service.data:
            entity_ids = extract_entity_ids(hass, service)
        else:
            entity_ids = hass.states.entity_ids(service.domain)

        for entity_id in entity_ids:
            domain, _ = split_entity_id(entity_id)

            if domain == "light":
                data = {ATTR_BRIGHTNESS: 200,
                        ATTR_XY_COLOR: random.choice(light_colors)}
            else:
                data = None

            hass.states.set(entity_id, STATE_ON, data)

    def mock_turn_off(service):
        """ Will fake the component has been turned off. """
        if service.data and ATTR_ENTITY_ID in service.data:
            entity_ids = extract_entity_ids(hass, service)
        else:
            entity_ids = hass.states.entity_ids(service.domain)

        for entity_id in entity_ids:
            hass.states.set(entity_id, STATE_OFF)

    # Setup sun
    if CONF_LATITUDE not in config[ha.DOMAIN]:
        config[ha.DOMAIN][CONF_LATITUDE] = '32.87336'

    if CONF_LONGITUDE not in config[ha.DOMAIN]:
        config[ha.DOMAIN][CONF_LONGITUDE] = '-117.22743'

    loader.get_component('sun').setup(hass, config)

    # Setup fake lights
    lights = ['light.Bowl', 'light.Ceiling', 'light.TV_Back_light',
              'light.Bed_light']

    hass.services.register('light', SERVICE_TURN_ON, mock_turn_on)
    hass.services.register('light', SERVICE_TURN_OFF, mock_turn_off)

    mock_turn_on(ha.ServiceCall('light', SERVICE_TURN_ON,
                                {'entity_id': lights[0:2]}))
    mock_turn_off(ha.ServiceCall('light', SERVICE_TURN_OFF,
                                 {'entity_id': lights[2:]}))

    group.setup_group(hass, GROUP_NAME_ALL_LIGHTS, lights, False)

    # Setup switch
    switches = ['switch.AC', 'switch.Christmas_Lights']

    hass.services.register('switch', SERVICE_TURN_ON, mock_turn_on)
    hass.services.register('switch', SERVICE_TURN_OFF, mock_turn_off)

    mock_turn_on(ha.ServiceCall('switch', SERVICE_TURN_ON,
                                {'entity_id': switches[0:1]}))
    mock_turn_off(ha.ServiceCall('switch', SERVICE_TURN_OFF,
                                 {'entity_id': switches[1:]}))

    # Setup room groups
    group.setup_group(hass, 'living_room', lights[0:3] + switches[0:1])
    group.setup_group(hass, 'bedroom', [lights[3]] + switches[1:])

    # Setup process
    hass.states.set("process.XBMC", STATE_ON)

    # Setup device tracker
    hass.states.set("device_tracker.Paulus", "home",
                    {ATTR_ENTITY_PICTURE:
                     "http://graph.facebook.com/schoutsen/picture"})
    hass.states.set("device_tracker.Anne_Therese", "not_home",
                    {ATTR_ENTITY_PICTURE:
                     "http://graph.facebook.com/anne.t.frederiksen/picture"})

    hass.states.set("group.all_devices", "home",
                    {
                        "auto": True,
                        "entity_id": [
                            "device_tracker.Paulus",
                            "device_tracker.Anne_Therese"
                        ]
                    })

    # Setup chromecast
    hass.states.set("chromecast.Living_Rm", "Netflix",
                    {'friendly_name': 'Living Room',
                     ATTR_ENTITY_PICTURE:
                     'http://graph.facebook.com/KillBillMovie/picture'})

    # Setup tellstick sensors
    hass.states.set("tellstick_sensor.Outside_temperature", "15.6",
                    {
                        'friendly_name': 'Outside temperature',
                        'unit_of_measurement': '°C'
                    })
    hass.states.set("tellstick_sensor.Outside_humidity", "54",
                    {
                        'friendly_name': 'Outside humidity',
                        'unit_of_measurement': '%'
                    })

    return True
<commit_msg>Demo component now supports brightness/color for lights<commit_after>"""
homeassistant.components.demo
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Sets up a demo environment that mimics interaction with devices
"""
import random

import homeassistant as ha
import homeassistant.loader as loader
from homeassistant.helpers import extract_entity_ids
from homeassistant.const import (
    SERVICE_TURN_ON, SERVICE_TURN_OFF, STATE_ON, STATE_OFF,
    ATTR_ENTITY_PICTURE, ATTR_ENTITY_ID, CONF_LATITUDE, CONF_LONGITUDE)
from homeassistant.components.light import (
    ATTR_XY_COLOR, ATTR_RGB_COLOR, ATTR_BRIGHTNESS, GROUP_NAME_ALL_LIGHTS)
from homeassistant.util import split_entity_id, color_RGB_to_xy

DOMAIN = "demo"

DEPENDENCIES = []

def setup(hass, config):
    """ Setup a demo environment. """
    group = loader.get_component('group')

    config.setdefault(ha.DOMAIN, {})
    config.setdefault(DOMAIN, {})

    if config[DOMAIN].get('hide_demo_state') != '1':
        hass.states.set('a.Demo_Mode', 'Enabled')

    light_colors = [
        [0.861, 0.3259],
        [0.6389, 0.3028],
        [0.1684, 0.0416]
    ]

    def mock_turn_on(service):
        """ Will fake the component has been turned on. """
        if service.data and ATTR_ENTITY_ID in service.data:
            entity_ids = extract_entity_ids(hass, service)
        else:
            entity_ids = hass.states.entity_ids(service.domain)

        for entity_id in entity_ids:
            domain, _ = split_entity_id(entity_id)

            if domain == "light":
                rgb_color = service.data.get(ATTR_RGB_COLOR)

                if rgb_color is None:
                    color = random.choice(light_colors)
                else:
                    color = color_RGB_to_xy(
                        rgb_color[0], rgb_color[1], rgb_color[2])

                data = {
                    ATTR_BRIGHTNESS: service.data.get(ATTR_BRIGHTNESS, 200),
                    ATTR_XY_COLOR: color
                }
            else:
                data = None

            hass.states.set(entity_id, STATE_ON, data)

    def mock_turn_off(service):
        """ Will fake the component has been turned off. """
        if service.data and ATTR_ENTITY_ID in service.data:
            entity_ids = extract_entity_ids(hass, service)
        else:
            entity_ids = hass.states.entity_ids(service.domain)

        for entity_id in entity_ids:
            hass.states.set(entity_id, STATE_OFF)

    # Setup sun
    if CONF_LATITUDE not in config[ha.DOMAIN]:
        config[ha.DOMAIN][CONF_LATITUDE] = '32.87336'

    if CONF_LONGITUDE not in config[ha.DOMAIN]:
        config[ha.DOMAIN][CONF_LONGITUDE] = '-117.22743'

    loader.get_component('sun').setup(hass, config)

    # Setup fake lights
    lights = ['light.Bowl', 'light.Ceiling', 'light.TV_Back_light',
              'light.Bed_light']

    hass.services.register('light', SERVICE_TURN_ON, mock_turn_on)
    hass.services.register('light', SERVICE_TURN_OFF, mock_turn_off)

    mock_turn_on(ha.ServiceCall('light', SERVICE_TURN_ON,
                                {'entity_id': lights[0:2]}))
    mock_turn_off(ha.ServiceCall('light', SERVICE_TURN_OFF,
                                 {'entity_id': lights[2:]}))

    group.setup_group(hass, GROUP_NAME_ALL_LIGHTS, lights, False)

    # Setup switch
    switches = ['switch.AC', 'switch.Christmas_Lights']

    hass.services.register('switch', SERVICE_TURN_ON, mock_turn_on)
    hass.services.register('switch', SERVICE_TURN_OFF, mock_turn_off)

    mock_turn_on(ha.ServiceCall('switch', SERVICE_TURN_ON,
                                {'entity_id': switches[0:1]}))
    mock_turn_off(ha.ServiceCall('switch', SERVICE_TURN_OFF,
                                 {'entity_id': switches[1:]}))

    # Setup room groups
    group.setup_group(hass, 'living_room', lights[0:3] + switches[0:1])
    group.setup_group(hass, 'bedroom', [lights[3]] + switches[1:])

    # Setup process
    hass.states.set("process.XBMC", STATE_ON)

    # Setup device tracker
    hass.states.set("device_tracker.Paulus", "home",
                    {ATTR_ENTITY_PICTURE:
                     "http://graph.facebook.com/schoutsen/picture"})
    hass.states.set("device_tracker.Anne_Therese", "not_home",
                    {ATTR_ENTITY_PICTURE:
                     "http://graph.facebook.com/anne.t.frederiksen/picture"})

    hass.states.set("group.all_devices", "home",
                    {
                        "auto": True,
                        "entity_id": [
                            "device_tracker.Paulus",
                            "device_tracker.Anne_Therese"
                        ]
                    })

    # Setup chromecast
    hass.states.set("chromecast.Living_Rm", "Netflix",
                    {'friendly_name': 'Living Room',
                     ATTR_ENTITY_PICTURE:
                     'http://graph.facebook.com/KillBillMovie/picture'})

    # Setup tellstick sensors
    hass.states.set("tellstick_sensor.Outside_temperature", "15.6",
                    {
                        'friendly_name': 'Outside temperature',
                        'unit_of_measurement': '°C'
                    })
    hass.states.set("tellstick_sensor.Outside_humidity", "54",
                    {
                        'friendly_name': 'Outside humidity',
                        'unit_of_measurement': '%'
                    })

    return True
<|endoftext|>