@@ -201,6 +201,77 @@ def project(gl):
201201 print (f"Project already deleted: { e } " )
202202
203203
204+ @pytest .fixture (scope = "function" )
205+ def merge_request (project , wait_for_sidekiq ):
206+ """Fixture used to create a merge_request.
207+
208+ It will create a branch, add a commit to the branch, and then create a
209+ merge request against project.default_branch. The MR will be returned.
210+
211+ When finished any created merge requests and branches will be deleted.
212+
213+ NOTE: No attempt is made to restore project.default_branch to its previous
214+ state. So if the merge request is merged then its content will be in the
215+ project.default_branch branch.
216+ """
217+
218+ to_delete = []
219+
220+ def _merge_request (* , source_branch : str ):
221+ # Wait for processes to be done before we start...
222+ # NOTE(jlvillal): Sometimes the CI would give a "500 Internal Server
223+ # Error". Hoping that waiting until all other processes are done will
224+ # help with that.
225+ result = wait_for_sidekiq (timeout = 60 )
226+ assert result is True , "sidekiq process should have terminated but did not"
227+
228+ project .refresh () # Gets us the current default branch
229+ project .branches .create (
230+ {"branch" : source_branch , "ref" : project .default_branch }
231+ )
232+ # NOTE(jlvillal): Must create a commit in the new branch before we can
233+ # create an MR that will work.
234+ project .files .create (
235+ {
236+ "file_path" : f"README.{ source_branch } " ,
237+ "branch" : source_branch ,
238+ "content" : "Initial content" ,
239+ "commit_message" : "New commit in new branch" ,
240+ }
241+ )
242+ mr = project .mergerequests .create (
243+ {
244+ "source_branch" : source_branch ,
245+ "target_branch" : project .default_branch ,
246+ "title" : "Should remove source branch" ,
247+ "remove_source_branch" : True ,
248+ }
249+ )
250+ result = wait_for_sidekiq (timeout = 60 )
251+ assert result is True , "sidekiq process should have terminated but did not"
252+
253+ mr_iid = mr .iid
254+ for _ in range (60 ):
255+ mr = project .mergerequests .get (mr_iid )
256+ if mr .merge_status != "checking" :
257+ break
258+ time .sleep (0.5 )
259+ assert mr .merge_status != "checking"
260+
261+ to_delete .append ((mr .iid , source_branch ))
262+ return mr
263+
264+ yield _merge_request
265+
266+ for mr_iid , source_branch in to_delete :
267+ project .mergerequests .delete (mr_iid )
268+ try :
269+ project .branches .delete (source_branch )
270+ except gitlab .exceptions .GitlabDeleteError :
271+ # Ignore if branch was already deleted
272+ pass
273+
274+
204275@pytest .fixture (scope = "module" )
205276def project_file (project ):
206277 """File fixture for tests requiring a project with files and branches."""
0 commit comments