<commit_before>##########################################################################
#
#  Copyright (c) 2013, Image Engine Design Inc. All rights reserved.
#
#  Redistribution and use in source and binary forms, with or without
#  modification, are permitted provided that the following conditions are
#  met:
#
#      * Redistributions of source code must retain the above
#        copyright notice, this list of conditions and the following
#        disclaimer.
#
#      * Redistributions in binary form must reproduce the above
#        copyright notice, this list of conditions and the following
#        disclaimer in the documentation and/or other materials provided with
#        the distribution.
#
#      * Neither the name of John Haddon nor the names of
#        any other contributors to this software may be used to endorse or
#        promote products derived from this software without specific prior
#        written permission.
#
#  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
#  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
#  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
#  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
#  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
#  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
#  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
#  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
#  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
#  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
#  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
##########################################################################

import IECore

import Gaffer
import GafferUI
import GafferImageUI

##########################################################################
# _TogglePlugValueWidget
##########################################################################

# Toggles between default value and the last non-default value
class _TogglePlugValueWidget( GafferUI.PlugValueWidget ) :

	def __init__( self, plug, **kw ) :

		row = GafferUI.ListContainer( GafferUI.ListContainer.Orientation.Horizontal, spacing = 2 )

		GafferUI.PlugValueWidget.__init__( self, row, plug, **kw )

		self.__imagePrefix = Gaffer.Metadata.plugValue( plug, "togglePlugValueWidget:imagePrefix" )
		with row :

			self.__button = GafferUI.Button( "", self.__imagePrefix + "Off.png", hasFrame=False )
			self.__clickedConnection = self.__button.clickedSignal().connect( Gaffer.WeakMethod( self.__clicked ) )

			if not isinstance( plug, Gaffer.BoolPlug ) :
				plugValueWidget = GafferUI.PlugValueWidget.create( plug, useTypeOnly=True )
				plugValueWidget.numericWidget().setFixedCharacterWidth( 5 )

		self.__toggleValue = Gaffer.Metadata.plugValue( plug, "togglePlugValueWidget:defaultToggleValue" )
		self._updateFromPlug()

	def hasLabel( self ) :

		return True

	def getToolTip( self ) :

		result = GafferUI.PlugValueWidget.getToolTip( self )

		result += "
"
		result += "
Click to toggle to/from default value
"
		result += "
"

		return result

	def _updateFromPlug( self ) :

		with self.getContext() :
			value = self.getPlug().getValue()

		if value != self.getPlug().defaultValue() :
			self.__toggleValue = value
			self.__button.setImage( self.__imagePrefix + "On.png" )
		else :
			self.__button.setImage( self.__imagePrefix + "Off.png" )

		self.setEnabled( self.getPlug().settable() )

	def __clicked( self, button ) :

		with self.getContext() :
			value = self.getPlug().getValue()

		if value == self.getPlug().defaultValue() and self.__toggleValue is not None :
			self.getPlug().setValue( self.__toggleValue )
		else :
			self.getPlug().setToDefault()

##########################################################################
# _DisplayTransformPlugValueWidget
##########################################################################

class _DisplayTransformPlugValueWidget( GafferUI.PresetsPlugValueWidget ) :

	def __init__( self, plug, **kw ) :

		GafferUI.PresetsPlugValueWidget.__init__( self, plug, **kw )

		## \todo Perhaps the layout could do this sort of thing for us
		# based on a metadata value?
		self._qtWidget().setFixedWidth( 100 )

##########################################################################
# _ColorInspectorPlugValueWidget
##########################################################################

class _ColorInspectorPlugValueWidget( GafferUI.PlugValueWidget ) :

	def __init__( self, plug, **kw ) :

		frame = GafferUI.Frame( borderWidth = 4 )
		frame._qtWidget().setObjectName( "gafferDarker" )

		GafferUI.PlugValueWidget.__init__( self, frame, plug, **kw )

		with frame :

			with GafferUI.ListContainer( GafferUI.ListContainer.Orientation.Horizontal, spacing = 4 ) :

				self.__positionLabel = GafferUI.Label()
				self.__positionLabel._qtWidget().setFixedWidth( 90 )

				self.__swatch = GafferUI.ColorSwatch()
				self.__swatch._qtWidget().setFixedWidth( 12 )
				self.__swatch._qtWidget().setFixedHeight( 12 )

				self.__rgbLabel = GafferUI.Label()

				GafferUI.Spacer( IECore.V2i( 20, 10 ), IECore.V2i( 20, 10 ) )

				self.__hsvLabel = GafferUI.Label()

	def _updateFromPlug( self ) :

		view = self.getPlug().node()

		## \todo We're getting the context from the view because our
		# own context hasn't been set properly. We need to fix that
		# properly, I think by having some sort of ContextSensitiveWidget
		# base class which inherits contexts from parents.
		with view.getContext() :
			channelNames = view.viewportGadget().getPrimaryChild().getImage()["channelNames"].getValue()
			pixel = self.getPlug()["pixel"].getValue()
			color = self.getPlug()["color"].getValue()

		if "A" not in channelNames :
			color = IECore.Color3f( color[0], color[1], color[2] )

		self.__positionLabel.setText( "XY : %d %d" % ( pixel.x, pixel.y ) )
		self.__swatch.setColor( color )

		if isinstance( color, IECore.Color4f ) :
			self.__rgbLabel.setText( "RGBA : %.3f %.3f %.3f %.3f" % ( color.r, color.g, color.b, color.a ) )
		else :
			self.__rgbLabel.setText( "RGB : %.3f %.3f %.3f" % ( color.r, color.g, color.b ) )

		hsv = color.rgbToHSV()
		self.__hsvLabel.setText( "HSV : %.3f %.3f %.3f" % ( hsv.r, hsv.g, hsv.b ) )

##########################################################################
# Metadata registration.
##########################################################################

Gaffer.Metadata.registerNode(

	GafferImageUI.ImageView,

	"nodeToolbar:bottom:type", "GafferUI.StandardNodeToolbar.bottom",

	plugs = {

		"clipping" : [

			"description",
			"""
			Highlights the regions in which the colour values go above 1 or below 0.
			""",

			"plugValueWidget:type", "GafferImageUI.ImageViewToolbar._TogglePlugValueWidget",
			"togglePlugValueWidget:imagePrefix", "clipping",
			"togglePlugValueWidget:defaultToggleValue", True,
			"toolbarLayout:divider", True,

		],

		"exposure" : [

			"description",
			"""
			Applies an exposure adjustment to the image.
			""",

			"plugValueWidget:type", "GafferImageUI.ImageViewToolbar._TogglePlugValueWidget",
			"togglePlugValueWidget:imagePrefix", "exposure",
			"togglePlugValueWidget:defaultToggleValue", 1,

		],

		"gamma" : [

			"description",
			"""
			Applies a gamma correction to the image.
			""",

			"plugValueWidget:type", "GafferImageUI.ImageViewToolbar._TogglePlugValueWidget",
			"togglePlugValueWidget:imagePrefix", "gamma",
			"togglePlugValueWidget:defaultToggleValue", 2,

		],

		"displayTransform" : [

			"description",
			"""
			Applies colour space transformations for viewing the image correctly.
			""",

			"plugValueWidget:type", "GafferImageUI.ImageViewToolbar._DisplayTransformPlugValueWidget",
			"label", "",

			"presetNames", lambda plug : IECore.StringVectorData( GafferImageUI.ImageView.registeredDisplayTransforms() ),
			"presetValues", lambda plug : IECore.StringVectorData( GafferImageUI.ImageView.registeredDisplayTransforms() ),

		],

		"colorInspector" : [

			"plugValueWidget:type", "GafferImageUI.ImageViewToolbar._ColorInspectorPlugValueWidget",
			"label", "",
			"toolbarLayout:section", "Bottom",

		],

	}

)
<commit_msg>ImageViewToolbar : Handle computation errors.<commit_after>##########################################################################
#
#  Copyright (c) 2013, Image Engine Design Inc. All rights reserved.
#
#  Redistribution and use in source and binary forms, with or without
#  modification, are permitted provided that the following conditions are
#  met:
#
#      * Redistributions of source code must retain the above
#        copyright notice, this list of conditions and the following
#        disclaimer.
#
#      * Redistributions in binary form must reproduce the above
#        copyright notice, this list of conditions and the following
#        disclaimer in the documentation and/or other materials provided with
#        the distribution.
#
#      * Neither the name of John Haddon nor the names of
#        any other contributors to this software may be used to endorse or
#        promote products derived from this software without specific prior
#        written permission.
#
#  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
#  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
#  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
#  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
#  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
#  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
#  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
#  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
#  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
#  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
#  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
##########################################################################

import IECore

import Gaffer
import GafferUI
import GafferImageUI

##########################################################################
# _TogglePlugValueWidget
##########################################################################

# Toggles between default value and the last non-default value
class _TogglePlugValueWidget( GafferUI.PlugValueWidget ) :

	def __init__( self, plug, **kw ) :

		row = GafferUI.ListContainer( GafferUI.ListContainer.Orientation.Horizontal, spacing = 2 )

		GafferUI.PlugValueWidget.__init__( self, row, plug, **kw )

		self.__imagePrefix = Gaffer.Metadata.plugValue( plug, "togglePlugValueWidget:imagePrefix" )
		with row :

			self.__button = GafferUI.Button( "", self.__imagePrefix + "Off.png", hasFrame=False )
			self.__clickedConnection = self.__button.clickedSignal().connect( Gaffer.WeakMethod( self.__clicked ) )

			if not isinstance( plug, Gaffer.BoolPlug ) :
				plugValueWidget = GafferUI.PlugValueWidget.create( plug, useTypeOnly=True )
				plugValueWidget.numericWidget().setFixedCharacterWidth( 5 )

		self.__toggleValue = Gaffer.Metadata.plugValue( plug, "togglePlugValueWidget:defaultToggleValue" )
		self._updateFromPlug()

	def hasLabel( self ) :

		return True

	def getToolTip( self ) :

		result = GafferUI.PlugValueWidget.getToolTip( self )

		result += "
"
		result += "
Click to toggle to/from default value
"
		result += "
"

		return result

	def _updateFromPlug( self ) :

		with self.getContext() :
			value = self.getPlug().getValue()

		if value != self.getPlug().defaultValue() :
			self.__toggleValue = value
			self.__button.setImage( self.__imagePrefix + "On.png" )
		else :
			self.__button.setImage( self.__imagePrefix + "Off.png" )

		self.setEnabled( self.getPlug().settable() )

	def __clicked( self, button ) :

		with self.getContext() :
			value = self.getPlug().getValue()

		if value == self.getPlug().defaultValue() and self.__toggleValue is not None :
			self.getPlug().setValue( self.__toggleValue )
		else :
			self.getPlug().setToDefault()

##########################################################################
# _DisplayTransformPlugValueWidget
##########################################################################

class _DisplayTransformPlugValueWidget( GafferUI.PresetsPlugValueWidget ) :

	def __init__( self, plug, **kw ) :

		GafferUI.PresetsPlugValueWidget.__init__( self, plug, **kw )

		## \todo Perhaps the layout could do this sort of thing for us
		# based on a metadata value?
		self._qtWidget().setFixedWidth( 100 )

##########################################################################
# _ColorInspectorPlugValueWidget
##########################################################################

class _ColorInspectorPlugValueWidget( GafferUI.PlugValueWidget ) :

	def __init__( self, plug, **kw ) :

		frame = GafferUI.Frame( borderWidth = 4 )
		frame._qtWidget().setObjectName( "gafferDarker" )

		GafferUI.PlugValueWidget.__init__( self, frame, plug, **kw )

		with frame :

			with GafferUI.ListContainer( GafferUI.ListContainer.Orientation.Horizontal, spacing = 4 ) :

				self.__positionLabel = GafferUI.Label()
				self.__positionLabel._qtWidget().setFixedWidth( 90 )

				self.__swatch = GafferUI.ColorSwatch()
				self.__swatch._qtWidget().setFixedWidth( 12 )
				self.__swatch._qtWidget().setFixedHeight( 12 )

				self.__rgbLabel = GafferUI.Label()

				GafferUI.Spacer( IECore.V2i( 20, 10 ), IECore.V2i( 20, 10 ) )

				self.__hsvLabel = GafferUI.Label()

	def _updateFromPlug( self ) :

		view = self.getPlug().node()

		## \todo We're getting the context from the view because our
		# own context hasn't been set properly. We need to fix that
		# properly, I think by having some sort of ContextSensitiveWidget
		# base class which inherits contexts from parents.
		with view.getContext() :
			pixel = self.getPlug()["pixel"].getValue()
			try :
				channelNames = view.viewportGadget().getPrimaryChild().getImage()["channelNames"].getValue()
				color = self.getPlug()["color"].getValue()
			except :
				channelNames = view.viewportGadget().getPrimaryChild().getImage()["channelNames"].defaultValue()
				color = self.getPlug()["color"].defaultValue()

		if "A" not in channelNames :
			color = IECore.Color3f( color[0], color[1], color[2] )

		self.__positionLabel.setText( "XY : %d %d" % ( pixel.x, pixel.y ) )
		self.__swatch.setColor( color )

		if isinstance( color, IECore.Color4f ) :
			self.__rgbLabel.setText( "RGBA : %.3f %.3f %.3f %.3f" % ( color.r, color.g, color.b, color.a ) )
		else :
			self.__rgbLabel.setText( "RGB : %.3f %.3f %.3f" % ( color.r, color.g, color.b ) )

		hsv = color.rgbToHSV()
		self.__hsvLabel.setText( "HSV : %.3f %.3f %.3f" % ( hsv.r, hsv.g, hsv.b ) )

##########################################################################
# Metadata registration.
##########################################################################

Gaffer.Metadata.registerNode(

	GafferImageUI.ImageView,

	"nodeToolbar:bottom:type", "GafferUI.StandardNodeToolbar.bottom",

	plugs = {

		"clipping" : [

			"description",
			"""
			Highlights the regions in which the colour values go above 1 or below 0.
			""",

			"plugValueWidget:type", "GafferImageUI.ImageViewToolbar._TogglePlugValueWidget",
			"togglePlugValueWidget:imagePrefix", "clipping",
			"togglePlugValueWidget:defaultToggleValue", True,
			"toolbarLayout:divider", True,

		],

		"exposure" : [

			"description",
			"""
			Applies an exposure adjustment to the image.
			""",

			"plugValueWidget:type", "GafferImageUI.ImageViewToolbar._TogglePlugValueWidget",
			"togglePlugValueWidget:imagePrefix", "exposure",
			"togglePlugValueWidget:defaultToggleValue", 1,

		],

		"gamma" : [

			"description",
			"""
			Applies a gamma correction to the image.
			""",

			"plugValueWidget:type", "GafferImageUI.ImageViewToolbar._TogglePlugValueWidget",
			"togglePlugValueWidget:imagePrefix", "gamma",
			"togglePlugValueWidget:defaultToggleValue", 2,

		],

		"displayTransform" : [

			"description",
			"""
			Applies colour space transformations for viewing the image correctly.
			""",

			"plugValueWidget:type", "GafferImageUI.ImageViewToolbar._DisplayTransformPlugValueWidget",
			"label", "",

			"presetNames", lambda plug : IECore.StringVectorData( GafferImageUI.ImageView.registeredDisplayTransforms() ),
			"presetValues", lambda plug : IECore.StringVectorData( GafferImageUI.ImageView.registeredDisplayTransforms() ),

		],

		"colorInspector" : [

			"plugValueWidget:type", "GafferImageUI.ImageViewToolbar._ColorInspectorPlugValueWidget",
			"label", "",
			"toolbarLayout:section", "Bottom",

		],

	}

)
<|endoftext|>


<commit_before>import unittest
from robot import utils
from robot.result.keyword import Keyword
from robot.model.message import Message
from robot.output.loggerhelper import LEVELS
from robot.reporting.parsingcontext import Context
from robot.result.datamodel import DatamodelVisitor
from robot.result.jsondatamodelhandlers import _Handler, KeywordHandler, _StatusHandler
from robot.result.testcase import TestCase
from robot.result.testsuite import TestSuite
from robot.utils.asserts import assert_equals

class TestJsoning(unittest.TestCase, DatamodelVisitor):

    def setUp(self):
        self._elements = []
        self._context = Context()
        self._elements.append(_Handler(self._context))

    def test_html_message_to_json(self):
        message = Message(message='Great danger!',
                          level='WARN',
                          html=True,
                          timestamp='20121212 12:12:12.121')
        message.visit(self)
        self._verify_message(self.datamodel[0], message)

    def _verify_message(self, message_json, message):
        assert_equals(message_json[0], self._context.timestamp(message.timestamp))
        assert_equals(message_json[1], LEVELS[message.level])
        message_text = message.message
        if not message.html:
            message_text = utils.html_escape(message_text)
        self._assert_text(message_json[2], message_text)

    def _assert_text(self, text_index, text):
        assert_equals(text_index, self._context.get_id(text))

    def test_non_html_message_to_json(self):
        message = Message(message='This is an html mark --> ',
                          level='INFO',
                          timestamp='19991211 12:12:12.821')
        message.visit(self)
        self._verify_message(self.datamodel[0], message)

    def test_times(self):
        for timestamp in ['20110531 12:48:09.020','N/A','20110531 12:48:09.010','20110531 12:48:19.035']:
            Message(timestamp=timestamp).visit(self)
        for index, millis in enumerate([0, None, -10, 10015]):
            assert_equals(self.datamodel[index][0], millis)

    def test_keyword_jsoning(self):
        self._context.start_suite()
        keyword = Keyword(name='Keyword Name',
                          doc='Documentation for a keyword',
                          args=['${first}', '${second}', '${third}'],
                          type='setup',
                          timeout='2 seconds',
                          status='PASS',
                          starttime='20110101 16:16:16.100',
                          endtime='20110101 16:16:18.161')
        keyword.messages.create(message='keyword message',
                                level='INFO',
                                timestamp='20110101 16:16:16.161')
        keyword.keywords.create(name='No Operation',
                                type='kw',
                                status='PASS')
        keyword.visit(self)
        self._verify_keyword(self.datamodel[0], keyword)

    def _verify_keyword(self, keyword_json, keyword):
        assert_equals(keyword_json[0], KeywordHandler._types[keyword.type])
        self._assert_texts(keyword_json, {1:keyword.name,
                                          2:keyword.timeout,
                                          4: ', '.join(keyword.args)})
        self._assert_html_text(keyword_json[3], keyword.doc)
        assert_equals(keyword_json[-3][0], _StatusHandler._statuses[keyword.status])
        assert_equals(keyword_json[-3][1], self._millis(keyword.starttime))
        self._verify_elapsed(keyword_json[-3][2], keyword)
        for index, message in enumerate(keyword.messages):
            self._verify_message(keyword_json[-1][index], message)
        self._for_each_verify(keyword_json[-2], keyword.keywords, self._verify_keyword)

    def _millis(self, timestamp):
        return self._context.timestamp(timestamp)

    def _assert_html_text(self, text_index, text):
        self._assert_text(text_index, utils.html_escape(text))

    def test_testcase_jsoning(self):
        self._context.start_suite()
        test = TestCase(name='Foo Bar', doc='Test
case
 doc', tags=['foo', 'bar'],
                        timeout='35 years',
                        status='FAIL',
                        message='iz failz!',
                        starttime='20000101 01:00:00.000',
                        endtime='20350101 01:00:00.001')
        parent = lambda:0
        parent.critical = parent
        parent.test_is_critical = lambda *args: True
        test.parent = parent
        test.keywords.create(name=':FOR ${i} IN RANGE 123', type='for',
                             status='FAIL',
                             starttime='20000101 01:00:01.001',
                             endtime='20350101 01:00:00.001').\
                        keywords.create(type='foritem', status='FAIL',
                                        starttime='20000101 01:00:00.999',
                                        endtime='20350101 01:00:00.001').\
                        keywords.create(type='kw', name='Sleep forever',
                                        status='FAIL',
                                        starttime='20000101 01:00:01.000',
                                        endtime='20350101 01:00:00.001')
        test.visit(self)
        self._verify_test(self.datamodel[0], test)

    def _verify_test(self, test_json, test):
        self._assert_texts(test_json, {0:test.name,
                                       1:test.timeout})
        self._assert_html_text(test_json[3], test.doc)
        assert_equals(test_json[2], int(test.critical == 'yes'))
        self._verify_tags(test_json[4], test.tags)
        self._assert_text(test_json[5][0], _StatusHandler._statuses[test.status])
        assert_equals(test_json[5][1], self._millis(test.starttime))
        self._verify_elapsed(test_json[5][2], test)
        if test.message != '':
            self._assert_text(test_json[5][3], test.message)
        self._for_each_verify(test_json[6], test.keywords, self._verify_keyword)

    def _assert_texts(self, datamodel, index_to_text):
        for index in index_to_text:
            self._assert_text(datamodel[index], index_to_text[index])

    def _verify_tags(self, tags_json, tags):
        assert_equals(len(tags_json), len(tags))
        for tag_json, tag in zip(tags_json, tags):
            self._assert_text(tag_json, tag)

    def test_suite_jsoning(self):
        suite = TestSuite(source='../somewhere',
                          name='Somewhere',
                          doc='suite documentation',
                          metadata={'key<':'value<!>',
                                    'key2>':'va>lue2'})
        suite.starttime = '20000101 02:23:01.821'
        suite.endtime   = '20011221 11:31:12.371'
        suite.message   = 'so long and thank you for all the fish!'
        suite.keywords.create(type='setup')
        subsuite = suite.suites.create(name='subsuite')
        subsuite.tests.create(name='test', status='PASS')
        suite.keywords.create(type='teardown')
        suite.visit(self)
        self._verify_suite(self.datamodel[0], suite)

    def _verify_suite(self, suite_json, suite):
        self._assert_text(suite_json[0], suite.name)
        self._assert_text(suite_json[1], suite.source)
        self._assert_text(suite_json[2], '')
        self._assert_html_text(suite_json[3], suite.doc)
        self._verify_metadata(suite_json[4], suite.metadata)
        assert_equals(suite_json[5][0], _StatusHandler._statuses[suite.status])
        assert_equals(suite_json[5][1], self._millis(suite.starttime))
        self._verify_elapsed(suite_json[5][2], suite)
        if suite.message != '':
            self._assert_text(suite_json[5][3], suite.message)
        self._for_each_verify(suite_json[6], suite.suites, self._verify_suite)
        self._for_each_verify(suite_json[7], suite.tests, self._verify_test)
        self._for_each_verify(suite_json[8], suite.keywords, self._verify_keyword)

    def _for_each_verify(self, json, item_list, method):
        for index, subitem in enumerate(item_list):
            method(json[index], subitem)
        assert_equals(len(json), len(item_list))

    def _verify_elapsed(self, elapsed, item):
        if item.starttime != 'N/A':
            assert_equals(elapsed, self._millis(item.endtime)-self._millis(item.starttime))
        else:
            assert_equals(elapsed, 0)

    def _verify_metadata(self, metadata_json, metadata):
        expected = []
        for k,v in metadata.items():
            expected += [k,utils.html_escape(v)]
        for index, value in enumerate(expected):
            self._assert_text(metadata_json[index], value)

    def test_execution_result_jsoning(self):
        pass

if __name__ == '__main__':
    unittest.main()
<commit_msg>Automated merge with https://code.google.com/p/robotframework/<commit_after>import unittest
from robot import utils
from robot.result.executionresult import ExecutionResult
from robot.result.keyword import Keyword
from robot.model.message import Message
from robot.output.loggerhelper import LEVELS
from robot.reporting.parsingcontext import Context
from robot.result.datamodel import DatamodelVisitor
from robot.result.jsondatamodelhandlers import _Handler, KeywordHandler, _StatusHandler, ExecutionResultHandler
from robot.result.testcase import TestCase
from robot.result.testsuite import TestSuite
from robot.utils.asserts import assert_equals

class TestJsoning(unittest.TestCase, DatamodelVisitor):

    def setUp(self):
        self._elements = []
        self._context = Context()
        self._elements.append(_Handler(self._context))

    def test_html_message_to_json(self):
        message = Message(message='Great danger!',
                          level='WARN',
                          html=True,
                          timestamp='20121212 12:12:12.121')
        message.visit(self)
        self._verify_message(self.datamodel[0], message)

    def _verify_message(self, message_json, message):
        assert_equals(message_json[0], self._context.timestamp(message.timestamp))
        assert_equals(message_json[1], LEVELS[message.level])
        message_text = message.message
        if not message.html:
            message_text = utils.html_escape(message_text)
        self._assert_text(message_json[2], message_text)

    def _assert_text(self, text_index, text):
        assert_equals(text_index, self._context.get_id(text))

    def test_non_html_message_to_json(self):
        message = Message(message='This is an html mark --> ',
                          level='INFO',
                          timestamp='19991211 12:12:12.821')
        message.visit(self)
        self._verify_message(self.datamodel[0], message)

    def test_times(self):
        for timestamp in ['20110531 12:48:09.020','N/A','20110531 12:48:09.010','20110531 12:48:19.035']:
            Message(timestamp=timestamp).visit(self)
        for index, millis in enumerate([0, None, -10, 10015]):
            assert_equals(self.datamodel[index][0], millis)

    def test_keyword_jsoning(self):
        self._context.start_suite()
        keyword = Keyword(name='Keyword Name',
                          doc='Documentation for a keyword',
                          args=['${first}', '${second}', '${third}'],
                          type='setup',
                          timeout='2 seconds',
                          status='PASS',
                          starttime='20110101 16:16:16.100',
                          endtime='20110101 16:16:18.161')
        keyword.messages.create(message='keyword message',
                                level='INFO',
                                timestamp='20110101 16:16:16.161')
        keyword.keywords.create(name='No Operation',
                                type='kw',
                                status='PASS')
        keyword.visit(self)
        self._verify_keyword(self.datamodel[0], keyword)

    def _verify_keyword(self, keyword_json, keyword):
        assert_equals(keyword_json[0], KeywordHandler._types[keyword.type])
        self._assert_texts(keyword_json, {1:keyword.name,
                                          2:keyword.timeout,
                                          4: ', '.join(keyword.args)})
        self._assert_html_text(keyword_json[3], keyword.doc)
        assert_equals(keyword_json[-3][0], _StatusHandler._statuses[keyword.status])
        assert_equals(keyword_json[-3][1], self._millis(keyword.starttime))
        self._verify_elapsed(keyword_json[-3][2], keyword)
        for index, message in enumerate(keyword.messages):
            self._verify_message(keyword_json[-1][index], message)
        self._for_each_verify(keyword_json[-2], keyword.keywords, self._verify_keyword)

    def _millis(self, timestamp):
        return self._context.timestamp(timestamp)

    def _assert_html_text(self, text_index, text):
        self._assert_text(text_index, utils.html_escape(text))

    def test_testcase_jsoning(self):
        self._context.start_suite()
        test = TestCase(name='Foo Bar', doc='Test
case
 doc', tags=['foo', 'bar'],
                        timeout='35 years',
                        status='FAIL',
                        message='iz failz!',
                        starttime='20000101 01:00:00.000',
                        endtime='20350101 01:00:00.001')
        parent = lambda:0
        parent.critical = parent
        parent.test_is_critical = lambda *args: True
        test.parent = parent
        test.keywords.create(name=':FOR ${i} IN RANGE 123', type='for',
                             status='FAIL',
                             starttime='20000101 01:00:01.001',
                             endtime='20350101 01:00:00.001').\
                        keywords.create(type='foritem', status='FAIL',
                                        starttime='20000101 01:00:00.999',
                                        endtime='20350101 01:00:00.001').\
                        keywords.create(type='kw', name='Sleep forever',
                                        status='FAIL',
                                        starttime='20000101 01:00:01.000',
                                        endtime='20350101 01:00:00.001')
        test.visit(self)
        self._verify_test(self.datamodel[0], test)

    def _verify_test(self, test_json, test):
        self._assert_texts(test_json, {0:test.name,
                                       1:test.timeout})
        self._assert_html_text(test_json[3], test.doc)
        assert_equals(test_json[2], int(test.critical == 'yes'))
        self._verify_tags(test_json[4], test.tags)
        self._assert_text(test_json[5][0], _StatusHandler._statuses[test.status])
        assert_equals(test_json[5][1], self._millis(test.starttime))
        self._verify_elapsed(test_json[5][2], test)
        if test.message != '':
            self._assert_text(test_json[5][3], test.message)
        self._for_each_verify(test_json[6], test.keywords, self._verify_keyword)

    def _assert_texts(self, datamodel, index_to_text):
        for index in index_to_text:
            self._assert_text(datamodel[index], index_to_text[index])

    def _verify_tags(self, tags_json, tags):
        assert_equals(len(tags_json), len(tags))
        for tag_json, tag in zip(tags_json, tags):
            self._assert_text(tag_json, tag)

    def test_suite_jsoning(self):
        suite = TestSuite(source='../somewhere',
                          name='Somewhere',
                          doc='suite documentation',
                          metadata={'key<':'value<!>',
                                    'key2>':'va>lue2'})
        suite.starttime = '20000101 02:23:01.821'
        suite.endtime   = '20011221 11:31:12.371'
        suite.message   = 'so long and thank you for all the fish!'
        suite.keywords.create(type='setup')
        subsuite = suite.suites.create(name='subsuite')
        subsuite.tests.create(name='test', status='PASS')
        suite.keywords.create(type='teardown')
        suite.visit(self)
        self._verify_suite(self.datamodel[0], suite)

    def _verify_suite(self, suite_json, suite):
        self._assert_text(suite_json[0], suite.name)
        self._assert_text(suite_json[1], suite.source)
        self._assert_text(suite_json[2], '')
        self._assert_html_text(suite_json[3], suite.doc)
        self._verify_metadata(suite_json[4], suite.metadata)
        assert_equals(suite_json[5][0], _StatusHandler._statuses[suite.status])
        assert_equals(suite_json[5][1], self._millis(suite.starttime))
        self._verify_elapsed(suite_json[5][2], suite)
        if suite.message != '':
            self._assert_text(suite_json[5][3], suite.message)
        self._for_each_verify(suite_json[6], suite.suites, self._verify_suite)
        self._for_each_verify(suite_json[7], suite.tests, self._verify_test)
        self._for_each_verify(suite_json[8], suite.keywords, self._verify_keyword)

    def _for_each_verify(self, json, item_list, method):
        for index, subitem in enumerate(item_list):
            method(json[index], subitem)
        assert_equals(len(json), len(item_list))

    def _verify_elapsed(self, elapsed, item):
        if item.starttime != 'N/A':
            assert_equals(elapsed, self._millis(item.endtime)-self._millis(item.starttime))
        else:
            assert_equals(elapsed, 0)

    def _verify_metadata(self, metadata_json, metadata):
        expected = []
        for k,v in metadata.items():
            expected += [k,utils.html_escape(v)]
        for index, value in enumerate(expected):
            self._assert_text(metadata_json[index], value)

    def test_execution_result_jsoning(self):
        result = ExecutionResult()
        result.suite.source = 'kekkonen.html'
        result.suite.name = 'Kekkonen'
        result.suite.doc = 'Foo
Bar
'
        result.generator = 'unit test'
        result.suite.suites.create(name='Urho').tests.create(status='FAIL', name='moi', tags=['tagi']).keywords.create(name='FAILING', status='FAIL').messages.create(message='FAIL', level='WARN', timestamp='20110101 01:01:01.111')
        result.errors.messages.create(message='FAIL', level='WARN', timestamp='20110101 01:01:01.111', linkable=True)
        self._elements[0] = ExecutionResultHandler(self._context, result)
        result.visit(self)
        self._verify_message(self.datamodel['errors'][0], result.errors.messages[0])
        assert_equals(self._context.dump_texts()[self.datamodel['errors'][0][3]], '*s1-s1-t1-k1')
        self._verify_suite(self.datamodel['suite'], result.suite)
        assert_equals(self.datamodel['generator'], result.generator)
        assert_equals(self.datamodel['baseMillis'], self._context.basemillis)
        assert_equals(len(self.datamodel['strings']), 10)
        assert_equals(self.datamodel['stats'],
            [[{'fail': 1, 'label': 'Critical Tests', 'pass': 0},
              {'fail': 1, 'label': 'All Tests', 'pass': 0}],
             [{'fail': 1, 'label': 'tagi', 'pass': 0}],
             [{'fail': 1, 'label': 'Kekkonen', 'id': 's1', 'name': 'Kekkonen', 'pass': 0},
              {'fail': 1, 'label': 'Kekkonen.Urho', 'id': 's1-s1', 'name': 'Urho', 'pass': 0}]])

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


<commit_before>import os
import subprocess
from .simulator import Simulator

class Modelsim(Simulator):

    def __init__(self, system):
        super(Modelsim, self).__init__(system)
        self.sim_root = os.path.join(self.build_root, 'sim-modelsim')
        if system.config.has_option('modelsim', 'vlog_options'):
            self.vlog_options = system.config.get('modelsim','vlog_options').split()

    def configure(self):
        super(Modelsim, self).configure()
        self._write_config_files()

    def _write_config_files(self):
        self.cfg_file = self.system.name+'.scr'

        f = open(os.path.join(self.sim_root,self.cfg_file),'w')

        for include_dir in self.include_dirs:
            f.write("+incdir+" + include_dir + '\n')
        for rtl_file in self.rtl_files:
            f.write(rtl_file + '\n')
        for tb_file in self.tb_files:
            f.write(tb_file + '\n')

        f.close()

    def build(self):
        super(Modelsim, self).build()
        self.model_tech = os.getenv('MODEL_TECH')
        if not self.model_tech:
            print("Environment variable MODEL_TECH was not found. It should be set to <modelsim install path>/bin")
            exit(1)

        #FIXME: Handle failures. Save stdout/stderr. Build vmem file from elf file argument
        try:
            subprocess.check_call([self.model_tech+'/vlib', 'work'],
                                  cwd = self.sim_root)

        except OSError:
            print("Error: Command vlib not found. Make sure it is in $PATH")
            exit(1)
        except CalledProcessError:
            print("Error: Failed to create library work")
            exit(1)

        try:
            logfile = os.path.join(self.sim_root, 'vlog.log')
            subprocess.check_call([self.model_tech+'/vlog', '-f', self.cfg_file, '-quiet', '-l', logfile] +
                                  self.vlog_options,
                            cwd = self.sim_root)
        except OSError:
            print("Error: Command vlog not found. Make sure it is in $PATH")
            exit(1)
        except subprocess.CalledProcessError:
            print("Error: Failed to compile simulation model. Compile log is available in " + logfile)
            exit(1)

        for vpi_module in self.vpi_modules:
            objs = []
            for src_file in vpi_module['src_files']:
                try:
                    subprocess.check_call(['gcc', '-c', '-fPIC', '-g','-m32','-DMODELSIM_VPI'] +
                                          ['-I'+self.model_tech+'/../include'] +
                                          ['-I'+s for s in vpi_module['include_dirs']] +
                                          [src_file],
                                          cwd = self.sim_root,
                                          stdin=subprocess.PIPE)
                except OSError:
                    print("Error: Command gcc not found. Make sure it is in $PATH")
                    exit(1)
                except subprocess.CalledProcessError:
                    print("Error: Compilation of "+src_file + "failed")
                    exit(1)

            try:
                subprocess.check_call(['ld', '-shared','-E','-melf_i386','-o',vpi_module['name']] +
                                      ['gdb.o','jp_vpi.o','rsp-rtl_sim.o'],
                                      #[os.path.splitext(s)[0]+'.o' for s in vpi_module['src_files']],
                                      cwd = self.sim_root,
                                      stdin=subprocess.PIPE)
            except OSError:
                print("Error: Command ld not found. Make sure it is in $PATH")
                exit(1)
            except subprocess.CalledProcessError:
                print("Error: Linking of "+vpi_module['name'] + " failed")
                exit(1)

    def run(self, args):
        super(Modelsim, self).run(args)

        #FIXME: Handle failures. Save stdout/stderr. Build vmem file from elf file argument
        if self.vpi_modules:
            vpi_options = ['pli'] + [s['name'] for s in self.vpi_modules]
        else:
            vpi_options = []
        try:
            subprocess.check_call([self.model_tech+'/vsim', '-c', '-do', 'run -all'] +
                                  vpi_options +
                                  ['work.orpsoc_tb'] +
                                  ['+'+s for s in self.plusargs],
                                  cwd = self.sim_root,
                                  stdin=subprocess.PIPE)
        except OSError:
            print("Error: Command vsim not found. Make sure it is in $PATH")
            exit(1)
        except subprocess.CalledProcessError:
            print("Error: Simulation failed")
            exit(1)
<commit_msg>Add support for vlog/vsim options in modelsim<commit_after>import os
import subprocess
from .simulator import Simulator

class Modelsim(Simulator):

    def __init__(self, system):
        super(Modelsim, self).__init__(system)
        self.sim_root = os.path.join(self.build_root, 'sim-modelsim')
        if system.config.has_option('modelsim', 'vlog_options'):
            self.vlog_options = system.config.get('modelsim','vlog_options').split()
        else:
            self.vlog_options = []

        if system.config.has_option('modelsim', 'vsim_options'):
            self.vsim_options = system.config.get('modelsim','vsim_options').split()
        else:
            self.vsim_options = []

    def configure(self):
        super(Modelsim, self).configure()
        self._write_config_files()

    def _write_config_files(self):
        self.cfg_file = self.system.name+'.scr'

        f = open(os.path.join(self.sim_root,self.cfg_file),'w')

        for include_dir in self.include_dirs:
            f.write("+incdir+" + include_dir + '\n')
        for rtl_file in self.rtl_files:
            f.write(rtl_file + '\n')
        for tb_file in self.tb_files:
            f.write(tb_file + '\n')

        f.close()

    def build(self):
        super(Modelsim, self).build()
        self.model_tech = os.getenv('MODEL_TECH')
        if not self.model_tech:
            print("Environment variable MODEL_TECH was not found. It should be set to <modelsim install path>/bin")
            exit(1)

        #FIXME: Handle failures. Save stdout/stderr. Build vmem file from elf file argument
        try:
            subprocess.check_call([self.model_tech+'/vlib', 'work'],
                                  cwd = self.sim_root)

        except OSError:
            print("Error: Command vlib not found. Make sure it is in $PATH")
            exit(1)
        except CalledProcessError:
            print("Error: Failed to create library work")
            exit(1)

        try:
            logfile = os.path.join(self.sim_root, 'vlog.log')
            subprocess.check_call([self.model_tech+'/vlog', '-f', self.cfg_file, '-quiet', '-l', logfile] +
                                  self.vlog_options,
                            cwd = self.sim_root)
        except OSError:
            print("Error: Command vlog not found. Make sure it is in $PATH")
            exit(1)
        except subprocess.CalledProcessError:
            print("Error: Failed to compile simulation model. Compile log is available in " + logfile)
            exit(1)

        for vpi_module in self.vpi_modules:
            objs = []
            for src_file in vpi_module['src_files']:
                try:
                    subprocess.check_call(['gcc', '-c', '-fPIC', '-g','-m32','-DMODELSIM_VPI'] +
                                          ['-I'+self.model_tech+'/../include'] +
                                          ['-I'+s for s in vpi_module['include_dirs']] +
                                          [src_file],
                                          cwd = self.sim_root,
                                          stdin=subprocess.PIPE)
                except OSError:
                    print("Error: Command gcc not found. Make sure it is in $PATH")
                    exit(1)
                except subprocess.CalledProcessError:
                    print("Error: Compilation of "+src_file + "failed")
                    exit(1)

            try:
                subprocess.check_call(['ld', '-shared','-E','-melf_i386','-o',vpi_module['name']] +
                                      ['gdb.o','jp_vpi.o','rsp-rtl_sim.o'],
                                      #[os.path.splitext(s)[0]+'.o' for s in vpi_module['src_files']],
                                      cwd = self.sim_root,
                                      stdin=subprocess.PIPE)
            except OSError:
                print("Error: Command ld not found. Make sure it is in $PATH")
                exit(1)
            except subprocess.CalledProcessError:
                print("Error: Linking of "+vpi_module['name'] + " failed")
                exit(1)

    def run(self, args):
        super(Modelsim, self).run(args)

        #FIXME: Handle failures. Save stdout/stderr. Build vmem file from elf file argument
        if self.vpi_modules:
            vpi_options = ['pli'] + [s['name'] for s in self.vpi_modules]
        else:
            vpi_options = []
        try:
            logfile = os.path.join(self.sim_root, 'vsim.log')
            subprocess.check_call([self.model_tech+'/vsim', '-c', '-do', 'run -all'] +
                                  ['-l', logfile] +
                                  self.vsim_options +
                                  vpi_options +
                                  ['work.orpsoc_tb'] +
                                  ['+'+s for s in self.plusargs],
                                  cwd = self.sim_root,
                                  stdin=subprocess.PIPE)
        except OSError:
            print("Error: Command vsim not found. Make sure it is in $PATH")
            exit(1)
        except subprocess.CalledProcessError:
            print("Error: Simulation failed. Simulation log is available in " + logfile)
            exit(1)
<|endoftext|>


<commit_before>import unittest
from robot import utils
from robot.result.executionresult import ExecutionResult
from robot.result.keyword import Keyword
from robot.model.message import Message
from robot.output.loggerhelper import LEVELS
from robot.reporting.parsingcontext import Context
from robot.result.datamodel import JSModelCreator
from robot.result.jsondatamodelhandlers import _Handler, KeywordHandler, StatusHandler
from robot.result.testcase import TestCase
from robot.result.testsuite import TestSuite
from robot.utils.asserts import assert_equals, assert_true

class Handler(_Handler):

    def __init__(self, context):
        _Handler.__init__(self, context)
        self._all = []

    def _add(self, data):
        self._all.append(data)

    add_keyword = add_test = add_suite = add_errors = add_message = _add

    def build(self, item):
        return self._all

class _PartialJSModelCreator(JSModelCreator):

    def __init__(self, splitlog=False):
        self._datamodel = None
        self._handlers = []
        self._context = Context(split_log=splitlog)
        self._handlers.append(Handler(self._context))

class TestJsoning(unittest.TestCase):

    def setUp(self):
        self._visitor = _PartialJSModelCreator()
        self._context = self._visitor._context

    @property
    def datamodel(self):
        return self._visitor.datamodel

    def test_html_message_to_json(self):
        message = Message(message='Great danger!',
                          level='WARN',
                          html=True,
                          timestamp='20121212 12:12:12.121')
        message.visit(self._visitor)
        self._verify_message(self._visitor.datamodel[0], message)

    def _verify_message(self, message_json, message):
        assert_equals(message_json[0], self._context.timestamp(message.timestamp))
        assert_equals(message_json[1], LEVELS[message.level])
        message_text = message.message
        if not message.html:
            message_text = utils.html_escape(message_text)
        self._assert_text(message_json[2], message_text)

    def _assert_text(self, text_index, text):
        assert_equals(text_index, self._context.get_id(text))

    def test_non_html_message_to_json(self):
        message = Message(message='This is an html mark --> ',
                          level='INFO',
                          timestamp='19991211 12:12:12.821')
        message.visit(self._visitor)
        self._verify_message(self.datamodel[0], message)

    def test_times(self):
        for timestamp in ['20110531 12:48:09.020','N/A','20110531 12:48:09.010','20110531 12:48:19.035']:
            Message(timestamp=timestamp).visit(self._visitor)
        for index, millis in enumerate([0, None, -10, 10015]):
            assert_equals(self.datamodel[index][0], millis)

    def test_keyword_jsoning(self):
        self._context.start_suite()
        keyword = Keyword(name='Keyword Name',
                          doc='Documentation for a keyword',
                          args=['${first}', '${second}', '${third}'],
                          type='setup',
                          timeout='2 seconds',
                          status='PASS',
                          starttime='20110101 16:16:16.100',
                          endtime='20110101 16:16:18.161')
        keyword.messages.create(message='keyword message',
                                level='INFO',
                                timestamp='20110101 16:16:16.161')
        keyword.keywords.create(name='No Operation',
                                type='kw',
                                status='PASS')
        keyword.visit(self._visitor)
        self._verify_keyword(self.datamodel[0], keyword)

    def _verify_keyword(self, keyword_json, keyword):
        assert_equals(keyword_json[0], KeywordHandler._types[keyword.type])
        self._assert_texts(keyword_json, {1:keyword.name,
                                          2:keyword.timeout,
                                          4: ', '.join(keyword.args)})
        self._assert_html_text(keyword_json[3], keyword.doc)
        assert_equals(keyword_json[-3][0], StatusHandler._statuses[keyword.status])
        assert_equals(keyword_json[-3][1], self._millis(keyword.starttime))
        self._verify_elapsed(keyword_json[-3][2], keyword)
        for index, message in enumerate(keyword.messages):
            self._verify_message(keyword_json[-1][index], message)
        self._for_each_verify(keyword_json[-2], keyword.keywords, self._verify_keyword)

    def _millis(self, timestamp):
        return self._context.timestamp(timestamp)

    def _assert_html_text(self, text_index, text):
        self._assert_text(text_index, utils.html_escape(text))

    def test_testcase_jsoning(self):
        self._context.start_suite()
        test = TestCase(name='Foo Bar', doc='Test
case
 doc', tags=['foo', 'bar'],
                        timeout='35 years',
                        status='FAIL',
                        message='iz failz!',
                        starttime='20000101 01:00:00.000',
                        endtime='20350101 01:00:00.001')
        parent = lambda:0
        parent.criticality = parent
        parent.test_is_critical = lambda *args: True
        test.parent = parent
        test.keywords.create(name=':FOR ${i} IN RANGE 123', type='for',
                             status='FAIL',
                             starttime='20000101 01:00:01.001',
                             endtime='20350101 01:00:00.001').\
                        keywords.create(type='foritem', status='FAIL',
                                        starttime='20000101 01:00:00.999',
                                        endtime='20350101 01:00:00.001').\
                        keywords.create(type='kw', name='Sleep forever',
                                        status='FAIL',
                                        starttime='20000101 01:00:01.000',
                                        endtime='20350101 01:00:00.001')
        test.visit(self._visitor)
        self._verify_test(self.datamodel[0], test)

    def _verify_test(self, test_json, test):
        self._assert_texts(test_json, {0:test.name,
                                       1:test.timeout})
        self._assert_html_text(test_json[3], test.doc)
        assert_equals(test_json[2], int(test.critical == 'yes'))
        self._verify_tags(test_json[4], test.tags)
        self._assert_text(test_json[5][0], StatusHandler._statuses[test.status])
        assert_equals(test_json[5][1], self._millis(test.starttime))
        self._verify_elapsed(test_json[5][2], test)
        if test.message != '':
            self._assert_text(test_json[5][3], test.message)
        self._for_each_verify(test_json[6], test.keywords, self._verify_keyword)

    def _assert_texts(self, datamodel, index_to_text):
        for index in index_to_text:
            self._assert_text(datamodel[index], index_to_text[index])

    def _verify_tags(self, tags_json, tags):
        assert_equals(len(tags_json), len(tags))
        for tag_json, tag in zip(tags_json, tags):
            self._assert_text(tag_json, tag)

    def test_suite_jsoning(self):
        suite = self._create_suite()
        suite.visit(self._visitor)
        self._verify_suite(self.datamodel[0], suite)

    def test_suite_jsoning_with_splitlog(self):
        suite = self._create_suite()
        self._visitor = _PartialJSModelCreator(splitlog=True)
        self._context = self._visitor._context
        suite.visit(self._visitor)
        self._verify_keywords_splitted_from_suite_keywords(self.datamodel[0][8])
        self._verify_keywords_splitted_from_tests(self.datamodel[0][6][0][7])

    def test_splitlog_keywords_with_strings_are_in_separate_json(self):
        self._visitor = _PartialJSModelCreator(splitlog=True)
        self._context = self._visitor._context
        self._context.start_suite()
        test = TestCase(name='some name')
        test.keywords.create(name='some other name')
        parent = lambda:0
        parent.criticality = parent
        parent.test_is_critical = lambda *args: True
        test.parent = parent
        test.visit(self._visitor)
        model, strings = self._context.split_results[self.datamodel[0][6]-1]
        assert_equals(strings[model[0][1]], '*some other name')

    def _verify_keywords_splitted_from_suite_keywords(self, suite_keywords):
        for kw in suite_keywords:
            self._verify_empty_list_or_int(kw[-2])

    def _verify_keywords_splitted_from_tests(self, tests):
        for test in tests:
            self._verify_empty_list_or_int(test[6])

    def _verify_empty_list_or_int(self, item):
        assert_true(item == [] or isinstance(item, int))

    def _create_suite(self):
        suite = TestSuite(source='../somewhere',
                          name='Somewhere',
                          doc='suite documentation',
                          metadata={'key<': 'value<!>',
                                    'key2>': 'va>lue2'})
        suite.starttime = '20000101 02:23:01.821'
        suite.endtime = '20011221 11:31:12.371'
        suite.message = 'so long and thank you for all the fish!'
        suite.keywords.create(type='setup').keywords.create(name='some keyword')
        subsuite = suite.suites.create(name='subsuite')
        subsuite.tests.create(name='test', status='PASS').keywords.create(name='some other keyword')
        suite.keywords.create(type='teardown')
        return suite

    def _verify_suite(self, suite_json, suite):
        self._assert_text(suite_json[0], suite.name)
        self._assert_text(suite_json[1], suite.source)
        self._assert_text(suite_json[2], '')
        self._assert_html_text(suite_json[3], suite.doc)
        self._verify_metadata(suite_json[4], suite.metadata)
        assert_equals(suite_json[5][0], StatusHandler._statuses[suite.status])
        assert_equals(suite_json[5][1], self._millis(suite.starttime))
        self._verify_elapsed(suite_json[5][2], suite)
        if suite.message != '':
            self._assert_text(suite_json[5][3], suite.message)
        self._for_each_verify(suite_json[6], suite.suites, self._verify_suite)
        self._for_each_verify(suite_json[7], suite.tests, self._verify_test)
        self._for_each_verify(suite_json[8], suite.keywords, self._verify_keyword)

    def _for_each_verify(self, json, item_list, method):
        for index, subitem in enumerate(item_list):
            method(json[index], subitem)
        assert_equals(len(json), len(item_list))

    def _verify_elapsed(self, elapsed, item):
        if item.starttime != 'N/A':
            assert_equals(elapsed, self._millis(item.endtime)-self._millis(item.starttime))
        else:
            assert_equals(elapsed, 0)

    def _verify_metadata(self, metadata_json, metadata):
        expected = []
        for k,v in metadata.items():
            expected += [k,utils.html_escape(v)]
        for index, value in enumerate(expected):
            self._assert_text(metadata_json[index], value)

    def test_execution_result_jsoning(self):
        result = ExecutionResult()
        result.suite.source = 'kekkonen.html'
        result.suite.name = 'Kekkonen'
        result.suite.doc = 'Foo
Bar
'
        result.generator = 'unit test'
        result.suite.suites.create(name='Urho').tests.create(status='FAIL', name='moi', tags=['tagi']).keywords.create(name='FAILING', status='FAIL').messages.create(message='FAIL', level='WARN', timestamp='20110101 01:01:01.111')
        result.errors.messages.create(message='FAIL', level='WARN', timestamp='20110101 01:01:01.111', linkable=True)
        self._visitor = JSModelCreator(result)
        self._context = self._visitor._context
        result.visit(self._visitor)
        self._verify_message(self.datamodel['errors'][0],
                             result.errors.messages[0])
        assert_equals(self._context.dump_texts()[self.datamodel['errors'][0][3]], '*s1-s1-t1-k1')
        self._verify_suite(self.datamodel['suite'], result.suite)
        assert_equals(self.datamodel['generator'], result.generator)
        assert_equals(self.datamodel['baseMillis'], self._context.basemillis)
        assert_equals(len(self.datamodel['strings']), 10)
        assert_equals(self.datamodel['stats'],
            [[{'fail': 1, 'label': 'Critical Tests', 'pass': 0},
              {'fail': 1, 'label': 'All Tests', 'pass': 0}],
             [{'fail': 1, 'label': 'tagi', 'pass': 0}],
             [{'fail': 1, 'label': 'Kekkonen', 'id': 's1', 'name': 'Kekkonen', 'pass': 0},
              {'fail': 1, 'label': 'Kekkonen.Urho', 'id': 's1-s1', 'name': 'Urho', 'pass': 0}]])

if __name__ == '__main__':
    unittest.main()
<commit_msg>Remove expectation related to generator<commit_after>import unittest
from robot import utils
from robot.result.executionresult import ExecutionResult
from robot.result.keyword import Keyword
from robot.model.message import Message
from robot.output.loggerhelper import LEVELS
from robot.reporting.parsingcontext import Context
from robot.result.datamodel import JSModelCreator
from robot.result.jsondatamodelhandlers import _Handler, KeywordHandler, StatusHandler
from robot.result.testcase import TestCase
from robot.result.testsuite import TestSuite
from robot.utils.asserts import assert_equals, assert_true

class Handler(_Handler):

    def __init__(self, context):
        _Handler.__init__(self, context)
        self._all = []

    def _add(self, data):
        self._all.append(data)

    add_keyword = add_test = add_suite = add_errors = add_message = _add

    def build(self, item):
        return self._all

class _PartialJSModelCreator(JSModelCreator):

    def __init__(self, splitlog=False):
        self._datamodel = None
        self._handlers = []
        self._context = Context(split_log=splitlog)
        self._handlers.append(Handler(self._context))

class TestJsoning(unittest.TestCase):

    def setUp(self):
        self._visitor = _PartialJSModelCreator()
        self._context = self._visitor._context

    @property
    def datamodel(self):
        return self._visitor.datamodel

    def test_html_message_to_json(self):
        message = Message(message='Great danger!',
                          level='WARN',
                          html=True,
                          timestamp='20121212 12:12:12.121')
        message.visit(self._visitor)
        self._verify_message(self._visitor.datamodel[0], message)

    def _verify_message(self, message_json, message):
        assert_equals(message_json[0], self._context.timestamp(message.timestamp))
        assert_equals(message_json[1], LEVELS[message.level])
        message_text = message.message
        if not message.html:
            message_text = utils.html_escape(message_text)
        self._assert_text(message_json[2], message_text)

    def _assert_text(self, text_index, text):
        assert_equals(text_index, self._context.get_id(text))

    def test_non_html_message_to_json(self):
        message = Message(message='This is an html mark --> ',
                          level='INFO',
                          timestamp='19991211 12:12:12.821')
        message.visit(self._visitor)
        self._verify_message(self.datamodel[0], message)

    def test_times(self):
        for timestamp in ['20110531 12:48:09.020','N/A','20110531 12:48:09.010','20110531 12:48:19.035']:
            Message(timestamp=timestamp).visit(self._visitor)
        for index, millis in enumerate([0, None, -10, 10015]):
            assert_equals(self.datamodel[index][0], millis)

    def test_keyword_jsoning(self):
        self._context.start_suite()
        keyword = Keyword(name='Keyword Name',
                          doc='Documentation for a keyword',
                          args=['${first}', '${second}', '${third}'],
                          type='setup',
                          timeout='2 seconds',
                          status='PASS',
                          starttime='20110101 16:16:16.100',
                          endtime='20110101 16:16:18.161')
        keyword.messages.create(message='keyword message',
                                level='INFO',
                                timestamp='20110101 16:16:16.161')
        keyword.keywords.create(name='No Operation',
                                type='kw',
                                status='PASS')
        keyword.visit(self._visitor)
        self._verify_keyword(self.datamodel[0], keyword)

    def _verify_keyword(self, keyword_json, keyword):
        assert_equals(keyword_json[0], KeywordHandler._types[keyword.type])
        self._assert_texts(keyword_json, {1:keyword.name,
                                          2:keyword.timeout,
                                          4: ', '.join(keyword.args)})
        self._assert_html_text(keyword_json[3], keyword.doc)
        assert_equals(keyword_json[-3][0], StatusHandler._statuses[keyword.status])
        assert_equals(keyword_json[-3][1], self._millis(keyword.starttime))
        self._verify_elapsed(keyword_json[-3][2], keyword)
        for index, message in enumerate(keyword.messages):
            self._verify_message(keyword_json[-1][index], message)
        self._for_each_verify(keyword_json[-2], keyword.keywords, self._verify_keyword)

    def _millis(self, timestamp):
        return self._context.timestamp(timestamp)

    def _assert_html_text(self, text_index, text):
        self._assert_text(text_index, utils.html_escape(text))

    def test_testcase_jsoning(self):
        self._context.start_suite()
        test = TestCase(name='Foo Bar', doc='Test
case
 doc', tags=['foo', 'bar'],
                        timeout='35 years',
                        status='FAIL',
                        message='iz failz!',
                        starttime='20000101 01:00:00.000',
                        endtime='20350101 01:00:00.001')
        parent = lambda:0
        parent.criticality = parent
        parent.test_is_critical = lambda *args: True
        test.parent = parent
        test.keywords.create(name=':FOR ${i} IN RANGE 123', type='for',
                             status='FAIL',
                             starttime='20000101 01:00:01.001',
                             endtime='20350101 01:00:00.001').\
                        keywords.create(type='foritem', status='FAIL',
                                        starttime='20000101 01:00:00.999',
                                        endtime='20350101 01:00:00.001').\
                        keywords.create(type='kw', name='Sleep forever',
                                        status='FAIL',
                                        starttime='20000101 01:00:01.000',
                                        endtime='20350101 01:00:00.001')
        test.visit(self._visitor)
        self._verify_test(self.datamodel[0], test)

    def _verify_test(self, test_json, test):
        self._assert_texts(test_json, {0:test.name,
                                       1:test.timeout})
        self._assert_html_text(test_json[3], test.doc)
        assert_equals(test_json[2], int(test.critical == 'yes'))
        self._verify_tags(test_json[4], test.tags)
        self._assert_text(test_json[5][0], StatusHandler._statuses[test.status])
        assert_equals(test_json[5][1], self._millis(test.starttime))
        self._verify_elapsed(test_json[5][2], test)
        if test.message != '':
            self._assert_text(test_json[5][3], test.message)
        self._for_each_verify(test_json[6], test.keywords, self._verify_keyword)

    def _assert_texts(self, datamodel, index_to_text):
        for index in index_to_text:
            self._assert_text(datamodel[index], index_to_text[index])

    def _verify_tags(self, tags_json, tags):
        assert_equals(len(tags_json), len(tags))
        for tag_json, tag in zip(tags_json, tags):
            self._assert_text(tag_json, tag)

    def test_suite_jsoning(self):
        suite = self._create_suite()
        suite.visit(self._visitor)
        self._verify_suite(self.datamodel[0], suite)

    def test_suite_jsoning_with_splitlog(self):
        suite = self._create_suite()
        self._visitor = _PartialJSModelCreator(splitlog=True)
        self._context = self._visitor._context
        suite.visit(self._visitor)
        self._verify_keywords_splitted_from_suite_keywords(self.datamodel[0][8])
        self._verify_keywords_splitted_from_tests(self.datamodel[0][6][0][7])

    def test_splitlog_keywords_with_strings_are_in_separate_json(self):
        self._visitor = _PartialJSModelCreator(splitlog=True)
        self._context = self._visitor._context
        self._context.start_suite()
        test = TestCase(name='some name')
        test.keywords.create(name='some other name')
        parent = lambda:0
        parent.criticality = parent
        parent.test_is_critical = lambda *args: True
        test.parent = parent
        test.visit(self._visitor)
        model, strings = self._context.split_results[self.datamodel[0][6]-1]
        assert_equals(strings[model[0][1]], '*some other name')

    def _verify_keywords_splitted_from_suite_keywords(self, suite_keywords):
        for kw in suite_keywords:
            self._verify_empty_list_or_int(kw[-2])

    def _verify_keywords_splitted_from_tests(self, tests):
        for test in tests:
            self._verify_empty_list_or_int(test[6])

    def _verify_empty_list_or_int(self, item):
        assert_true(item == [] or isinstance(item, int))

    def _create_suite(self):
        suite = TestSuite(source='../somewhere',
                          name='Somewhere',
                          doc='suite documentation',
                          metadata={'key<': 'value<!>',
                                    'key2>': 'va>lue2'})
        suite.starttime = '20000101 02:23:01.821'
        suite.endtime = '20011221 11:31:12.371'
        suite.message = 'so long and thank you for all the fish!'
        suite.keywords.create(type='setup').keywords.create(name='some keyword')
        subsuite = suite.suites.create(name='subsuite')
        subsuite.tests.create(name='test', status='PASS').keywords.create(name='some other keyword')
        suite.keywords.create(type='teardown')
        return suite

    def _verify_suite(self, suite_json, suite):
        self._assert_text(suite_json[0], suite.name)
        self._assert_text(suite_json[1], suite.source)
        self._assert_text(suite_json[2], '')
        self._assert_html_text(suite_json[3], suite.doc)
        self._verify_metadata(suite_json[4], suite.metadata)
        assert_equals(suite_json[5][0], StatusHandler._statuses[suite.status])
        assert_equals(suite_json[5][1], self._millis(suite.starttime))
        self._verify_elapsed(suite_json[5][2], suite)
        if suite.message != '':
            self._assert_text(suite_json[5][3], suite.message)
        self._for_each_verify(suite_json[6], suite.suites, self._verify_suite)
        self._for_each_verify(suite_json[7], suite.tests, self._verify_test)
        self._for_each_verify(suite_json[8], suite.keywords, self._verify_keyword)

    def _for_each_verify(self, json, item_list, method):
        for index, subitem in enumerate(item_list):
            method(json[index], subitem)
        assert_equals(len(json), len(item_list))

    def _verify_elapsed(self, elapsed, item):
        if item.starttime != 'N/A':
            assert_equals(elapsed, self._millis(item.endtime)-self._millis(item.starttime))
        else:
            assert_equals(elapsed, 0)

    def _verify_metadata(self, metadata_json, metadata):
        expected = []
        for k,v in metadata.items():
            expected += [k,utils.html_escape(v)]
        for index, value in enumerate(expected):
            self._assert_text(metadata_json[index], value)

    def test_execution_result_jsoning(self):
        result = ExecutionResult()
        result.suite.source = 'kekkonen.html'
        result.suite.name = 'Kekkonen'
        result.suite.doc = 'Foo
Bar
'
        result.generator = 'unit test'
        result.suite.suites.create(name='Urho').tests.create(status='FAIL', name='moi', tags=['tagi']).keywords.create(name='FAILING', status='FAIL').messages.create(message='FAIL', level='WARN', timestamp='20110101 01:01:01.111')
        result.errors.messages.create(message='FAIL', level='WARN', timestamp='20110101 01:01:01.111', linkable=True)
        self._visitor = JSModelCreator()
        self._context = self._visitor._context
        result.visit(self._visitor)
        self._verify_message(self.datamodel['errors'][0],
                             result.errors.messages[0])
        assert_equals(self._context.dump_texts()[self.datamodel['errors'][0][3]], '*s1-s1-t1-k1')
        self._verify_suite(self.datamodel['suite'], result.suite)
        assert_equals(self.datamodel['baseMillis'], self._context.basemillis)
        assert_equals(len(self.datamodel['strings']), 10)
        assert_equals(self.datamodel['stats'],
            [[{'fail': 1, 'label': 'Critical Tests', 'pass': 0},
              {'fail': 1, 'label': 'All Tests', 'pass': 0}],
             [{'fail': 1, 'label': 'tagi', 'pass': 0}],
             [{'fail': 1, 'label': 'Kekkonen', 'id': 's1', 'name': 'Kekkonen', 'pass': 0},
              {'fail': 1, 'label': 'Kekkonen.Urho', 'id': 's1-s1', 'name': 'Urho', 'pass': 0}]])

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


<commit_before>import sys
from abc import abstractmethod
from collections import deque

class LRUCache:
    """Page Replacement Algorithm, Least Recently Used (LRU) Caching."""

    dq_store = object()  # Cache store of keys
    key_reference_map = object()  # References of the keys in cache
    _MAX_CAPACITY: int = 10  # Maximum capacity of cache

    @abstractmethod
    def __init__(self, n: int):
        """Creates an empty store and map for the keys.
        The LRUCache is set the size n.
        """
        self.dq_store = deque()
        self.key_reference_map = set()
        if not n:
            LRUCache._MAX_CAPACITY = sys.maxsize
        elif n < 0:
            raise ValueError("n should be an integer greater than 0.")
        else:
            LRUCache._MAX_CAPACITY = n

    def refer(self, x):
        """
        Looks for a page in the cache store and adds reference to the set.
        Remove the least recently used key if the store is full.
        Update store to reflect recent access.
        """
        if x not in self.key_reference_map:
            if len(self.dq_store) == LRUCache._MAX_CAPACITY:
                last_element = self.dq_store.pop()
                self.key_reference_map.remove(last_element)
        else:
            index_remove = 0
            for idx, key in enumerate(self.dq_store):
                if key == x:
                    index_remove = idx
                    break
            self.dq_store.remove(index_remove)

        self.dq_store.appendleft(x)
        self.key_reference_map.add(x)

    def display(self):
        """
        Prints all the elements in the store.
        """
        for k in self.dq_store:
            print(k)

if __name__ == "__main__":
    lru_cache = LRUCache(4)
    lru_cache.refer(1)
    lru_cache.refer(2)
    lru_cache.refer(3)
    lru_cache.refer(1)
    lru_cache.refer(4)
    lru_cache.refer(5)
    lru_cache.display()
<commit_msg>[mypy] fix type annotations for other/least-recently-used.py (#5811)<commit_after>import sys
from collections import deque

class LRUCache:
    """Page Replacement Algorithm, Least Recently Used (LRU) Caching."""

    dq_store = object()  # Cache store of keys
    key_reference_map = object()  # References of the keys in cache
    _MAX_CAPACITY: int = 10  # Maximum capacity of cache

    def __init__(self, n: int):
        """Creates an empty store and map for the keys.
        The LRUCache is set the size n.
        """
        self.dq_store = deque()
        self.key_reference_map = set()
        if not n:
            LRUCache._MAX_CAPACITY = sys.maxsize
        elif n < 0:
            raise ValueError("n should be an integer greater than 0.")
        else:
            LRUCache._MAX_CAPACITY = n

    def refer(self, x):
        """
        Looks for a page in the cache store and adds reference to the set.
        Remove the least recently used key if the store is full.
        Update store to reflect recent access.
        """
        if x not in self.key_reference_map:
            if len(self.dq_store) == LRUCache._MAX_CAPACITY:
                last_element = self.dq_store.pop()
                self.key_reference_map.remove(last_element)
        else:
            index_remove = 0
            for idx, key in enumerate(self.dq_store):
                if key == x:
                    index_remove = idx
                    break
            self.dq_store.remove(index_remove)

        self.dq_store.appendleft(x)
        self.key_reference_map.add(x)

    def display(self):
        """
        Prints all the elements in the store.
        """
        for k in self.dq_store:
            print(k)

if __name__ == "__main__":
    lru_cache = LRUCache(4)
    lru_cache.refer(1)
    lru_cache.refer(2)
    lru_cache.refer(3)
    lru_cache.refer(1)
    lru_cache.refer(4)
    lru_cache.refer(5)
    lru_cache.display()
<|endoftext|>


<commit_before>from django.core.files.storage import FileSystemStorage
# from django.conf import settings
import os

class OverwriteStorage(FileSystemStorage):
    """Subclass of FileSystemStorage which clobbers existing file"""

    # def __init__(self, *args, **kwargs):
    #     """defaults to self.MEDIA_ROOT if location is not passed in"""
    #     self.location = kwargs.pop("location", settings.MEDIA_ROOT)
    #     super(OverwriteStorage, self).__init__(*args, **kwargs)

    def get_available_name(self, name, max_length=None):
        """deletes pre-existing file preventing filename mangling"""
        if self.exists(name):
            os.remove(os.path.join(self.location, name))
        return name
<commit_msg>simple docstring change<commit_after>from django.core.files.storage import FileSystemStorage
# from django.conf import settings
import os

class OverwriteStorage(FileSystemStorage):
    """Subclass of FileSystemStorage which clobbers existing file"""

    # def __init__(self, *args, **kwargs):
    #     """defaults to self.MEDIA_ROOT if location is not passed in"""
    #     self.location = kwargs.pop("location", settings.MEDIA_ROOT)
    #     super(OverwriteStorage, self).__init__(*args, **kwargs)

    def get_available_name(self, name, max_length=None):
        """deletes pre-existing file with same name

        preventing filename mangling"""
        if self.exists(name):
            os.remove(os.path.join(self.location, name))
        return name
<|endoftext|>