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

from unittest import mock

from rally.common.io import junit
from tests.unit import test


class JUnitTestCase(test.TestCase):
    def setUp(self):
        super().setUp()
        p_mock_datetime = mock.patch("rally.common.io.junit.dt.datetime")
        self.mock_datetime = p_mock_datetime.start()
        isoformat = self.mock_datetime.utcnow.return_value.isoformat
        isoformat.return_value = "TIME"
        self.addCleanup(p_mock_datetime.stop)

        p_mock_version = mock.patch("rally.common.version.version_string",
                                    return_value="VERSION")
        self.mock_version = p_mock_version.start()
        self.addCleanup(p_mock_version.stop)

    def test_basic_testsuite(self):
        j = junit.JUnitXML()
        test_suite = j.add_test_suite("uuid1", time="58.51", timestamp="3")
        test_suite.add_test_case(classname="Foo", name="Bar", time="3.14")
        t = test_suite.add_test_case(classname="Foo", name="Baz", time="13.37")
        t.mark_as_failed("fail_message")

        expected = """<testsuites>
  <!--Report is generated by Rally VERSION at TIME-->
  <testsuite errors="0" failures="1" id="uuid1" skipped="0" tests="2" time="58.51" timestamp="3">
    <testcase classname="Foo" name="Bar" time="3.14" />
    <testcase classname="Foo" name="Baz" time="13.37">
      <failure>fail_message</failure>
    </testcase>
  </testsuite>
</testsuites>
"""  # noqa: E501
        self.assertEqual(expected, j.to_string())

    def test_empty_testsuite(self):
        j = junit.JUnitXML()
        expected = """<testsuites>
  <!--Report is generated by Rally VERSION at TIME-->
</testsuites>
"""
        self.assertEqual(expected, str(j))
