@@ -38,4 +38,91 @@ describe('Util', function()
3838 end )
3939 end )
4040 end )
41+
42+ describe (' readfile' , function ()
43+ --- @type OrgFile
44+ local file
45+ before_each (function ()
46+ if not file then
47+ file = helpers .create_file ({
48+ ' First line' ,
49+ ' ' ,
50+ ' * Headline' ,
51+ ' Contents' ,
52+ })
53+ end
54+ end )
55+
56+ it (' returns lines' , function ()
57+ local contents = utils .readfile (file .filename ):wait ()
58+ assert .are .same (contents , {
59+ ' First line' ,
60+ ' ' ,
61+ ' * Headline' ,
62+ ' Contents' ,
63+ })
64+ end )
65+
66+ it (' returns raw contents' , function ()
67+ local contents = utils .readfile (file .filename , { raw = true }):wait ()
68+ assert .are .equal (contents , ' First line\n\n * Headline\n Contents\n ' )
69+ end )
70+
71+ it (' schedules its results for later' , function ()
72+ utils
73+ .readfile (file .filename , { schedule = true })
74+ :next (function (contents )
75+ -- Without `schedule = true`, this line would run inside `fast-api`
76+ -- and thus fail.
77+ vim .fn .setreg (' ' , contents )
78+ end )
79+ :wait ()
80+ local contents = vim .fn .getreg (' ' )
81+ assert .are .equal (contents , ' First line\n\n * Headline\n Contents\n ' )
82+ end )
83+ end )
84+
85+ describe (' writefile' , function ()
86+ --- @type string
87+ local filename
88+ before_each (function ()
89+ if not filename then
90+ filename = vim .fn .tempname ()
91+ end
92+ end )
93+
94+ local contents = {
95+ ' First line' ,
96+ ' ' ,
97+ ' * Headline' ,
98+ ' Contents' ,
99+ }
100+
101+ it (' writes bare strings' , function ()
102+ local bytes = utils .writefile (filename , table.concat (contents , ' \n ' )):wait ()
103+ assert .are .equal (bytes , 31 )
104+ local reread = vim .fn .readfile (filename )
105+ assert .are .same (reread , contents )
106+ end )
107+
108+ it (' writes lists of strings by concatenation' , function ()
109+ local bytes = utils .writefile (filename , contents ):wait ()
110+ assert .are .equal (bytes , 28 )
111+ local reread = vim .fn .readfile (filename )
112+ assert .are .same (reread , { ' First line* HeadlineContents' })
113+ end )
114+
115+ it (' does not schedule its results' , function ()
116+ local promise = utils .writefile (filename , contents ):next (function (bytes )
117+ return vim .fn .setreg (' ' , bytes )
118+ end )
119+ --- @type boolean , string ?
120+ local ok , err = pcall (promise .wait , promise )
121+ assert .is .False (ok )
122+ assert (err )
123+ local expected = ' E5560: Vimscript function must not be called in a lua loop callback'
124+ local msg = err :sub (# err - # expected )
125+ assert .are .equal (expected , msg )
126+ end )
127+ end )
41128end )
0 commit comments