import sys
import io

import hacks


def test_stdout_monkeypatching():
    
    # Let's first patch stdout manually:
    real_stdout = sys.stdout
    fake_stdout = io.StringIO()
    sys.stdout = fake_stdout  # While it is monkey-patched, other users
    print('Hello')            # may write something else into out fake_stdout.
    sys.stdout = real_stdout

    assert fake_stdout.getvalue() == 'Hello\n'


    # Now let's patch stdout with hacks:
    sys.stdout = hacks.friendly_callable('stdout')(sys.stdout)
    # Nothing bad should happen for now

    fake_stdout = io.StringIO()
    @hacks.around('stdout')
    def capture_stdout(real_stdout_ignored):
        return fake_stdout
    
    with hacks.use(capture_stdout):  # hacks-aided monkeypatching should not
        print('Hello')               # affect other users of stdout

    assert fake_stdout.getvalue() == 'Hello\n'


    # The other benefit is that hacks stack nicely
    @hacks.around('stdout')
    def zomg_ponies(stdout_to_modify):
        class Ponyfier:
            def write(self, text):
                stdout_to_modify.write('🐎' * len(text))
        return Ponyfier()

    with hacks.use(capture_stdout):
        with hacks.use(zomg_ponies):  # A second hack stacks on top
            print('oh no')            # of the other one reasonably

    assert fake_stdout.getvalue() == 'Hello\n' + '🐎' * len('oh no\n')

@@ -1051,24 +1051,104 @@
 elf, text):%0A
+                ponified = ''.join('%F0%9F%90%8E' if not c.isspace() else c for c in text)%0A
             
@@ -1178,23 +1178,16 @@
 ite(
-'%F0%9F%90%8E' * len(text)
+ponified
 )%0A  
@@ -1243,24 +1243,43 @@
 re_stdout):%0A
+        print('I')%0A
         with
@@ -1357,15 +1357,15 @@
 nt('
-oh no
+HATE
 ')
+ 
     
@@ -1381,21 +1381,21 @@
  of the 
-other
+first
  one rea
@@ -1401,16 +1401,40 @@
 asonably
+%0A        print('PONIES')
 %0A%0A    as
@@ -1476,29 +1476,23 @@
 lo%5Cn
-' + '%F0%9F%90%8E' * len('oh no
+I%5Cn%F0%9F%90%8E%F0%9F%90%8E%F0%9F%90%8E%F0%9F%90%8E%5CnPONIES
 %5Cn'
-)
 %0A

Make monkeypatching test more readable