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

from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals

import codecs
import os
import tempfile
from unittest import TestCase

from spdx.parsers.rdf import Parser as RDFParser
from spdx.parsers.rdfbuilders import Builder as RDFBuilder
from spdx.parsers.loggers import StandardLogger
from spdx.parsers.tagvalue import Parser as TVParser
from spdx.parsers.tagvaluebuilders import Builder as TVBuilder
from spdx.parsers.jsonparser import Parser as JSONParser
from spdx.parsers.yamlparser import Parser as YAMLParser
from spdx.parsers.xmlparser import Parser as XMLParser
from spdx.parsers.jsonyamlxmlbuilders import Builder as JSONYAMLXMLBuilder
import spdx.writers.rdf as rdfwriter
import spdx.writers.tagvalue as tvwriter
import spdx.writers.json as jsonwriter
import spdx.writers.yaml as yamlwriter
import spdx.writers.xml as xmlwriter

from tests import utils_test

def get_temp_file(extension=''):
    """
    Return a unique new temporary file location to a non-existing
    temporary file that can safely be created without a risk of name
    collision.
    """

    if extension and not extension.startswith('.'):
            extension = '.' + extension
    file_name = 'temp_file' + extension
    temp_dir = tempfile.mkdtemp()
    return os.path.join(temp_dir, file_name)

class TestConversions(TestCase):
    maxDiff = None

    def parse_rdf_file(self, file_name):
        with open(file_name, mode='rb') as infile:
            rdfparser = RDFParser(RDFBuilder(), StandardLogger())
            doc, error = rdfparser.parse(infile)
        assert not error
        assert doc.validate([]) == []
        return doc

    def parse_tagvalue_file(self, file_name):
        with open(file_name, mode='r') as infile:
            tvparser = TVParser(TVBuilder(), StandardLogger())
            tvparser.build()
<<<<<<< Upstream, based on spdx/master
            doc, error = tvparser.parse(infile.read())
        assert not error
        assert doc.validate([]) == []
        return doc
=======
            return tvparser.parse(infile.read())
>>>>>>> e152d93 Add maxDiff None to all tests and format code

    def parse_json_file(self, file_name):
        with open(file_name, mode='r') as infile:
            jsonparser = JSONParser(JSONYAMLXMLBuilder(), StandardLogger())
<<<<<<< Upstream, based on spdx/master
            doc, error = jsonparser.parse(infile)
        assert not error
        assert doc.validate([]) == []
        return doc
=======
            return jsonparser.parse(infile)
>>>>>>> e152d93 Add maxDiff None to all tests and format code

    def parse_yaml_file(self, file_name):
        with open(file_name, mode='r') as infile:
            yamlparser = YAMLParser(JSONYAMLXMLBuilder(), StandardLogger())
<<<<<<< Upstream, based on spdx/master
            doc, error = yamlparser.parse(infile)
        assert not error
        assert doc.validate([]) == []
        return doc
=======
            return yamlparser.parse(infile)
>>>>>>> e152d93 Add maxDiff None to all tests and format code

    def parse_xml_file(self, file_name):
        with open(file_name, mode='r') as infile:
            xmlparser = XMLParser(JSONYAMLXMLBuilder(), StandardLogger())
            doc, error = xmlparser.parse(infile)
        assert not error
        assert doc.validate([]) == []
        return doc

    def write_tagvalue_file(self, document, file_name):
        with codecs.open(file_name, mode='w', encoding='utf-8') as out:
            tvwriter.write_document(document, out)

    def write_rdf_file(self, document, file_name):
        with open(file_name, mode='wb') as out:
            rdfwriter.write_document(document, out)

    def write_json_file(self, document, file_name):
        with open(file_name, mode='w') as out:
            jsonwriter.write_document(document, out)

    def write_yaml_file(self, document, file_name):
        with open(file_name, mode='w') as out:
            yamlwriter.write_document(document, out)

    def write_xml_file(self, document, file_name):
        with open(file_name, mode='w') as out:
            xmlwriter.write_document(document, out)

    def test_tagvalue_rdf(self):
        doc = self.parse_tagvalue_file(utils_test.get_test_loc('formats/SPDXTagExample.tag'))
        filename = get_temp_file('.rdf')
        self.write_rdf_file(doc, filename)
<<<<<<< Upstream, based on spdx/master
        self.parse_rdf_file(filename)
=======
        doc, error = self.parse_rdf_file(filename)
        assert not error
        assert doc.validate([]) == []
>>>>>>> e152d93 Add maxDiff None to all tests and format code

    def test_json_rdf(self):
        doc = self.parse_json_file(utils_test.get_test_loc('formats/SPDXJsonExample.json'))
        filename = get_temp_file('.rdf')
        self.write_rdf_file(doc, filename)
<<<<<<< Upstream, based on spdx/master
        self.parse_rdf_file(filename)
=======
        doc, error = self.parse_rdf_file(filename)
        assert not error
        assert doc.validate([]) == []
>>>>>>> e152d93 Add maxDiff None to all tests and format code

    def test_yaml_rdf(self):
        doc = self.parse_yaml_file(utils_test.get_test_loc('formats/SPDXYamlExample.yaml'))
        filename = get_temp_file('.rdf')
        self.write_rdf_file(doc, filename)
        self.parse_rdf_file(filename)

    def test_xml_rdf(self):
        doc = self.parse_xml_file(utils_test.get_test_loc('formats/SPDXXmlExample.xml'))
        filename = get_temp_file('.rdf')
        self.write_rdf_file(doc, filename)
        self.parse_rdf_file(filename)

    def test_rdf_rdf(self):
        doc = self.parse_rdf_file(utils_test.get_test_loc('formats/SPDXRdfExample.rdf'))
        filename = get_temp_file('.rdf')
        self.write_rdf_file(doc, filename)
        self.parse_rdf_file(filename)

    def test_tagvalue_tagvalue(self):
        doc = self.parse_tagvalue_file(utils_test.get_test_loc('formats/SPDXTagExample.tag'))
        filename = get_temp_file('.tag')
        self.write_tagvalue_file(doc, filename)
        self.parse_tagvalue_file(filename)

    def test_rdf_tagvalue(self):
        doc = self.parse_rdf_file(utils_test.get_test_loc('formats/SPDXRdfExample.rdf'))
        filename = get_temp_file('.tag')
        self.write_tagvalue_file(doc, filename)
<<<<<<< Upstream, based on spdx/master
        self.parse_tagvalue_file(filename)
=======
        ###############################################
        doc, error = self.parse_tagvalue_file(filename)
        # print(doc.annotations[-1].annotation_type)
        assert not error
        assert doc.validate([]) == []
>>>>>>> e152d93 Add maxDiff None to all tests and format code

    def test_json_tagvalue(self):
        doc = self.parse_json_file(utils_test.get_test_loc('formats/SPDXJsonExample.json'))
        filename = get_temp_file('.tag')
        self.write_tagvalue_file(doc, filename)
<<<<<<< Upstream, based on spdx/master
        self.parse_tagvalue_file(filename)
=======
        doc, error = self.parse_tagvalue_file(filename)
        assert not error
        assert doc.validate([]) == []
>>>>>>> e152d93 Add maxDiff None to all tests and format code

    def test_yaml_tagvalue(self):
        doc = self.parse_yaml_file(utils_test.get_test_loc('formats/SPDXYamlExample.yaml'))
        filename = get_temp_file('.tag')
        self.write_tagvalue_file(doc, filename)
        self.parse_tagvalue_file(filename)

    def test_xml_tagvalue(self):
        doc = self.parse_xml_file(utils_test.get_test_loc('formats/SPDXXmlExample.xml'))
        filename = get_temp_file('.tag')
        self.write_tagvalue_file(doc, filename)
<<<<<<< Upstream, based on spdx/master
        self.parse_tagvalue_file(filename)
=======
        doc, error = self.parse_tagvalue_file(filename)
        assert not error
        assert doc.validate([]) == []
>>>>>>> e152d93 Add maxDiff None to all tests and format code

    def test_tagvalue_json(self):
        doc = self.parse_tagvalue_file(utils_test.get_test_loc('formats/SPDXTagExample.tag'))
        filename = get_temp_file('.json')
        self.write_json_file(doc, filename)
<<<<<<< Upstream, based on spdx/master
        self.parse_json_file(filename)
=======
        doc, error = self.parse_json_file(filename)
        assert not error
        assert doc.validate([]) == []
>>>>>>> e152d93 Add maxDiff None to all tests and format code

    def test_rdf_json(self):
        doc = self.parse_rdf_file(utils_test.get_test_loc('formats/SPDXRdfExample.rdf'))
        filename = get_temp_file('.json')
        self.write_json_file(doc, filename)
<<<<<<< Upstream, based on spdx/master
        self.parse_json_file(filename)
=======
        doc, error = self.parse_json_file(filename)
        assert not error
        assert doc.validate([]) == []
>>>>>>> e152d93 Add maxDiff None to all tests and format code

    def test_yaml_json(self):
        doc = self.parse_yaml_file(utils_test.get_test_loc('formats/SPDXYamlExample.yaml'))
        filename = get_temp_file('.json')
        self.write_json_file(doc, filename)
        self.parse_json_file(filename)

    def test_xml_json(self):
        doc = self.parse_xml_file(utils_test.get_test_loc('formats/SPDXXmlExample.xml'))
        filename = get_temp_file('.json')
        self.write_json_file(doc, filename)
<<<<<<< Upstream, based on spdx/master
        self.parse_json_file(filename)
=======
        doc, error = self.parse_json_file(filename)
        assert not error
        assert doc.validate([]) == []
>>>>>>> e152d93 Add maxDiff None to all tests and format code

    def test_json_json(self):
        doc = self.parse_json_file(utils_test.get_test_loc('formats/SPDXJsonExample.json'))
        filename = get_temp_file('.json')
        self.write_json_file(doc, filename)
<<<<<<< Upstream, based on spdx/master
        self.parse_json_file(filename)
=======
        doc, error = self.parse_json_file(filename)
        assert not error
        assert doc.validate([]) == []
>>>>>>> e152d93 Add maxDiff None to all tests and format code

    def test_tagvalue_yaml(self):
        doc = self.parse_tagvalue_file(utils_test.get_test_loc('formats/SPDXTagExample.tag'))
        filename = get_temp_file('.yaml')
        self.write_yaml_file(doc, filename)
<<<<<<< Upstream, based on spdx/master
        self.parse_yaml_file(filename)
=======
        doc, error = self.parse_yaml_file(filename)
        assert not error
        assert doc.validate([]) == []
>>>>>>> e152d93 Add maxDiff None to all tests and format code

    def test_rdf_yaml(self):
        doc = self.parse_rdf_file(utils_test.get_test_loc('formats/SPDXRdfExample.rdf'))
        filename = get_temp_file('.yaml')
        self.write_yaml_file(doc, filename)
<<<<<<< Upstream, based on spdx/master
        self.parse_yaml_file(filename)
=======
        doc, error = self.parse_yaml_file(filename)
        assert not error
        assert doc.validate([]) == []
>>>>>>> e152d93 Add maxDiff None to all tests and format code

    def test_json_yaml(self):
        doc = self.parse_json_file(utils_test.get_test_loc('formats/SPDXJsonExample.json'))
        filename = get_temp_file('.yaml')
        self.write_yaml_file(doc, filename)
        self.parse_yaml_file(filename)

    def test_xml_yaml(self):
        doc = self.parse_xml_file(utils_test.get_test_loc('formats/SPDXXmlExample.xml'))
        filename = get_temp_file('.yaml')
        self.write_yaml_file(doc, filename)
<<<<<<< Upstream, based on spdx/master
        self.parse_yaml_file(filename)
=======
        doc, error = self.parse_yaml_file(filename)
        assert not error
        assert doc.validate([]) == []
>>>>>>> e152d93 Add maxDiff None to all tests and format code

    def test_yaml_yaml(self):
        doc = self.parse_yaml_file(utils_test.get_test_loc('formats/SPDXYamlExample.yaml'))
        filename = get_temp_file('.yaml')
        self.write_yaml_file(doc, filename)
<<<<<<< Upstream, based on spdx/master
        self.parse_yaml_file(filename)
=======
        doc, error = self.parse_yaml_file(filename)
        assert not error
        assert doc.validate([]) == []
>>>>>>> e152d93 Add maxDiff None to all tests and format code

    def test_tagvalue_xml(self):
        doc = self.parse_tagvalue_file(utils_test.get_test_loc('formats/SPDXTagExample.tag'))
        filename = get_temp_file('.xml')
        self.write_xml_file(doc, filename)
<<<<<<< Upstream, based on spdx/master
        self.parse_xml_file(filename)
=======
        doc, error = self.parse_xml_file(filename)
        assert not error
        assert doc.validate([]) == []
>>>>>>> e152d93 Add maxDiff None to all tests and format code

    def test_rdf_xml(self):
        doc = self.parse_rdf_file(utils_test.get_test_loc('formats/SPDXRdfExample.rdf'))
        filename = get_temp_file('.xml')
        self.write_xml_file(doc, filename)
<<<<<<< Upstream, based on spdx/master
        self.parse_xml_file(filename)
=======
        doc, error = self.parse_xml_file(filename)
        assert not error
        assert doc.validate([]) == []
>>>>>>> e152d93 Add maxDiff None to all tests and format code

    def test_json_xml(self):
        doc = self.parse_json_file(utils_test.get_test_loc('formats/SPDXJsonExample.json'))
        filename = get_temp_file('.xml')
        self.write_xml_file(doc, filename)
<<<<<<< Upstream, based on spdx/master
        self.parse_xml_file(filename)
=======
        doc, error = self.parse_xml_file(filename)
        assert not error
        assert doc.validate([]) == []
>>>>>>> e152d93 Add maxDiff None to all tests and format code

    def test_yaml_xml(self):
        doc = self.parse_yaml_file(utils_test.get_test_loc('formats/SPDXYamlExample.yaml'))
        filename = get_temp_file('.xml')
        self.write_xml_file(doc, filename)
        self.parse_xml_file(filename)

    def test_xml_xml(self):
        doc = self.parse_xml_file(utils_test.get_test_loc('formats/SPDXXmlExample.xml'))
        filename = get_temp_file('.xml')
        self.write_xml_file(doc, filename)
<<<<<<< Upstream, based on spdx/master
        self.parse_xml_file(filename)
=======
        doc, error = self.parse_xml_file(filename)
        assert not error
        assert doc.validate([]) == []
>>>>>>> e152d93 Add maxDiff None to all tests and format code
<commit_msg>Move test data to tests. Simplify tests code<commit_after>
# Copyright (c) 2014 Ahmed H. Ismail
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#     http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals

import codecs
import os
import tempfile
from unittest import TestCase

from spdx.parsers.rdf import Parser as RDFParser
from spdx.parsers.rdfbuilders import Builder as RDFBuilder
from spdx.parsers.loggers import StandardLogger
from spdx.parsers.tagvalue import Parser as TVParser
from spdx.parsers.tagvaluebuilders import Builder as TVBuilder
from spdx.parsers.jsonparser import Parser as JSONParser
from spdx.parsers.yamlparser import Parser as YAMLParser
from spdx.parsers.xmlparser import Parser as XMLParser
from spdx.parsers.jsonyamlxmlbuilders import Builder as JSONYAMLXMLBuilder
import spdx.writers.rdf as rdfwriter
import spdx.writers.tagvalue as tvwriter
import spdx.writers.json as jsonwriter
import spdx.writers.yaml as yamlwriter
import spdx.writers.xml as xmlwriter

from tests import utils_test

def get_temp_file(extension=''):
    """
    Return a unique new temporary file location to a non-existing
    temporary file that can safely be created without a risk of name
    collision.
    """

    if extension and not extension.startswith('.'):
            extension = '.' + extension
    file_name = 'temp_file' + extension
    temp_dir = tempfile.mkdtemp()
    return os.path.join(temp_dir, file_name)

class TestConversions(TestCase):
    maxDiff = None

    def parse_rdf_file(self, file_name):
        with open(file_name, mode='rb') as infile:
            rdfparser = RDFParser(RDFBuilder(), StandardLogger())
            doc, error = rdfparser.parse(infile)
        assert not error
        assert doc.validate([]) == []
        return doc

    def parse_tagvalue_file(self, file_name):
        with open(file_name, mode='r') as infile:
            tvparser = TVParser(TVBuilder(), StandardLogger())
            tvparser.build()
            doc, error = tvparser.parse(infile.read())
        assert not error
        assert doc.validate([]) == []
        return doc

    def parse_json_file(self, file_name):
        with open(file_name, mode='r') as infile:
            jsonparser = JSONParser(JSONYAMLXMLBuilder(), StandardLogger())
            doc, error = jsonparser.parse(infile)
        assert not error
        assert doc.validate([]) == []
        return doc

    def parse_yaml_file(self, file_name):
        with open(file_name, mode='r') as infile:
            yamlparser = YAMLParser(JSONYAMLXMLBuilder(), StandardLogger())
            doc, error = yamlparser.parse(infile)
        assert not error
        assert doc.validate([]) == []
        return doc

    def parse_xml_file(self, file_name):
        with open(file_name, mode='r') as infile:
            xmlparser = XMLParser(JSONYAMLXMLBuilder(), StandardLogger())
            doc, error = xmlparser.parse(infile)
        assert not error
        assert doc.validate([]) == []
        return doc

    def write_tagvalue_file(self, document, file_name):
        with codecs.open(file_name, mode='w', encoding='utf-8') as out:
            tvwriter.write_document(document, out)

    def write_rdf_file(self, document, file_name):
        with open(file_name, mode='wb') as out:
            rdfwriter.write_document(document, out)

    def write_json_file(self, document, file_name):
        with open(file_name, mode='w') as out:
            jsonwriter.write_document(document, out)

    def write_yaml_file(self, document, file_name):
        with open(file_name, mode='w') as out:
            yamlwriter.write_document(document, out)

    def write_xml_file(self, document, file_name):
        with open(file_name, mode='w') as out:
            xmlwriter.write_document(document, out)

    def test_tagvalue_rdf(self):
        doc = self.parse_tagvalue_file(utils_test.get_test_loc('formats/SPDXTagExample.tag'))
        filename = get_temp_file('.rdf')
        self.write_rdf_file(doc, filename)
        self.parse_rdf_file(filename)

    def test_json_rdf(self):
        doc = self.parse_json_file(utils_test.get_test_loc('formats/SPDXJsonExample.json'))
        filename = get_temp_file('.rdf')
        self.write_rdf_file(doc, filename)
        self.parse_rdf_file(filename)

    def test_yaml_rdf(self):
        doc = self.parse_yaml_file(utils_test.get_test_loc('formats/SPDXYamlExample.yaml'))
        filename = get_temp_file('.rdf')
        self.write_rdf_file(doc, filename)
        self.parse_rdf_file(filename)

    def test_xml_rdf(self):
        doc = self.parse_xml_file(utils_test.get_test_loc('formats/SPDXXmlExample.xml'))
        filename = get_temp_file('.rdf')
        self.write_rdf_file(doc, filename)
        self.parse_rdf_file(filename)

    def test_rdf_rdf(self):
        doc = self.parse_rdf_file(utils_test.get_test_loc('formats/SPDXRdfExample.rdf'))
        filename = get_temp_file('.rdf')
        self.write_rdf_file(doc, filename)
        self.parse_rdf_file(filename)

    def test_tagvalue_tagvalue(self):
        doc = self.parse_tagvalue_file(utils_test.get_test_loc('formats/SPDXTagExample.tag'))
        filename = get_temp_file('.tag')
        self.write_tagvalue_file(doc, filename)
        self.parse_tagvalue_file(filename)

    def test_rdf_tagvalue(self):
        doc = self.parse_rdf_file(utils_test.get_test_loc('formats/SPDXRdfExample.rdf'))
        filename = get_temp_file('.tag')
        self.write_tagvalue_file(doc, filename)
        self.parse_tagvalue_file(filename)

    def test_json_tagvalue(self):
        doc = self.parse_json_file(utils_test.get_test_loc('formats/SPDXJsonExample.json'))
        filename = get_temp_file('.tag')
        self.write_tagvalue_file(doc, filename)
        self.parse_tagvalue_file(filename)

    def test_yaml_tagvalue(self):
        doc = self.parse_yaml_file(utils_test.get_test_loc('formats/SPDXYamlExample.yaml'))
        filename = get_temp_file('.tag')
        self.write_tagvalue_file(doc, filename)
        self.parse_tagvalue_file(filename)

    def test_xml_tagvalue(self):
        doc = self.parse_xml_file(utils_test.get_test_loc('formats/SPDXXmlExample.xml'))
        filename = get_temp_file('.tag')
        self.write_tagvalue_file(doc, filename)
        self.parse_tagvalue_file(filename)

    def test_tagvalue_json(self):
        doc = self.parse_tagvalue_file(utils_test.get_test_loc('formats/SPDXTagExample.tag'))
        filename = get_temp_file('.json')
        self.write_json_file(doc, filename)
        self.parse_json_file(filename)

    def test_rdf_json(self):
        doc = self.parse_rdf_file(utils_test.get_test_loc('formats/SPDXRdfExample.rdf'))
        filename = get_temp_file('.json')
        self.write_json_file(doc, filename)
        self.parse_json_file(filename)

    def test_yaml_json(self):
        doc = self.parse_yaml_file(utils_test.get_test_loc('formats/SPDXYamlExample.yaml'))
        filename = get_temp_file('.json')
        self.write_json_file(doc, filename)
        self.parse_json_file(filename)

    def test_xml_json(self):
        doc = self.parse_xml_file(utils_test.get_test_loc('formats/SPDXXmlExample.xml'))
        filename = get_temp_file('.json')
        self.write_json_file(doc, filename)
        self.parse_json_file(filename)

    def test_json_json(self):
        doc = self.parse_json_file(utils_test.get_test_loc('formats/SPDXJsonExample.json'))
        filename = get_temp_file('.json')
        self.write_json_file(doc, filename)
        self.parse_json_file(filename)

    def test_tagvalue_yaml(self):
        doc = self.parse_tagvalue_file(utils_test.get_test_loc('formats/SPDXTagExample.tag'))
        filename = get_temp_file('.yaml')
        self.write_yaml_file(doc, filename)
        self.parse_yaml_file(filename)

    def test_rdf_yaml(self):
        doc = self.parse_rdf_file(utils_test.get_test_loc('formats/SPDXRdfExample.rdf'))
        filename = get_temp_file('.yaml')
        self.write_yaml_file(doc, filename)
        self.parse_yaml_file(filename)

    def test_json_yaml(self):
        doc = self.parse_json_file(utils_test.get_test_loc('formats/SPDXJsonExample.json'))
        filename = get_temp_file('.yaml')
        self.write_yaml_file(doc, filename)
        self.parse_yaml_file(filename)

    def test_xml_yaml(self):
        doc = self.parse_xml_file(utils_test.get_test_loc('formats/SPDXXmlExample.xml'))
        filename = get_temp_file('.yaml')
        self.write_yaml_file(doc, filename)
        self.parse_yaml_file(filename)

    def test_yaml_yaml(self):
        doc = self.parse_yaml_file(utils_test.get_test_loc('formats/SPDXYamlExample.yaml'))
        filename = get_temp_file('.yaml')
        self.write_yaml_file(doc, filename)
        self.parse_yaml_file(filename)

    def test_tagvalue_xml(self):
        doc = self.parse_tagvalue_file(utils_test.get_test_loc('formats/SPDXTagExample.tag'))
        filename = get_temp_file('.xml')
        self.write_xml_file(doc, filename)
        self.parse_xml_file(filename)

    def test_rdf_xml(self):
        doc = self.parse_rdf_file(utils_test.get_test_loc('formats/SPDXRdfExample.rdf'))
        filename = get_temp_file('.xml')
        self.write_xml_file(doc, filename)
        self.parse_xml_file(filename)

    def test_json_xml(self):
        doc = self.parse_json_file(utils_test.get_test_loc('formats/SPDXJsonExample.json'))
        filename = get_temp_file('.xml')
        self.write_xml_file(doc, filename)
        self.parse_xml_file(filename)

    def test_yaml_xml(self):
        doc = self.parse_yaml_file(utils_test.get_test_loc('formats/SPDXYamlExample.yaml'))
        filename = get_temp_file('.xml')
        self.write_xml_file(doc, filename)
        self.parse_xml_file(filename)

    def test_xml_xml(self):
        doc = self.parse_xml_file(utils_test.get_test_loc('formats/SPDXXmlExample.xml'))
        filename = get_temp_file('.xml')
        self.write_xml_file(doc, filename)
        self.parse_xml_file(filename)
<|endoftext|>


<commit_before># No shebang line, this module is meant to be imported
#
# Copyright 2013 Oliver Palmer
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from os import urandom
from uuid import uuid4
from random import randint, choice

from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.types import BigInteger, CHAR
from sqlalchemy.exc import StatementError

from utcore import ModelTestCase, unittest
from pyfarm.core.enums import AgentState, DBAgentState, WorkState, DBWorkState
from pyfarm.master.application import db
from pyfarm.models.core.cfg import TABLE_PREFIX
from pyfarm.models.core.types import (
    IPv4Address, UseAgentAddressEnum, JSONDict, JSONList,
    JSONSerializable, id_column, GUID, AgentStateEnum,
    IDTypeWork, IDTypeAgent, IDTypeTag, IPAddress, WorkStateEnum)

class TypeModel(db.Model):
    __tablename__ = "%s_test_types" % TABLE_PREFIX
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    ipv4 = db.Column(IPv4Address)
    json_dict = db.Column(JSONDict)
    json_list = db.Column(JSONList)
    agent_addr = db.Column(UseAgentAddressEnum)
    agent_state = db.Column(AgentStateEnum)
    work_state = db.Column(WorkStateEnum)

class TestJsonTypes(ModelTestCase):
    def test_types_notimplemented(self):
        class TestType(JSONSerializable):
            pass

        with self.assertRaises(NotImplementedError):
            TestType()

    def test_dict(self):
        for test_type in JSONDict.serialize_types:
            for i in xrange(10):
                test_data = test_type({
                    "str": urandom(1024).encode("hex"),
                    "int": randint(-1024, 1024),
                    "list": [
                        urandom(1024).encode("hex"), -1024, 1024, True, None],
                    "bool": choice([True, False]), "none": None,
                    "dict": {
                        "str": urandom(1024).encode("hex"),
                        "true": True, "false": False,
                        "int": randint(-1024, 1024),
                        "list": [
                            urandom(1024).encode("hex"),
                            -1024, 1024, True, None]}})

                model = TypeModel(json_dict=test_data)
                self.assertIsInstance(model.json_dict, test_type)
                db.session.add(model)
                db.session.commit()
                insert_id = model.id
                db.session.remove()
                result = TypeModel.query.filter_by(id=insert_id).first()
                self.assertIsNot(model, result)
                self.assertIsInstance(model.json_dict, dict)
                self.assertEqual(model.json_dict, result.json_dict)

    def test_dict_error(self):
        model = TypeModel(json_dict=[])
        db.session.add(model)

        with self.assertRaises(StatementError):
            db.session.commit()

    def test_list(self):
        for test_type in JSONList.serialize_types:
            for i in xrange(10):
                test_data = test_type(
                    [urandom(1024).encode("hex"), -1024, 1024, True, None])

                model = TypeModel(json_list=test_data)
                self.assertIsInstance(model.json_list, test_type)
                db.session.add(model)
                db.session.commit()
                insert_id = model.id
                db.session.remove()
                result = TypeModel.query.filter_by(id=insert_id).first()
                self.assertIsNot(model, result)
                self.assertIsInstance(model.json_list, list)
                self.assertEqual(model.json_list, result.json_list)

    def test_list_error(self):
        data = TypeModel(json_list={})
        db.session.add(data)

        with self.assertRaises(StatementError):
            db.session.commit()

class TestIPAddressType(ModelTestCase):
    def test_implementation(self):
        # IP addrs are a spec, we need to be specific
        self.assertIs(IPv4Address.impl, BigInteger)
        self.assertEqual(IPv4Address.MAX_INT, 4294967295)

        with self.assertRaises(ValueError):
            instance = IPv4Address()
            instance.checkInteger(-1)

        with self.assertRaises(ValueError):
            instance = IPv4Address()
            instance.checkInteger(IPv4Address.MAX_INT + 1)

    def test_comparison(self):
        self.assertEqual(IPAddress("0.0.0.0"), "0.0.0.0")
        self.assertNotEqual(IPAddress("0.0.0.0"), "0.0.0.1")
        self.assertEqual(IPAddress("0.0.0.0"), int(IPAddress("0.0.0.0")))
        self.assertNotEqual(IPAddress("0.0.0.0"), int(IPAddress("0.0.0.1")))
        self.assertEqual(IPAddress("0.0.0.0"), IPAddress("0.0.0.0"))
        self.assertNotEqual(IPAddress("0.0.0.0"), IPAddress("0.0.0.1"))

    def test_insert_int(self):
        ipvalue = int(IPAddress("192.168.1.1"))
        model = TypeModel(ipv4=ipvalue)
        self.assertEqual(model.ipv4, ipvalue)
        db.session.add(model)
        db.session.commit()
        insert_id = model.id
        db.session.remove()
        result = TypeModel.query.filter_by(id=insert_id).first()
        self.assertIsInstance(result.ipv4, IPAddress)
        self.assertEqual(int(result.ipv4), ipvalue)

    def test_insert_string(self):
        ipvalue = "192.168.1.1"
        model = TypeModel(ipv4=ipvalue)
        self.assertEqual(model.ipv4, ipvalue)
        db.session.add(model)
        db.session.commit()
        insert_id = model.id
        db.session.remove()
        result = TypeModel.query.filter_by(id=insert_id).first()
        self.assertIsInstance(result.ipv4, IPAddress)
        self.assertEqual(str(result.ipv4), ipvalue)

    def test_insert_ipclass(self):
        ipvalue = IPAddress("192.168.1.1")
        model = TypeModel(ipv4=ipvalue)
        self.assertEqual(model.ipv4, ipvalue)
        db.session.add(model)
        db.session.commit()
        insert_id = model.id
        db.session.remove()
        result = TypeModel.query.filter_by(id=insert_id).first()
        self.assertIsInstance(result.ipv4, IPAddress)
        self.assertEqual(result.ipv4, ipvalue)

    def test_insert_float(self):
        ipvalue = 3.14
        model = TypeModel(ipv4=ipvalue)
        self.assertEqual(model.ipv4, ipvalue)
        db.session.add(model)
        with self.assertRaises(StatementError):
            db.session.commit()

class TestIDColumn(ModelTestCase):
    def test_integer(self):
        column = id_column(db.Integer)
        self.assertIsInstance(column.type, db.Integer)
        self.assertTrue(column.primary_key)
        self.assertFalse(column.nullable)
        self.assertTrue(column.autoincrement)

    def test_id_types(self):
        if db.engine.name == "sqlite":
            self.assertIs(IDTypeWork, db.Integer)
        else:
            self.assertIs(IDTypeWork, db.BigInteger)

        self.assertIs(IDTypeAgent, db.Integer)
        self.assertIs(IDTypeTag, db.Integer)

class TestAgentStateEnumTypes(ModelTestCase):
    def test_invalid(self):
        model = TypeModel(agent_state=1e10)
        db.session.add(model)

        with self.assertRaises(StatementError):
            db.session.commit()

        db.session.remove()

        model = TypeModel(agent_state=urandom(10).encode("hex"))
        db.session.add(model)

        with self.assertRaises(StatementError):
            db.session.commit()

    def test_integer(self):
        for i in DBAgentState:
            model = TypeModel(agent_state=i)
            self.assertEqual(model.agent_state, i)
            db.session.add(model)
            db.session.commit()
            model_id = model.id
            db.session.remove()
            result = TypeModel.query.filter_by(id=model_id).first()
            self.assertEqual(result.agent_state, i)

    def test_string(self):
        for i in AgentState:
            model = TypeModel(agent_state=i)
            self.assertEqual(model.agent_state, i)
            db.session.add(model)
            db.session.commit()
            model_id = model.id
            db.session.remove()
            result = TypeModel.query.filter_by(id=model_id).first()
            self.assertEqual(result.agent_state, i)

    def test_ge(self):
        print "START"
        model = TypeModel(agent_state=AgentState.RUNNING)
        print type(model.agent_state)
        db.session.add(model)
        db.session.commit()
        print type(model.agent_state)

class TestGUIDImpl(unittest.TestCase):
    def _dialect(self, name, driver):
        """
        constructs a fake dialect object that replicates a
        sqlalchemy dialect
        """
        return type("FakeDialect", (object, ), {
                    "name": name,
                    "driver": driver,
                    "type_descriptor": lambda self, value: value})()

    def _short(self, value):
        return str(value).replace("-", "")

    def test_id_column(self):
        column = id_column(GUID)
        self.assertIsInstance(column.type, GUID)
        self.assertTrue(column.primary_key)
        self.assertFalse(column.nullable)
        self.assertTrue(column.autoincrement)

    def test_driver_psycopg2(self):
        guid = GUID()
        dialect = self._dialect("postgresql", "psycopg2")
        impl = guid.load_dialect_impl(dialect)
        self.assertIsInstance(impl, UUID)

    def test_driver_pg8000(self):
        guid = GUID()
        dialect = self._dialect("postgresql", "pg8000")
        impl = guid.load_dialect_impl(dialect)
        self.assertIsInstance(impl, CHAR)

    def test_driver_mysql(self):
        guid = GUID()
        dialect = self._dialect("mysql", None)
        impl = guid.load_dialect_impl(dialect)
        self.assertIsInstance(impl, CHAR)
        self.assertEqual(impl.length, 32)

    def test_bind_param(self):
        guid = GUID()
        self.assertIsNone(guid.process_bind_param(None, None))
        dialect = self._dialect("postgresql", None)
        uid = uuid4()
        short_uid = self._short(uid)
        self.assertEqual(
            guid.process_bind_param(uid, dialect), short_uid)
        dialect = self._dialect(None, None)
        self.assertEqual(
            guid.process_bind_param(uid, dialect), short_uid)
        self.assertEqual(
            guid.process_bind_param(str(uid), dialect), short_uid)
        self.assertEqual(
            guid.process_bind_param(self._short(str(uid)), dialect), short_uid)
<commit_msg>removing unused test<commit_after># No shebang line, this module is meant to be imported
#
# Copyright 2013 Oliver Palmer
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from os import urandom
from uuid import uuid4
from random import randint, choice

from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.types import BigInteger, CHAR
from sqlalchemy.exc import StatementError

from utcore import ModelTestCase, unittest
from pyfarm.core.enums import AgentState, DBAgentState, WorkState, DBWorkState
from pyfarm.master.application import db
from pyfarm.models.core.cfg import TABLE_PREFIX
from pyfarm.models.core.types import (
    IPv4Address, UseAgentAddressEnum, JSONDict, JSONList,
    JSONSerializable, id_column, GUID, AgentStateEnum,
    IDTypeWork, IDTypeAgent, IDTypeTag, IPAddress, WorkStateEnum)

class TypeModel(db.Model):
    __tablename__ = "%s_test_types" % TABLE_PREFIX
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    ipv4 = db.Column(IPv4Address)
    json_dict = db.Column(JSONDict)
    json_list = db.Column(JSONList)
    agent_addr = db.Column(UseAgentAddressEnum)
    agent_state = db.Column(AgentStateEnum)
    work_state = db.Column(WorkStateEnum)

class TestJsonTypes(ModelTestCase):
    def test_types_notimplemented(self):
        class TestType(JSONSerializable):
            pass

        with self.assertRaises(NotImplementedError):
            TestType()

    def test_dict(self):
        for test_type in JSONDict.serialize_types:
            for i in xrange(10):
                test_data = test_type({
                    "str": urandom(1024).encode("hex"),
                    "int": randint(-1024, 1024),
                    "list": [
                        urandom(1024).encode("hex"), -1024, 1024, True, None],
                    "bool": choice([True, False]), "none": None,
                    "dict": {
                        "str": urandom(1024).encode("hex"),
                        "true": True, "false": False,
                        "int": randint(-1024, 1024),
                        "list": [
                            urandom(1024).encode("hex"),
                            -1024, 1024, True, None]}})

                model = TypeModel(json_dict=test_data)
                self.assertIsInstance(model.json_dict, test_type)
                db.session.add(model)
                db.session.commit()
                insert_id = model.id
                db.session.remove()
                result = TypeModel.query.filter_by(id=insert_id).first()
                self.assertIsNot(model, result)
                self.assertIsInstance(model.json_dict, dict)
                self.assertEqual(model.json_dict, result.json_dict)

    def test_dict_error(self):
        model = TypeModel(json_dict=[])
        db.session.add(model)

        with self.assertRaises(StatementError):
            db.session.commit()

    def test_list(self):
        for test_type in JSONList.serialize_types:
            for i in xrange(10):
                test_data = test_type(
                    [urandom(1024).encode("hex"), -1024, 1024, True, None])

                model = TypeModel(json_list=test_data)
                self.assertIsInstance(model.json_list, test_type)
                db.session.add(model)
                db.session.commit()
                insert_id = model.id
                db.session.remove()
                result = TypeModel.query.filter_by(id=insert_id).first()
                self.assertIsNot(model, result)
                self.assertIsInstance(model.json_list, list)
                self.assertEqual(model.json_list, result.json_list)

    def test_list_error(self):
        data = TypeModel(json_list={})
        db.session.add(data)

        with self.assertRaises(StatementError):
            db.session.commit()

class TestIPAddressType(ModelTestCase):
    def test_implementation(self):
        # IP addrs are a spec, we need to be specific
        self.assertIs(IPv4Address.impl, BigInteger)
        self.assertEqual(IPv4Address.MAX_INT, 4294967295)

        with self.assertRaises(ValueError):
            instance = IPv4Address()
            instance.checkInteger(-1)

        with self.assertRaises(ValueError):
            instance = IPv4Address()
            instance.checkInteger(IPv4Address.MAX_INT + 1)

    def test_comparison(self):
        self.assertEqual(IPAddress("0.0.0.0"), "0.0.0.0")
        self.assertNotEqual(IPAddress("0.0.0.0"), "0.0.0.1")
        self.assertEqual(IPAddress("0.0.0.0"), int(IPAddress("0.0.0.0")))
        self.assertNotEqual(IPAddress("0.0.0.0"), int(IPAddress("0.0.0.1")))
        self.assertEqual(IPAddress("0.0.0.0"), IPAddress("0.0.0.0"))
        self.assertNotEqual(IPAddress("0.0.0.0"), IPAddress("0.0.0.1"))

    def test_insert_int(self):
        ipvalue = int(IPAddress("192.168.1.1"))
        model = TypeModel(ipv4=ipvalue)
        self.assertEqual(model.ipv4, ipvalue)
        db.session.add(model)
        db.session.commit()
        insert_id = model.id
        db.session.remove()
        result = TypeModel.query.filter_by(id=insert_id).first()
        self.assertIsInstance(result.ipv4, IPAddress)
        self.assertEqual(int(result.ipv4), ipvalue)

    def test_insert_string(self):
        ipvalue = "192.168.1.1"
        model = TypeModel(ipv4=ipvalue)
        self.assertEqual(model.ipv4, ipvalue)
        db.session.add(model)
        db.session.commit()
        insert_id = model.id
        db.session.remove()
        result = TypeModel.query.filter_by(id=insert_id).first()
        self.assertIsInstance(result.ipv4, IPAddress)
        self.assertEqual(str(result.ipv4), ipvalue)

    def test_insert_ipclass(self):
        ipvalue = IPAddress("192.168.1.1")
        model = TypeModel(ipv4=ipvalue)
        self.assertEqual(model.ipv4, ipvalue)
        db.session.add(model)
        db.session.commit()
        insert_id = model.id
        db.session.remove()
        result = TypeModel.query.filter_by(id=insert_id).first()
        self.assertIsInstance(result.ipv4, IPAddress)
        self.assertEqual(result.ipv4, ipvalue)

    def test_insert_float(self):
        ipvalue = 3.14
        model = TypeModel(ipv4=ipvalue)
        self.assertEqual(model.ipv4, ipvalue)
        db.session.add(model)
        with self.assertRaises(StatementError):
            db.session.commit()

class TestIDColumn(ModelTestCase):
    def test_integer(self):
        column = id_column(db.Integer)
        self.assertIsInstance(column.type, db.Integer)
        self.assertTrue(column.primary_key)
        self.assertFalse(column.nullable)
        self.assertTrue(column.autoincrement)

    def test_id_types(self):
        if db.engine.name == "sqlite":
            self.assertIs(IDTypeWork, db.Integer)
        else:
            self.assertIs(IDTypeWork, db.BigInteger)

        self.assertIs(IDTypeAgent, db.Integer)
        self.assertIs(IDTypeTag, db.Integer)

class TestAgentStateEnumTypes(ModelTestCase):
    def test_invalid(self):
        model = TypeModel(agent_state=1e10)
        db.session.add(model)

        with self.assertRaises(StatementError):
            db.session.commit()

        db.session.remove()

        model = TypeModel(agent_state=urandom(10).encode("hex"))
        db.session.add(model)

        with self.assertRaises(StatementError):
            db.session.commit()

    def test_integer(self):
        for i in DBAgentState:
            model = TypeModel(agent_state=i)
            self.assertEqual(model.agent_state, i)
            db.session.add(model)
            db.session.commit()
            model_id = model.id
            db.session.remove()
            result = TypeModel.query.filter_by(id=model_id).first()
            self.assertEqual(result.agent_state, i)

    def test_string(self):
        for i in AgentState:
            model = TypeModel(agent_state=i)
            self.assertEqual(model.agent_state, i)
            db.session.add(model)
            db.session.commit()
            model_id = model.id
            db.session.remove()
            result = TypeModel.query.filter_by(id=model_id).first()
            self.assertEqual(result.agent_state, i)

class TestGUIDImpl(unittest.TestCase):
    def _dialect(self, name, driver):
        """
        constructs a fake dialect object that replicates a
        sqlalchemy dialect
        """
        return type("FakeDialect", (object, ), {
                    "name": name,
                    "driver": driver,
                    "type_descriptor": lambda self, value: value})()

    def _short(self, value):
        return str(value).replace("-", "")

    def test_id_column(self):
        column = id_column(GUID)
        self.assertIsInstance(column.type, GUID)
        self.assertTrue(column.primary_key)
        self.assertFalse(column.nullable)
        self.assertTrue(column.autoincrement)

    def test_driver_psycopg2(self):
        guid = GUID()
        dialect = self._dialect("postgresql", "psycopg2")
        impl = guid.load_dialect_impl(dialect)
        self.assertIsInstance(impl, UUID)

    def test_driver_pg8000(self):
        guid = GUID()
        dialect = self._dialect("postgresql", "pg8000")
        impl = guid.load_dialect_impl(dialect)
        self.assertIsInstance(impl, CHAR)

    def test_driver_mysql(self):
        guid = GUID()
        dialect = self._dialect("mysql", None)
        impl = guid.load_dialect_impl(dialect)
        self.assertIsInstance(impl, CHAR)
        self.assertEqual(impl.length, 32)

    def test_bind_param(self):
        guid = GUID()
        self.assertIsNone(guid.process_bind_param(None, None))
        dialect = self._dialect("postgresql", None)
        uid = uuid4()
        short_uid = self._short(uid)
        self.assertEqual(
            guid.process_bind_param(uid, dialect), short_uid)
        dialect = self._dialect(None, None)
        self.assertEqual(
            guid.process_bind_param(uid, dialect), short_uid)
        self.assertEqual(
            guid.process_bind_param(str(uid), dialect), short_uid)
        self.assertEqual(
            guid.process_bind_param(self._short(str(uid)), dialect), short_uid)
<|endoftext|>


<commit_before>""""""
import pytest
import logging
from dhcpcanon.dhcpcapfsm import DHCPCAPFSM

FORMAT = "%(levelname)s: %(filename)s:%(lineno)s - %(funcName)s - " + \
         "%(message)s"
logging.basicConfig(format=FORMAT, level=logging.DEBUG)
logger = logging.getLogger(__name__)

class TestDHCPCAPFSM:
    def test_intialize(self, dhcpcanon):
        assert dhcpcanon.client.client_mac == "00:0a:0b:0c:0d:0f"

# class TestDHCPCAPFSM(unittest.TestCase):
#     def TestBOUND(self):
#         # d_hcpcapfs_m = DHCPCAPFSM()
#         # self.assertEqual(expected, d_hcpcapfs_m.BOUND())
#         assert False # TODO: implement your test here
#
#     def TestEND(self):
#         # d_hcpcapfs_m = DHCPCAPFSM()
#         # self.assertEqual(expected, d_hcpcapfs_m.END())
#         assert False # TODO: implement your test here
#
#     def TestERROR(self):
#         # d_hcpcapfs_m = DHCPCAPFSM()
#         # self.assertEqual(expected, d_hcpcapfs_m.ERROR())
#         assert False # TODO: implement your test here
#
#     def TestINIT(self):
#         # d_hcpcapfs_m = DHCPCAPFSM()
#         # self.assertEqual(expected, d_hcpcapfs_m.INIT())
#         assert False # TODO: implement your test here
#
#     def TestREBINDING(self):
#         # d_hcpcapfs_m = DHCPCAPFSM()
#         # self.assertEqual(expected, d_hcpcapfs_m.REBINDING())
#         assert False # TODO: implement your test here
#
#     def TestRENEWING(self):
#         # d_hcpcapfs_m = DHCPCAPFSM()
#         # self.assertEqual(expected, d_hcpcapfs_m.RENEWING())
#         assert False # TODO: implement your test here
#
#     def TestREQUESTING(self):
#         # d_hcpcapfs_m = DHCPCAPFSM()
#         # self.assertEqual(expected, d_hcpcapfs_m.REQUESTING())
#         assert False # TODO: implement your test here
#
#     def TestSELECTING(self):
#         # d_hcpcapfs_m = DHCPCAPFSM()
#         # self.assertEqual(expected, d_hcpcapfs_m.SELECTING())
#         assert False # TODO: implement your test here
#
#     def test_get_timeout(self):
#         # d_hcpcapfs_m = DHCPCAPFSM()
#         # self.assertEqual(expected, d_hcpcapfs_m.get_timeout(state, function))
#         assert False # TODO: implement your test here
#
#     def test_lease_expires(self):
#         # d_hcpcapfs_m = DHCPCAPFSM()
#         # self.assertEqual(expected, d_hcpcapfs_m.lease_expires())
#         assert False # TODO: implement your test here
#
#     def test_on_ack_requesting(self):
#         # d_hcpcapfs_m = DHCPCAPFSM()
#         # self.assertEqual(expected, d_hcpcapfs_m.on_ack_requesting())
#         assert False # TODO: implement your test here
#
#     def test_on_rebinding(self):
#         # d_hcpcapfs_m = DHCPCAPFSM()
#         # self.assertEqual(expected, d_hcpcapfs_m.on_rebinding())
#         assert False # TODO: implement your test here
#
#     def test_on_rebinding_time_expires(self):
#         # d_hcpcapfs_m = DHCPCAPFSM()
#         # self.assertEqual(expected, d_hcpcapfs_m.on_rebinding_time_expires())
#         assert False # TODO: implement your test here
#
#     def test_on_renewing(self):
#         # d_hcpcapfs_m = DHCPCAPFSM()
#         # self.assertEqual(expected, d_hcpcapfs_m.on_renewing())
#         assert False # TODO: implement your test here
#
#     def test_on_renewing_time_expires(self):
#         # d_hcpcapfs_m = DHCPCAPFSM()
#         # self.assertEqual(expected, d_hcpcapfs_m.on_renewing_time_expires())
#         assert False # TODO: implement your test here
#
#     def test_on_retransmit_discover(self):
#         # d_hcpcapfs_m = DHCPCAPFSM()
#         # self.assertEqual(expected, d_hcpcapfs_m.on_retransmit_discover())
#         assert False # TODO: implement your test here
#
#     def test_on_retransmit_request(self):
#         # d_hcpcapfs_m = DHCPCAPFSM()
#         # self.assertEqual(expected, d_hcpcapfs_m.on_retransmit_request())
#         assert False # TODO: implement your test here
#
#     def test_on_retransmit_request_rebinding(self):
#         # d_hcpcapfs_m = DHCPCAPFSM()
#         # self.assertEqual(expected, d_hcpcapfs_m.on_retransmit_request_rebinding())
#         assert False # TODO: implement your test here
#
#     def test_on_retransmit_request_renewing(self):
#         # d_hcpcapfs_m = DHCPCAPFSM()
#         # self.assertEqual(expected, d_hcpcapfs_m.on_retransmit_request_renewing())
#         assert False # TODO: implement your test here
#
#     def test_on_select_offer(self):
#         # d_hcpcapfs_m = DHCPCAPFSM()
#         # self.assertEqual(expected, d_hcpcapfs_m.on_select_offer())
#         assert False # TODO: implement your test here
#
#     def test_on_timeout_delay_selecting(self):
#         # d_hcpcapfs_m = DHCPCAPFSM()
#         # self.assertEqual(expected, d_hcpcapfs_m.on_timeout_delay_selecting())
#         assert False # TODO: implement your test here
#
#     def test_parse_args(self):
#         # d_hcpcapfs_m = DHCPCAPFSM()
#         # self.assertEqual(expected, d_hcpcapfs_m.parse_args(iface, server_port, client_port, client_mac, scriptfile))
#         assert False # TODO: implement your test here
#
#     def test_process_received_ack(self):
#         # d_hcpcapfs_m = DHCPCAPFSM()
#         # self.assertEqual(expected, d_hcpcapfs_m.process_received_ack(pkt))
#         assert False # TODO: implement your test here
#
#     def test_process_received_nak(self):
#         # d_hcpcapfs_m = DHCPCAPFSM()
#         # self.assertEqual(expected, d_hcpcapfs_m.process_received_nak(pkt))
#         assert False # TODO: implement your test here
#
#     def test_rebinding_time_expires(self):
#         # d_hcpcapfs_m = DHCPCAPFSM()
#         # self.assertEqual(expected, d_hcpcapfs_m.rebinding_time_expires())
#         assert False # TODO: implement your test here
#
#     def test_receive_ack_rebinding(self):
#         # d_hcpcapfs_m = DHCPCAPFSM()
#         # self.assertEqual(expected, d_hcpcapfs_m.receive_ack_rebinding(pkt))
#         assert False # TODO: implement your test here
#
#     def test_receive_ack_renewing(self):
#         # d_hcpcapfs_m = DHCPCAPFSM()
#         # self.assertEqual(expected, d_hcpcapfs_m.receive_ack_renewing(pkt))
#         assert False # TODO: implement your test here
#
#     def test_receive_ack_requesting(self):
#         # d_hcpcapfs_m = DHCPCAPFSM()
#         # self.assertEqual(expected, d_hcpcapfs_m.receive_ack_requesting(pkt))
#         assert False # TODO: implement your test here
#
#     def test_receive_nak_rebinding(self):
#         # d_hcpcapfs_m = DHCPCAPFSM()
#         # self.assertEqual(expected, d_hcpcapfs_m.receive_nak_rebinding(pkt))
#         assert False # TODO: implement your test here
#
#     def test_receive_nak_renewing(self):
#         # d_hcpcapfs_m = DHCPCAPFSM()
#         # self.assertEqual(expected, d_hcpcapfs_m.receive_nak_renewing(pkt))
#         assert False # TODO: implement your test here
#
#     def test_receive_nak_requesting(self):
#         # d_hcpcapfs_m = DHCPCAPFSM()
#         # self.assertEqual(expected, d_hcpcapfs_m.receive_nak_requesting(pkt))
#         assert False # TODO: implement your test here
#
#     def test_receive_offer(self):
#         # d_hcpcapfs_m = DHCPCAPFSM()
#         # self.assertEqual(expected, d_hcpcapfs_m.receive_offer(pkt))
#         assert False # TODO: implement your test here
#
#     def test_renewing_time_expires(self):
#         # d_hcpcapfs_m = DHCPCAPFSM()
#         # self.assertEqual(expected, d_hcpcapfs_m.renewing_time_expires())
#         assert False # TODO: implement your test here
#
#     def test_reset(self):
#         # d_hcpcapfs_m = DHCPCAPFSM()
#         # self.assertEqual(expected, d_hcpcapfs_m.reset(iface, client_mac, **kargs))
#         assert False # TODO: implement your test here
#
#     def test_select_offer(self):
#         # d_hcpcapfs_m = DHCPCAPFSM()
#         # self.assertEqual(expected, d_hcpcapfs_m.select_offer())
#         assert False # TODO: implement your test here
#
#     def test_send_discover(self):
#         # d_hcpcapfs_m = DHCPCAPFSM()
#         # self.assertEqual(expected, d_hcpcapfs_m.send_discover())
#         assert False # TODO: implement your test here
#
#     def test_send_request(self):
#         # d_hcpcapfs_m = DHCPCAPFSM()
#         # self.assertEqual(expected, d_hcpcapfs_m.send_request())
#         assert False # TODO: implement your test here
#
#     def test_set_timeout(self):
#         # d_hcpcapfs_m = DHCPCAPFSM()
#         # self.assertEqual(expected, d_hcpcapfs_m.set_timeout(state, function, newtimeout))
#         assert False # TODO: implement your test here
#
#     def test_set_timers(self):
#         # d_hcpcapfs_m = DHCPCAPFSM()
#         # self.assertEqual(expected, d_hcpcapfs_m.set_timers())
#         assert False # TODO: implement your test here
#
#     def test_timeout_delay_selecting(self):
#         # d_hcpcapfs_m = DHCPCAPFSM()
#         # self.assertEqual(expected, d_hcpcapfs_m.timeout_delay_selecting())
#         assert False # TODO: implement your test here
#
#     def test_timeout_request_rebinding(self):
#         # d_hcpcapfs_m = DHCPCAPFSM()
#         # self.assertEqual(expected, d_hcpcapfs_m.timeout_request_rebinding())
#         assert False # TODO: implement your test here
#
#     def test_timeout_request_renewing(self):
#         # d_hcpcapfs_m = DHCPCAPFSM()
#         # self.assertEqual(expected, d_hcpcapfs_m.timeout_request_renewing())
#         assert False # TODO: implement your test here
#
#     def test_timeout_requesting(self):
#         # d_hcpcapfs_m = DHCPCAPFSM()
#         # self.assertEqual(expected, d_hcpcapfs_m.timeout_requesting())
#         assert False # TODO: implement your test here
#
#     def test_timeout_selecting(self):
#         # d_hcpcapfs_m = DHCPCAPFSM()
#         # self.assertEqual(expected, d_hcpcapfs_m.timeout_selecting())
#         assert False # TODO: implement your test here
#
# if __name__ == '__main__':
#     unittest.main()
<commit_msg>Create timeout test. Remove comments<commit_after>""""""
import pytest
import logging
from dhcpcanon.dhcpcapfsm import DHCPCAPFSM
from dhcpcanon.constants import STATE_REQUESTING

FORMAT = "%(levelname)s: %(filename)s:%(lineno)s - %(funcName)s - " + \
         "%(message)s"
logging.basicConfig(format=FORMAT, level=logging.DEBUG)
logger = logging.getLogger(__name__)

class TestDHCPCAPFSM:
    def test_intialize(self, dhcpcanon):
        assert dhcpcanon.client.client_mac == "00:0a:0b:0c:0d:0f"

    def test_set_timeout(self, dhcpcanon):
        dhcpcanon.set_timeout(STATE_REQUESTING, dhcpcanon.timeout_requesting, 1)
        timeout = dhcpcanon.get_timeout(STATE_REQUESTING,
                                        dhcpcanon.timeout_requesting)
        logger.debug('timeout %s', timeout)
        assert timeout == 1
<|endoftext|>


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

"""
<Program Name>
  test_ecdsa_keys.py

<Author>
  Vladimir Diaz <vladimir.v.diaz@gmail.com>

<Started>
  November 23, 2016.

<Copyright>
  See LICENSE for licensing information.

<Purpose>
  Test cases for test_ecdsa_keys.py.
"""

# Help with Python 3 compatibility, where the print statement is a function, an
# implicit relative import is invalid, and the '/' operator performs true
# division.  Example:  print 'hello world' raises a 'SyntaxError' exception.
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals

import unittest
import os
import logging

import securesystemslib.exceptions
import securesystemslib.formats
import securesystemslib.ecdsa_keys
import securesystemslib.pycrypto_keys

logger = logging.getLogger('securesystemslib_test_ecdsa_keys')

public, private = securesystemslib.ecdsa_keys.generate_public_and_private()
FORMAT_ERROR_MSG = 'securesystemslib.exceptions.FormatError raised.  Check object\'s format.'

class TestECDSA_keys(unittest.TestCase):
  def setUp(self):
    pass

  def test_generate_public_and_private(self):
    public, private = securesystemslib.ecdsa_keys.generate_public_and_private()

    # Check format of 'public' and 'private'.
    self.assertEqual(True, securesystemslib.formats.PEMECDSA_SCHEMA.matches(public))
    self.assertEqual(True, securesystemslib.formats.PEMECDSA_SCHEMA.matches(private))

    # Test for invalid argument.
    self.assertRaises(securesystemslib.exceptions.FormatError,
      securesystemslib.ecdsa_keys.generate_public_and_private, 'bad_algo')

  def test_create_ecdsa_public_and_private_from_pem(self):
    global public
    global private

    # Check format of 'public' and 'private'.
    self.assertEqual(True, securesystemslib.formats.PEMECDSA_SCHEMA.matches(public))
    self.assertEqual(True, securesystemslib.formats.PEMECDSA_SCHEMA.matches(private))

    # Check for a valid private pem.
    public, private = \
      securesystemslib.ecdsa_keys.create_ecdsa_public_and_private_from_pem(private)

    # Check for an invalid pem (non-private).
    self.assertRaises(securesystemslib.exceptions.CryptoError,
      securesystemslib.ecdsa_keys.create_ecdsa_public_and_private_from_pem,
      public)

    # Test for invalid argument.
    self.assertRaises(securesystemslib.exceptions.FormatError,
      securesystemslib.ecdsa_keys.create_ecdsa_public_and_private_from_pem,
      123)

  def test_create_signature(self):
    global public
    global private
    data = b'The quick brown fox jumps over the lazy dog'
    signature, method = securesystemslib.ecdsa_keys.create_signature(public, private, data)

    # Verify format of returned values.
    self.assertEqual(True,
                     securesystemslib.formats.ECDSASIGNATURE_SCHEMA.matches(signature))

    self.assertEqual(True, securesystemslib.formats.NAME_SCHEMA.matches(method))
    self.assertEqual('ecdsa-sha2-nistp256', method)

    # Check for improperly formatted argument.
    self.assertRaises(securesystemslib.exceptions.FormatError,
                      securesystemslib.ecdsa_keys.create_signature, 123, private, data)

    self.assertRaises(securesystemslib.exceptions.FormatError,
                      securesystemslib.ecdsa_keys.create_signature, public, 123, data)

    # Check for invalid 'data'.
    self.assertRaises(securesystemslib.exceptions.CryptoError,
                      securesystemslib.ecdsa_keys.create_signature, public, private, 123)

  def test_verify_signature(self):
    global public
    global private
    data = b'The quick brown fox jumps over the lazy dog'
    signature, method = securesystemslib.ecdsa_keys.create_signature(public, private, data)

    valid_signature = securesystemslib.ecdsa_keys.verify_signature(public, method, signature, data)
    self.assertEqual(True, valid_signature)

    # Generate an RSA key so that we can verify that non-ECDSA keys are
    # rejected.
    rsa_pem, junk = securesystemslib.pycrypto_keys.generate_rsa_public_and_private()

    # Verify that a non-ECDSA key (via the PEM argument) is rejected.
    self.assertRaises(securesystemslib.exceptions.FormatError,
      securesystemslib.ecdsa_keys.verify_signature, rsa_pem, method, signature,
      data)

    # Check for improperly formatted arguments.
    self.assertRaises(securesystemslib.exceptions.FormatError, securesystemslib.ecdsa_keys.verify_signature, 123, method,
                                       signature, data)

    # Signature method improperly formatted.
    self.assertRaises(securesystemslib.exceptions.FormatError, securesystemslib.ecdsa_keys.verify_signature, public, 123,
                                       signature, data)

    # Invalid signature method.
    self.assertRaises(securesystemslib.exceptions.UnknownMethodError, securesystemslib.ecdsa_keys.verify_signature, public,
                                       'unsupported_method', signature, data)

    # Signature not a string.
    self.assertRaises(securesystemslib.exceptions.FormatError, securesystemslib.ecdsa_keys.verify_signature, public, method,
                                       123, data)

    # Invalid signature..
    self.assertRaises(securesystemslib.exceptions.FormatError, securesystemslib.ecdsa_keys.verify_signature, public, method,
                                       'bad_signature', data)

    # Check for invalid signature and data.
    # Mismatched data.
    self.assertRaises(securesystemslib.exceptions.FormatError,
      securesystemslib.ecdsa_keys.verify_signature, public, method,
      signature, '123')

    self.assertEqual(False, securesystemslib.ecdsa_keys.verify_signature(public, method,
                                                     signature, b'123'))
    # Mismatched signature.
    bad_signature = b'a'*64
    self.assertEqual(False, securesystemslib.ecdsa_keys.verify_signature(public, method,
                                                     bad_signature, data))

    # Generated signature created with different data.
    new_signature, method = securesystemslib.ecdsa_keys.create_signature(public, private,
                                                     b'mismatched data')

    self.assertEqual(False, securesystemslib.ecdsa_keys.verify_signature(public, method,
                                                     new_signature, data))

# Run the unit tests.
if __name__ == '__main__':
  unittest.main()
<commit_msg>Resolve unit tests failures in test_ecdsa_keys.py<commit_after>#!/usr/bin/env/ python

"""
<Program Name>
  test_ecdsa_keys.py

<Author>
  Vladimir Diaz <vladimir.v.diaz@gmail.com>

<Started>
  November 23, 2016.

<Copyright>
  See LICENSE for licensing information.

<Purpose>
  Test cases for test_ecdsa_keys.py.
"""

# Help with Python 3 compatibility, where the print statement is a function, an
# implicit relative import is invalid, and the '/' operator performs true
# division.  Example:  print 'hello world' raises a 'SyntaxError' exception.
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals

import unittest
import os
import logging

import securesystemslib.exceptions
import securesystemslib.formats
import securesystemslib.ecdsa_keys
import securesystemslib.pycrypto_keys

logger = logging.getLogger('securesystemslib_test_ecdsa_keys')

public, private = securesystemslib.ecdsa_keys.generate_public_and_private()
FORMAT_ERROR_MSG = 'securesystemslib.exceptions.FormatError raised.  Check object\'s format.'

class TestECDSA_keys(unittest.TestCase):
  def setUp(self):
    pass

  def test_generate_public_and_private(self):
    public, private = securesystemslib.ecdsa_keys.generate_public_and_private()

    # Check format of 'public' and 'private'.
    self.assertEqual(True, securesystemslib.formats.PEMECDSA_SCHEMA.matches(public))
    self.assertEqual(True, securesystemslib.formats.PEMECDSA_SCHEMA.matches(private))

    # Test for invalid argument.
    self.assertRaises(securesystemslib.exceptions.FormatError,
      securesystemslib.ecdsa_keys.generate_public_and_private, 'bad_algo')

  def test_create_ecdsa_public_and_private_from_pem(self):
    global public
    global private

    # Check format of 'public' and 'private'.
    self.assertEqual(True, securesystemslib.formats.PEMECDSA_SCHEMA.matches(public))
    self.assertEqual(True, securesystemslib.formats.PEMECDSA_SCHEMA.matches(private))

    # Check for a valid private pem.
    public, private = \
      securesystemslib.ecdsa_keys.create_ecdsa_public_and_private_from_pem(private)

    # Check for an invalid pem (non-private).
    self.assertRaises(securesystemslib.exceptions.CryptoError,
      securesystemslib.ecdsa_keys.create_ecdsa_public_and_private_from_pem,
      public)

    # Test for invalid argument.
    self.assertRaises(securesystemslib.exceptions.FormatError,
      securesystemslib.ecdsa_keys.create_ecdsa_public_and_private_from_pem,
      123)

  def test_create_signature(self):
    global public
    global private
    data = b'The quick brown fox jumps over the lazy dog'
    signature, method = securesystemslib.ecdsa_keys.create_signature(public, private, data)

    # Verify format of returned values.
    self.assertEqual(True,
                     securesystemslib.formats.ECDSASIGNATURE_SCHEMA.matches(signature))

    self.assertEqual(True, securesystemslib.formats.NAME_SCHEMA.matches(method))
    self.assertEqual('ecdsa-sha2-nistp256', method)

    # Check for improperly formatted argument.
    self.assertRaises(securesystemslib.exceptions.FormatError,
                      securesystemslib.ecdsa_keys.create_signature, 123, private, data)

    self.assertRaises(securesystemslib.exceptions.FormatError,
                      securesystemslib.ecdsa_keys.create_signature, public, 123, data)

    # Check for invalid 'data'.
    self.assertRaises(securesystemslib.exceptions.CryptoError,
                      securesystemslib.ecdsa_keys.create_signature, public, private, 123)

  def test_verify_signature(self):
    global public
    global private
    data = b'The quick brown fox jumps over the lazy dog'
    scheme = 'ecdsa-sha2-nistp256'
    signature, scheme = securesystemslib.ecdsa_keys.create_signature(public,
        private, data, scheme)

    valid_signature = securesystemslib.ecdsa_keys.verify_signature(public,
        scheme, signature, data)
    self.assertEqual(True, valid_signature)

    # Generate an RSA key so that we can verify that non-ECDSA keys are
    # rejected.
    rsa_pem, junk = securesystemslib.pycrypto_keys.generate_rsa_public_and_private()

    # Verify that a non-ECDSA key (via the PEM argument) is rejected.
    self.assertRaises(securesystemslib.exceptions.FormatError,
      securesystemslib.ecdsa_keys.verify_signature, rsa_pem, scheme, signature,
      data)

    # Check for improperly formatted arguments.
    self.assertRaises(securesystemslib.exceptions.FormatError,
        securesystemslib.ecdsa_keys.verify_signature, 123, scheme,
        signature, data)

    # Signature method improperly formatted.
    self.assertRaises(securesystemslib.exceptions.FormatError,
        securesystemslib.ecdsa_keys.verify_signature, public, 123,
        signature, data)

    # Invalid signature method.
    self.assertRaises(securesystemslib.exceptions.FormatError,
        securesystemslib.ecdsa_keys.verify_signature, public,
        'unsupported_scheme', signature, data)

    # Signature not a string.
    self.assertRaises(securesystemslib.exceptions.FormatError,
        securesystemslib.ecdsa_keys.verify_signature, public, scheme,
        123, data)

    # Invalid signature..
    self.assertRaises(securesystemslib.exceptions.FormatError,
        securesystemslib.ecdsa_keys.verify_signature, public, scheme,
        'bad_signature', data)

    # Check for invalid signature and data.
    # Mismatched data.
    self.assertRaises(securesystemslib.exceptions.FormatError,
      securesystemslib.ecdsa_keys.verify_signature, public, scheme,
      signature, '123')

    self.assertEqual(False, securesystemslib.ecdsa_keys.verify_signature(public,
        scheme, signature, b'123'))

    # Mismatched signature.
    bad_signature = b'a'*64
    self.assertEqual(False, securesystemslib.ecdsa_keys.verify_signature(public,
        scheme, bad_signature, data))

    # Generated signature created with different data.
    new_signature, scheme = securesystemslib.ecdsa_keys.create_signature(public,
        private, b'mismatched data')

    self.assertEqual(False, securesystemslib.ecdsa_keys.verify_signature(public,
        scheme, new_signature, data))

# Run the unit tests.
if __name__ == '__main__':
  unittest.main()
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
import unittest
import sys
from odin import exceptions

class ValidationException(unittest.TestCase):
    def test_with_string(self):
        test_message = "Test message"
        target = exceptions.ValidationError(test_message)

        self.assertListEqual([test_message], target.messages)
        self.assertFalse(hasattr(target, 'message_dict'))
        self.assertEqual("['Test message']", str(target))
        self.assertEqual("ValidationError(['Test message'])", repr(target))

    def test_with_list(self):
        test_message_list = ["Test message", "Test message 2"]
        target = exceptions.ValidationError(test_message_list)

        self.assertListEqual(test_message_list, target.messages)
        self.assertFalse(hasattr(target, 'message_dict'))
        self.assertEqual("['Test message', 'Test message 2']", str(target))
        self.assertEqual("ValidationError(['Test message', 'Test message 2'])", repr(target))

    @unittest.skipIf(sys.version_info[0] > 2 and sys.version_info[1] > 2, "Disabled as Python 3.3 randomises the hash "
                                                                          "function.")
    def test_with_dict(self):
        test_message_dict = {
            "Test Key 1": ["Test Message 1"],
            "Test Key 2": ["Test Message 2"],
        }
        target = exceptions.ValidationError(test_message_dict)

        self.assertDictEqual(test_message_dict, target.message_dict)
        self.assertListEqual([{
            "Test Key 1": ["Test Message 1"],
            "Test Key 2": ["Test Message 2"],
        }], target.messages)
        self.assertEqual("{'Test Key 2': ['Test Message 2'], 'Test Key 1': ['Test Message 1']}", str(target))
        self.assertEqual("ValidationError({'Test Key 2': ['Test Message 2'], 'Test Key 1': ['Test Message 1']})",
                         repr(target))
<commit_msg>Improved python3 tests compatibility<commit_after># -*- coding: utf-8 -*-
import unittest
from odin import exceptions

class ValidationException(unittest.TestCase):
    def test_with_string(self):
        test_message = "Test message"
        target = exceptions.ValidationError(test_message)

        self.assertListEqual([test_message], target.messages)
        self.assertFalse(hasattr(target, 'message_dict'))
        self.assertEqual("['Test message']", str(target))
        self.assertEqual("ValidationError(['Test message'])", repr(target))

    def test_with_list(self):
        test_message_list = ["Test message", "Test message 2"]
        target = exceptions.ValidationError(test_message_list)

        self.assertListEqual(test_message_list, target.messages)
        self.assertFalse(hasattr(target, 'message_dict'))
        self.assertEqual("['Test message', 'Test message 2']", str(target))
        self.assertEqual("ValidationError(['Test message', 'Test message 2'])", repr(target))

    def test_with_dict(self):
        test_message_dict = {
            "Test Key 1": ["Test Message 1"],
            "Test Key 2": ["Test Message 2"],
        }
        target = exceptions.ValidationError(test_message_dict)

        self.assertDictEqual(test_message_dict, target.message_dict)
        self.assertListEqual([{
            "Test Key 1": ["Test Message 1"],
            "Test Key 2": ["Test Message 2"],
        }], target.messages)

        expected = str({'Test Key 2': ['Test Message 2'], 'Test Key 1': ['Test Message 1']})
        self.assertEqual(expected, str(target))
        self.assertEqual("ValidationError(%s)" % expected, repr(target))
<|endoftext|>


<commit_before>from __future__ import unicode_literals

import warnings

from django.core.exceptions import ValidationError
from django.test import SimpleTestCase

from mutant.contrib.numeric.models import IntegerFieldDefinition
from mutant.contrib.text.models import CharFieldDefinition
from mutant.models.field import (
    FieldDefinition, FieldDefinitionChoice, NOT_PROVIDED,
)

from .utils import BaseModelDefinitionTestCase

class FieldDefinitionInheritanceTest(BaseModelDefinitionTestCase):
    def test_proxy_inheritance(self):
        obj = CharFieldDefinition.objects.create(
            name='caca',
            max_length=25,
            model_def=self.model_def,
        )
        save_obj = self.model_def.fielddefinitions.select_subclasses().get()
        self.assertEqual(obj, save_obj)
        Model = self.model_def.model_class()
        Model.objects.create(caca="NO WAY")

class FieldDefinitionDeclarationTest(SimpleTestCase):
    def test_delete_override(self):
        """
        Make sure a warning is raised when declaring a `FieldDefinition`
        subclass that override the `delete` method.
        """
        with self.assertRaises(TypeError):
            with warnings.catch_warnings(record=True) as catched_warnings:
                class CustomFieldDefinition(FieldDefinition):
                    def delete(self, *args, **kwargs):
                        pass

                class CustomFieldDefinitionProxy(CustomFieldDefinition):
                    class Meta:
                        proxy = True

                    def delete(self, *args, **kwargs):
                        pass

        self.assertIn('Avoid overriding the `delete` method on '
                      '`FieldDefinition` subclass `CustomFieldDefinition`',
                      catched_warnings[0].message.args[0])

def module_level_pickable_default():
    module_level_pickable_default.incr += 1
    return module_level_pickable_default.incr
module_level_pickable_default.incr = 0

class FieldDefaultTest(BaseModelDefinitionTestCase):
    def test_clean(self):
        field = IntegerFieldDefinition(name='field', model_def=self.model_def)
        # Field cleaning should work when a default value isn't provided
        field.clean()
        with self.assertRaises(ValidationError):
            field.default = 'invalid'
            field.clean()
        field.default = module_level_pickable_default
        field.clean()
        field.save()
        Model = self.model_def.model_class()
        self.assertEqual(Model.objects.create().field,
                         module_level_pickable_default.incr)
        field.default = NOT_PROVIDED
        field.save()
        with self.assertRaises(ValidationError):
            obj = Model()
            obj.field
            obj.full_clean()

    def test_create_with_default(self):
        Model = self.model_def.model_class()
        Model.objects.create()
        IntegerFieldDefinition.objects.create_with_default(1337, name='field',
                                                           model_def=self.model_def)
        before = Model.objects.get()
        self.assertEqual(before.field, 1337)
        self.assertFalse(Model().field)

class FieldDefinitionChoiceTest(BaseModelDefinitionTestCase):
    def test_simple_choices(self):
        field_def = CharFieldDefinition.objects.create(name='gender',
                                                       max_length=1,
                                                       model_def=self.model_def)
        male_choice = FieldDefinitionChoice(field_def=field_def,
                                            value='Male', label='Male')
        # Value is longer than the max_length
        self.assertRaises(ValidationError, male_choice.clean)
        # A length of 1 should work
        male_choice.value = 'M'
        male_choice.full_clean()
        male_choice.save()
        # Cleaning should raise validation error when passed invalid choice
        Model = self.model_def.model_class()
        obj = Model(gender='T')
        self.assertRaises(ValidationError, obj.full_clean)
        # Create another allowed choice
        female_choice = FieldDefinitionChoice(field_def=field_def,
                                              value='F', label='Female')
        female_choice.value = 'F'
        female_choice.full_clean()
        female_choice.save()
        # It should now be possible to create valid objects with this choice
        obj = Model(gender='F')
        obj.full_clean()
        # Make sure choices are correctly set
        choices = Model._meta.get_field('gender').get_choices(include_blank=False)
        self.assertEqual(choices, [('M', 'Male'), ('F', 'Female')])

    def test_grouped_choices(self):
        field_def = CharFieldDefinition.objects.create(name='media',
                                                       max_length=5,
                                                       model_def=self.model_def)
        # Create Audio choices
        FieldDefinitionChoice.objects.create(field_def=field_def, group='Audio',
                                             value='vinyl', label='Vinyl')
        FieldDefinitionChoice.objects.create(field_def=field_def, group='Audio',
                                             value='cd', label='CD')
        # Create Video choices
        FieldDefinitionChoice.objects.create(field_def=field_def, group='Video',
                                             value='vhs', label='VHS Tape')
        FieldDefinitionChoice.objects.create(field_def=field_def, group='Video',
                                             value='dvd', label='DVD')
        # Create Unknown choices
        FieldDefinitionChoice.objects.create(field_def=field_def,
                                             value='unknown', label='Unknown')
        # Make sure choices are correctly created
        Model = self.model_def.model_class()
        choices = Model._meta.get_field('media').get_choices(include_blank=False)
        expected_choices = [
            ('Audio', (
                ('vinyl', 'Vinyl'),
                ('cd', 'CD'),
            )),
            ('Video', (
                ('vhs', 'VHS Tape'),
                ('dvd', 'DVD'),
            )),
            ('unknown', 'Unknown')
        ]
        self.assertEqual(choices, expected_choices)

class FieldDefinitionManagerTest(BaseModelDefinitionTestCase):
    def test_natural_key(self):
        fd = CharFieldDefinition.objects.create(name='name', max_length=5,
                                                model_def=self.model_def)
        natural_key = fd.natural_key()
        self.assertEqual(
            FieldDefinition.objects.get_by_natural_key(*natural_key), fd
        )
<commit_msg>Added explicit app labels to test models.<commit_after>from __future__ import unicode_literals

import warnings

from django.core.exceptions import ValidationError
from django.test import SimpleTestCase

from mutant.contrib.numeric.models import IntegerFieldDefinition
from mutant.contrib.text.models import CharFieldDefinition
from mutant.models.field import (
    FieldDefinition, FieldDefinitionChoice, NOT_PROVIDED,
)

from .utils import BaseModelDefinitionTestCase

class FieldDefinitionInheritanceTest(BaseModelDefinitionTestCase):
    def test_proxy_inheritance(self):
        obj = CharFieldDefinition.objects.create(
            name='caca',
            max_length=25,
            model_def=self.model_def,
        )
        save_obj = self.model_def.fielddefinitions.select_subclasses().get()
        self.assertEqual(obj, save_obj)
        Model = self.model_def.model_class()
        Model.objects.create(caca="NO WAY")

class FieldDefinitionDeclarationTest(SimpleTestCase):
    def test_delete_override(self):
        """
        Make sure a warning is raised when declaring a `FieldDefinition`
        subclass that override the `delete` method.
        """
        with self.assertRaises(TypeError):
            with warnings.catch_warnings(record=True) as catched_warnings:
                class CustomFieldDefinition(FieldDefinition):
                    class Meta:
                        app_label = 'mutant'

                    def delete(self, *args, **kwargs):
                        pass

                class CustomFieldDefinitionProxy(CustomFieldDefinition):
                    class Meta:
                        app_label = 'mutant'
                        proxy = True

                    def delete(self, *args, **kwargs):
                        pass

        self.assertIn('Avoid overriding the `delete` method on '
                      '`FieldDefinition` subclass `CustomFieldDefinition`',
                      catched_warnings[0].message.args[0])

def module_level_pickable_default():
    module_level_pickable_default.incr += 1
    return module_level_pickable_default.incr
module_level_pickable_default.incr = 0

class FieldDefaultTest(BaseModelDefinitionTestCase):
    def test_clean(self):
        field = IntegerFieldDefinition(name='field', model_def=self.model_def)
        # Field cleaning should work when a default value isn't provided
        field.clean()
        with self.assertRaises(ValidationError):
            field.default = 'invalid'
            field.clean()
        field.default = module_level_pickable_default
        field.clean()
        field.save()
        Model = self.model_def.model_class()
        self.assertEqual(Model.objects.create().field,
                         module_level_pickable_default.incr)
        field.default = NOT_PROVIDED
        field.save()
        with self.assertRaises(ValidationError):
            obj = Model()
            obj.field
            obj.full_clean()

    def test_create_with_default(self):
        Model = self.model_def.model_class()
        Model.objects.create()
        IntegerFieldDefinition.objects.create_with_default(1337, name='field',
                                                           model_def=self.model_def)
        before = Model.objects.get()
        self.assertEqual(before.field, 1337)
        self.assertFalse(Model().field)

class FieldDefinitionChoiceTest(BaseModelDefinitionTestCase):
    def test_simple_choices(self):
        field_def = CharFieldDefinition.objects.create(name='gender',
                                                       max_length=1,
                                                       model_def=self.model_def)
        male_choice = FieldDefinitionChoice(field_def=field_def,
                                            value='Male', label='Male')
        # Value is longer than the max_length
        self.assertRaises(ValidationError, male_choice.clean)
        # A length of 1 should work
        male_choice.value = 'M'
        male_choice.full_clean()
        male_choice.save()
        # Cleaning should raise validation error when passed invalid choice
        Model = self.model_def.model_class()
        obj = Model(gender='T')
        self.assertRaises(ValidationError, obj.full_clean)
        # Create another allowed choice
        female_choice = FieldDefinitionChoice(field_def=field_def,
                                              value='F', label='Female')
        female_choice.value = 'F'
        female_choice.full_clean()
        female_choice.save()
        # It should now be possible to create valid objects with this choice
        obj = Model(gender='F')
        obj.full_clean()
        # Make sure choices are correctly set
        choices = Model._meta.get_field('gender').get_choices(include_blank=False)
        self.assertEqual(choices, [('M', 'Male'), ('F', 'Female')])

    def test_grouped_choices(self):
        field_def = CharFieldDefinition.objects.create(name='media',
                                                       max_length=5,
                                                       model_def=self.model_def)
        # Create Audio choices
        FieldDefinitionChoice.objects.create(field_def=field_def, group='Audio',
                                             value='vinyl', label='Vinyl')
        FieldDefinitionChoice.objects.create(field_def=field_def, group='Audio',
                                             value='cd', label='CD')
        # Create Video choices
        FieldDefinitionChoice.objects.create(field_def=field_def, group='Video',
                                             value='vhs', label='VHS Tape')
        FieldDefinitionChoice.objects.create(field_def=field_def, group='Video',
                                             value='dvd', label='DVD')
        # Create Unknown choices
        FieldDefinitionChoice.objects.create(field_def=field_def,
                                             value='unknown', label='Unknown')
        # Make sure choices are correctly created
        Model = self.model_def.model_class()
        choices = Model._meta.get_field('media').get_choices(include_blank=False)
        expected_choices = [
            ('Audio', (
                ('vinyl', 'Vinyl'),
                ('cd', 'CD'),
            )),
            ('Video', (
                ('vhs', 'VHS Tape'),
                ('dvd', 'DVD'),
            )),
            ('unknown', 'Unknown')
        ]
        self.assertEqual(choices, expected_choices)

class FieldDefinitionManagerTest(BaseModelDefinitionTestCase):
    def test_natural_key(self):
        fd = CharFieldDefinition.objects.create(name='name', max_length=5,
                                                model_def=self.model_def)
        natural_key = fd.natural_key()
        self.assertEqual(
            FieldDefinition.objects.get_by_natural_key(*natural_key), fd
        )
<|endoftext|>


<commit_before>from src.filesystem import FileSystem

class TestFileSystem(object):
    def setup_method(self):
        self.fs = FileSystem()

    def test_find_scans_directory(self):
        result = self.fs.find('src/')
        result = {repr(ref) for ref in result}

        assert result == {
            'src/__init__.py',
            'src/filesystem.py',
            'src/reflection.py'
        }

    def test_find_can_filter_by_file_name(self):
        result = self.fs.find('src/', 'filesystem.py')
        result = {repr(ref) for ref in result}

        assert result == {
            'src/filesystem.py',
        }
<commit_msg>add src/lcom.py to expected<commit_after>from src.filesystem import FileSystem

class TestFileSystem(object):
    def setup_method(self):
        self.fs = FileSystem()

    def test_find_scans_directory(self):
        result = self.fs.find('src/')
        result = {repr(ref) for ref in result}

        assert result == {
            'src/__init__.py',
            'src/filesystem.py',
            'src/lcom.py',
            'src/reflection.py'
        }

    def test_find_can_filter_by_file_name(self):
        result = self.fs.find('src/', 'filesystem.py')
        result = {repr(ref) for ref in result}

        assert result == {
            'src/filesystem.py',
        }
<|endoftext|>