[2.7] bpo-6700: Fix inspect.getsourcelines for module level frames/tracebacks (GH-8864)

(cherry picked from commit 91cb298f811961277fd4cc4a32211899d48bedcb)

Co-authored-by: Vladimir Matveev <v2matveev@outlook.com>
diff --git a/Lib/test/inspect_fodder.py b/Lib/test/inspect_fodder.py
index 5c87ae6..548765c 100644
--- a/Lib/test/inspect_fodder.py
+++ b/Lib/test/inspect_fodder.py
@@ -56,3 +56,9 @@
 
 class FesteringGob(MalodorousPervert, ParrotDroppings):
     pass
+
+currentframe = inspect.currentframe()
+try:
+    raise Exception()
+except:
+    tb = sys.exc_info()[2]
diff --git a/Lib/test/test_inspect.py b/Lib/test/test_inspect.py
index 7d09c6f..5063a30 100644
--- a/Lib/test/test_inspect.py
+++ b/Lib/test/test_inspect.py
@@ -209,7 +209,7 @@
 
     def sourcerange(self, top, bottom):
         lines = self.source.split("\n")
-        return "\n".join(lines[top-1:bottom]) + "\n"
+        return "\n".join(lines[top-1:bottom]) + ("\n" if bottom else "")
 
     def assertSourceEqual(self, obj, top, bottom):
         self.assertEqual(inspect.getsource(obj),
@@ -331,6 +331,16 @@
         finally:
             linecache.getlines = getlines
 
+class TestGettingSourceOfToplevelFrames(GetSourceBase):
+    fodderFile = mod
+
+    def test_range_toplevel_frame(self):
+        self.maxDiff = None
+        self.assertSourceEqual(mod.currentframe, 1, None)
+
+    def test_range_traceback_toplevel_frame(self):
+        self.assertSourceEqual(mod.tb, 1, None)
+
 class TestDecorators(GetSourceBase):
     fodderFile = mod2
 
@@ -896,7 +906,8 @@
         TestDecorators, TestRetrievingSourceCode, TestOneliners, TestBuggyCases,
         TestInterpreterStack, TestClassesAndFunctions, TestPredicates,
         TestGetcallargsFunctions, TestGetcallargsFunctionsCellVars,
-        TestGetcallargsMethods, TestGetcallargsUnboundMethods)
+        TestGetcallargsMethods, TestGetcallargsUnboundMethods,
+        TestGettingSourceOfToplevelFrames)
 
 if __name__ == "__main__":
     test_main()