<s> from unittest import TestCase <EOL> import simplejson as S <EOL> class JSONTestObject : <EOL> pass <EOL> class RecursiveJSONEncoder ( S . JSONEncoder ) : <EOL> recurse = False <EOL> def default ( self , o ) : <EOL> if o is JSONTestObject : <EOL> if self . recurse : <EOL> return [ JSONTestObject ] <EOL> else : <EOL> return '<STR_LIT>' <EOL> return S . JSONEncoder . default ( o ) <EOL> class TestRecursion ( TestCase ) : <EOL> def test_listrecursion ( self ) : <EOL> x = [ ] <EOL> x . append ( x ) <EOL> try : <EOL> S . dumps ( x ) <EOL> except ValueError : <EOL> pass <EOL> else : <EOL> self . fail ( "<STR_LIT>" ) <EOL> x = [ ] <EOL> y = [ x ] <EOL> x . append ( y ) <EOL> try : <EOL> S . dumps ( x ) <EOL> except ValueError : <EOL> pass <EOL> else : <EOL> self . fail ( "<STR_LIT>" ) <EOL> y = [ ] <EOL> x = [ y , y ] <EOL> S . dumps ( x ) <EOL> def test_dictrecursion ( self ) : <EOL> x = { } <EOL> x [ "<STR_LIT:test>" ] = x <EOL> try : <EOL> S . dumps ( x ) <EOL> except ValueError : <EOL> pass <EOL> else : <EOL> self . fail ( "<STR_LIT>" ) <EOL> x = { } <EOL> y = { "<STR_LIT:a>" : x , "<STR_LIT:b>" : x } <EOL> S . dumps ( x ) <EOL> def test_defaultrecursion ( self ) : <EOL> enc = RecursiveJSONEncoder ( ) <EOL> self . assertEquals ( enc . encode ( JSONTestObject ) , '<STR_LIT>' ) <EOL> enc . recurse = True <EOL> try : <EOL> enc . encode ( JSONTestObject ) <EOL> except ValueError : <EOL> pass <EOL> else : <EOL> self . fail ( "<STR_LIT>" ) </s>
