patch 9.1.0883: message history cleanup is missing some tests

Problem:  message history cleanup is missing some tests
Solution: Add tests, refactor common code into did_set_msghistory()
          (Shougo Matsushita)

closes: #16078

Co-authored-by: zeertzjq <zeertzjq@outlook.com>
Co-authored-by: Milly <milly.ca@gmail.com>
Signed-off-by: Shougo Matsushita <Shougo.Matsu@gmail.com>
Signed-off-by: Christian Brabandt <cb@256bit.org>
diff --git a/src/testdir/test_cmdline.vim b/src/testdir/test_cmdline.vim
index 110be65..9aec012 100644
--- a/src/testdir/test_cmdline.vim
+++ b/src/testdir/test_cmdline.vim
@@ -4011,4 +4011,30 @@
   let &shellslash = save_shellslash
 endfunc
 
+func Test_msghistory()
+  " After setting 'msghistory' to 2 and outputting a message 4 times with
+  " :echomsg, is the number of output lines of :messages 2?
+  set msghistory=2
+  echomsg 'foo'
+  echomsg 'bar'
+  echomsg 'baz'
+  echomsg 'foobar'
+  call assert_equal(['baz', 'foobar'], GetMessages())
+
+  " When the number of messages is 10 and 'msghistory' is changed to 5, is the
+  " number of output lines of :messages 5?
+  set msghistory=10
+  for num in range(1, 10)
+    echomsg num
+  endfor
+  set msghistory=5
+  call assert_equal(5, len(GetMessages()))
+
+  " Check empty list
+  set msghistory=0
+  call assert_true(empty(GetMessages()))
+
+  set msghistory&
+endfunc
+
 " vim: shiftwidth=2 sts=2 expandtab