summaryrefslogtreecommitdiffstats
path: root/scripts/objdiff
blob: 4fb5d67968932bbf83fbdc63ee84c374d552fa41 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
#!/bin/bash

# objdiff - a small script for validating that a commit or series of commits
# didn't change object code.
#
# Copyright 2014, Jason Cooper <jason@lakedaemon.net>
#
# Licensed under the terms of the GNU GPL version 2

# usage example:
#
# $ git checkout COMMIT_A
# $ <your fancy build command here>
# $ ./scripts/objdiff record path/to/*.o
#
# $ git checkout COMMIT_B
# $ <your fancy build command here>
# $ ./scripts/objdiff record path/to/*.o
#
# $ ./scripts/objdiff diff COMMIT_A COMMIT_B
# $

# And to clean up (everything is in .tmp_objdiff/*)
# $ ./scripts/objdiff clean all
#
# Note: 'make mrproper' will also remove .tmp_objdiff

SRCTREE=$(cd $(git rev-parse --show-toplevel 2>/dev/null); pwd)

if [ -z "$SRCTREE" ]; then
	echo >&2 "ERROR: Not a git repository."
	exit 1
fi

TMPD=$SRCTREE/.tmp_objdiff

usage() {
	echo >&2 "Usage: $0 <command> <args>"
	echo >&2 "  record    <list of object files or directories>"
	echo >&2 "  diff      <commitA> <commitB>"
	echo >&2 "  clean     all | <commit>"
	exit 1
}

get_output_dir() {
	dir=${1%/*}

	if [ "$dir" = "$1" ]; then
		dir=.
	fi

	dir=$(cd $dir; pwd)

	echo $TMPD/$CMT${dir#$SRCTREE}
}

do_objdump() {
	dir=$(get_output_dir $1)
	base=${1##*/}
	stripped=$dir/${base%.o}.stripped
	dis=$dir/${base%.o}.dis

	[ ! -d "$dir" ] && mkdir -p $dir

	# remove addresses for a cleaner diff
	# http://dummdida.tumblr.com/post/60924060451/binary-diff-between-libc-from-scientificlinux-and
	$STRIP -g $1 -R __bug_table -R .note -R .comment -o $stripped
	$OBJDUMP -D $stripped | sed -e "s/^[[:space:]]\+[0-9a-f]\+//" -e "s:^$stripped:$1:" > $dis
}

dorecord() {
	[ $# -eq 0 ] && usage

	FILES="$*"

	CMT="`git rev-parse --short HEAD`"

	STRIP="${CROSS_COMPILE}strip"
	OBJDUMP="${CROSS_COMPILE}objdump"

	for d in $FILES; do
		if [ -d "$d" ]; then
			for f in $(find $d -name '*.o')
			do
				do_objdump $f
			done
		else
			do_objdump $d
		fi
	done
}

dodiff() {
	[ $# -ne 2 ] && [ $# -ne 0 ] && usage

	if [ $# -eq 0 ]; then
		SRC="`git rev-parse --short HEAD^`"
		DST="`git rev-parse --short HEAD`"
	else
		SRC="`git rev-parse --short $1`"
		DST="`git rev-parse --short $2`"
	fi

	DIFF="`which colordiff`"

	if [ ${#DIFF} -eq 0 ] || [ ! -x "$DIFF" ]; then
		DIFF="`which diff`"
	fi

	SRCD="$TMPD/$SRC"
	DSTD="$TMPD/$DST"

	if [ ! -d "$SRCD" ]; then
		echo >&2 "ERROR: $SRCD doesn't exist"
		exit 1
	fi

	if [ ! -d "$DSTD" ]; then
		echo >&2 "ERROR: $DSTD doesn't exist"
		exit 1
	fi

	$DIFF -Nurd $SRCD $DSTD
}

doclean() {
	[ $# -eq 0 ] && usage
	[ $# -gt 1 ] && usage

	if [ "x$1" = "xall" ]; then
		rm -rf $TMPD/*
	else
		CMT="`git rev-parse --short $1`"

		if [ -d "$TMPD/$CMT" ]; then
			rm -rf $TMPD/$CMT
		else
			echo >&2 "$CMT not found"
		fi
	fi
}

[ $# -eq 0 ] &&	usage

case "$1" in
	record)
		shift
		dorecord $*
		;;
	diff)
		shift
		dodiff $*
		;;
	clean)
		shift
		doclean $*
		;;
	*)
		echo >&2 "Unrecognized command '$1'"
		exit 1
		;;
esac
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
# vim: tabstop=4 shiftwidth=4 softtabstop=4

# Copyright 2011 OpenStack LLC.
# 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.

import unittest
import webob

import mock

from openstack.common import exception
from openstack.common import wsgi


class RequestTest(unittest.TestCase):

    def test_content_type_missing(self):
        request = wsgi.Request.blank('/tests/123', method='POST')
        request.body = "<body />"
        self.assertEqual(None, request.get_content_type())

    def test_content_type_unsupported(self):
        request = wsgi.Request.blank('/tests/123', method='POST')
        request.headers["Content-Type"] = "text/html"
        request.body = "asdf<br />"
        self.assertRaises(exception.InvalidContentType,
                          request.get_content_type)

    def test_content_type_with_charset(self):
        request = wsgi.Request.blank('/tests/123')
        request.headers["Content-Type"] = "application/json; charset=UTF-8"
        result = request.get_content_type()
        self.assertEqual(result, "application/json")

    def test_content_type_with_given_content_types(self):
        request = wsgi.Request.blank('/tests/123')
        request.headers["Content-Type"] = "application/new-type;"
        result = request.get_content_type(["application/json",
                                           "application/new-type"])
        self.assertEqual(result, "application/new-type")

    def test_content_type_from_accept_xml(self):
        request = wsgi.Request.blank('/tests/123')
        request.headers["Accept"] = "application/xml"
        result = request.best_match_content_type()
        self.assertEqual(result, "application/xml")

        request = wsgi.Request.blank('/tests/123')
        request.headers["Accept"] = "application/json"
        result = request.best_match_content_type()
        self.assertEqual(result, "application/json")

        request = wsgi.Request.blank('/tests/123')
        request.headers["Accept"] = "application/xml, application/json"
        result = request.best_match_content_type()
        self.assertEqual(result, "application/json")

        request = wsgi.Request.blank('/tests/123')
        request.headers["Accept"] = ("application/json; q=0.3, "
                                     "application/xml; q=0.9")
        result = request.best_match_content_type()
        self.assertEqual(result, "application/xml")

    def test_content_type_from_query_extension(self):
        request = wsgi.Request.blank('/tests/123.xml')
        result = request.best_match_content_type()
        self.assertEqual(result, "application/xml")

        request = wsgi.Request.blank('/tests/123.json')
        result = request.best_match_content_type()
        self.assertEqual(result, "application/json")

        request = wsgi.Request.blank('/tests/123.invalid')
        result = request.best_match_content_type()
        self.assertEqual(result, "application/json")

    def test_content_type_accept_and_query_extension(self):
        request = wsgi.Request.blank('/tests/123.xml')
        request.headers["Accept"] = "application/json"
        result = request.best_match_content_type()
        self.assertEqual(result, "application/xml")

    def test_content_type_accept_default(self):
        request = wsgi.Request.blank('/tests/123.unsupported')
        request.headers["Accept"] = "application/unsupported1"
        result = request.best_match_content_type()
        self.assertEqual(result, "application/json")

    def test_content_type_accept_with_given_content_types(self):
        request = wsgi.Request.blank('/tests/123')
        request.headers["Accept"] = "application/new_type"
        result = request.best_match_content_type(["application/new_type"])
        self.assertEqual(result, "application/new_type")


class ActionDispatcherTest(unittest.TestCase):

    def test_dispatch(self):
        serializer = wsgi.ActionDispatcher()
        serializer.create = lambda x: x
        self.assertEqual(serializer.dispatch('pants', action='create'),
                         'pants')

    def test_dispatch_action_None(self):
        serializer = wsgi.ActionDispatcher()
        serializer.create = lambda x: x + ' pants'
        serializer.default = lambda x: x + ' trousers'
        self.assertEqual(serializer.dispatch('Two', action=None),
                         'Two trousers')

    def test_dispatch_default(self):
        serializer = wsgi.ActionDispatcher()
        serializer.create = lambda x: x + ' pants'
        serializer.default = lambda x: x + ' trousers'
        self.assertEqual(serializer.dispatch('Two', action='update'),
                         'Two trousers')


class ResponseHeadersSerializerTest(unittest.TestCase):

    def test_default(self):
        serializer = wsgi.ResponseHeadersSerializer()
        response = webob.Response()
        serializer.serialize(response, {'v': '123'}, 'asdf')
        self.assertEqual(response.status_int, 200)

    def test_custom(self):
        class Serializer(wsgi.ResponseHeadersSerializer):
            def update(self, response, data):
                response.status_int = 404
                response.headers['X-Custom-Header'] = data['v']
        serializer = Serializer()
        response = webob.Response()
        serializer.serialize(response, {'v': '123'}, 'update')
        self.assertEqual(response.status_int, 404)
        self.assertEqual(response.headers['X-Custom-Header'], '123')


class DictSerializerTest(unittest.TestCase):

    def test_dispatch_default(self):
        serializer = wsgi.DictSerializer()
        self.assertEqual(serializer.serialize({}, 'NonExistantAction'), '')


class XMLDictSerializerTest(unittest.TestCase):

    def test_xml(self):
        input_dict = dict(servers=dict(a=(2, 3)))
        expected_xml = """<servers xmlns="asdf">
                           <a>(2,3)</a>
                         </servers>"""
        serializer = wsgi.XMLDictSerializer(xmlns="asdf")
        result = serializer.serialize(input_dict)
        result = result.replace('\n', '').replace(' ', '')
        expected_xml = expected_xml.replace('\n', '').replace(' ', '')
        self.assertEqual(result, expected_xml)


class JSONDictSerializerTest(unittest.TestCase):

    def test_json(self):
        input_dict = dict(servers=dict(a=(2, 3)))
        expected_json = '{"servers":{"a":[2,3]}}'
        serializer = wsgi.JSONDictSerializer()
        result = serializer.serialize(input_dict)
        result = result.replace('\n', '').replace(' ', '')
        self.assertEqual(result, expected_json)

    def test_object_unicode(self):
        class TestUnicode:
            def __unicode__(self):
                return u'TestUnicode'
        input_dict = dict(cls=TestUnicode())
        expected_str = '{"cls":"TestUnicode"}'
        serializer = wsgi.JSONDictSerializer()
        result = serializer.serialize(input_dict)
        result = result.replace('\n', '').replace(' ', '')
        self.assertEqual(result, expected_str)


class TextDeserializerTest(unittest.TestCase):

    def test_dispatch_default(self):
        deserializer = wsgi.TextDeserializer()
        self.assertEqual(deserializer.deserialize({}, 'update'), {})


class JSONDeserializerTest(unittest.TestCase):

    def test_json(self):
        data = """{"a": {
                "a1": "1",
                "a2": "2",
                "bs": ["1", "2", "3", {"c": {"c1": "1"}}],
                "d": {"e": "1"},
                "f": "1"}}"""
        as_dict = {
            'body': {
                'a': {
                    'a1': '1',
                    'a2': '2',
                    'bs': ['1', '2', '3', {'c': {'c1': '1'}}],
                    'd': {'e': '1'},
                    'f': '1',
                },
            },
        }
        deserializer = wsgi.JSONDeserializer()
        self.assertEqual(deserializer.deserialize(data), as_dict)


class XMLDeserializerTest(unittest.TestCase):

    def test_xml(self):
        xml = """
            <a a1="1" a2="2">
              <bs><b>1</b><b>2</b><b>3</b><b><c c1="1"/></b></bs>
              <d><e>1</e></d>
              <f>1</f>
            </a>
            """.strip()
        as_dict = {
            'body': {
                'a': {
                    'a1': '1',
                    'a2': '2',
                    'bs': ['1', '2', '3', {'c': {'c1': '1'}}],
                    'd': {'e': '1'},
                    'f': '1',
                },
            },
        }
        metadata = {'plurals': {'bs': 'b', 'ts': 't'}}
        deserializer = wsgi.XMLDeserializer(metadata=metadata)
        self.assertEqual(deserializer.deserialize(xml), as_dict)

    def test_xml_empty(self):
        xml = '<a></a>'
        as_dict = {"body": {"a": {}}}
        deserializer = wsgi.XMLDeserializer()
        self.assertEqual(deserializer.deserialize(xml), as_dict)


class RequestHeadersDeserializerTest(unittest.TestCase):

    def test_default(self):
        deserializer = wsgi.RequestHeadersDeserializer()
        req = wsgi.Request.blank('/')
        self.assertEqual(deserializer.deserialize(req, 'nonExistant'), {})

    def test_custom(self):
        class Deserializer(wsgi.RequestHeadersDeserializer):
            def update(self, request):
                return {'a': request.headers['X-Custom-Header']}
        deserializer = Deserializer()
        req = wsgi.Request.blank('/')
        req.headers['X-Custom-Header'] = 'b'
        self.assertEqual(deserializer.deserialize(req, 'update'), {'a': 'b'})


class ResponseSerializerTest(unittest.TestCase):

    def setUp(self):
        class JSONSerializer(object):
            def serialize(self, data, action='default'):
                return 'pew_json'

        class XMLSerializer(object):
            def serialize(self, data, action='default'):
                return 'pew_xml'

        class HeadersSerializer(object):
            def serialize(self, response, data, action):
                response.status_int = 404

        self.body_serializers = {
            'application/json': JSONSerializer(),
            'application/xml': XMLSerializer(),
        }

        self.serializer = wsgi.ResponseSerializer(self.body_serializers,
                                                  HeadersSerializer())

    def tearDown(self):
        pass

    def test_get_serializer(self):
        ctype = 'application/json'
        self.assertEqual(self.serializer.get_body_serializer(ctype),
                         self.body_serializers[ctype])

    def test_get_serializer_unknown_content_type(self):
        self.assertRaises(exception.InvalidContentType,
                          self.serializer.get_body_serializer,
                          'application/unknown')

    def test_serialize_json_response(self):
        response = self.serializer.serialize({}, 'application/json')
        self.assertEqual(response.headers['Content-Type'], 'application/json')
        self.assertEqual(response.body, 'pew_json')
        self.assertEqual(response.status_int, 404)

    def test_serialize_xml_response(self):
        response = self.serializer.serialize({}, 'application/xml')
        self.assertEqual(response.headers['Content-Type'], 'application/xml')
        self.assertEqual(response.body, 'pew_xml')
        self.assertEqual(response.status_int, 404)

    def test_serialize_response_None(self):
        response = self.serializer.serialize(None, 'application/json')

        self.assertEqual(response.headers['Content-Type'], 'application/json')
        self.assertEqual(response.body, '')
        self.assertEqual(response.status_int, 404)