File: service_spec.rb

package info (click to toggle)
puppet 5.5.10-4
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 21,116 kB
  • sloc: ruby: 250,669; sh: 1,620; xml: 218; makefile: 151; sql: 103
file content (669 lines) | stat: -rw-r--r-- 28,613 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
#!/usr/bin/env ruby
require 'spec_helper'

describe "Puppet::Util::Windows::Service", :if => Puppet.features.microsoft_windows? do
  require 'puppet/util/windows'

  before(:each) do
    Puppet::Util::Windows::Error.stubs(:format_error_code)
      .with(anything)
      .returns("fake error!")
  end

  def service_state_str(state)
    Puppet::Util::Windows::Service::SERVICE_STATES[state].to_s
  end

  # The following should emulate a successful call to the private function
  # query_status that returns the value of query_return. This should give
  # us a way to mock changes in service status.
  #
  # Everything else is stubbed, the emulation of the successful call is really
  # just an expectation of subject::SERVICE_STATUS_PROCESS.new in sequence that
  # returns the value passed in as a param
  def expect_successful_status_query_and_return(query_return)
    subject::SERVICE_STATUS_PROCESS.expects(:new).in_sequence(status_checks).returns(query_return)
  end

  def expect_successful_status_queries_and_return(*query_returns)
    query_returns.each do |query_return|
      expect_successful_status_query_and_return(query_return)
    end
  end

  # The following should emulate a successful call to the private function
  # query_config that returns the value of query_return. This should give
  # us a way to mock changes in service configuration.
  #
  # Everything else is stubbed, the emulation of the successful call is really
  # just an expectation of subject::QUERY_SERVICE_CONFIGW.new in sequence that
  # returns the value passed in as a param
  def expect_successful_config_query_and_return(query_return)
    subject::QUERY_SERVICE_CONFIGW.expects(:new).in_sequence(status_checks).returns(query_return)
  end

  let(:subject)      { Puppet::Util::Windows::Service }
  let(:pointer) { mock() }
  let(:status_checks) { sequence('status_checks') }
  let(:mock_service_name) { mock() }
  let(:service) { mock() }
  let(:scm) { mock() }

  before do
    subject.stubs(:QueryServiceStatusEx).returns(1)
    subject.stubs(:QueryServiceConfigW).returns(1)
    subject.stubs(:ChangeServiceConfigW).returns(1)
    subject.stubs(:OpenSCManagerW).returns(scm)
    subject.stubs(:OpenServiceW).returns(service)
    subject.stubs(:CloseServiceHandle)
    subject.stubs(:EnumServicesStatusExW).returns(1)
    subject.stubs(:wide_string)
    subject::SERVICE_STATUS_PROCESS.stubs(:new)
    subject::QUERY_SERVICE_CONFIGW.stubs(:new)
    subject::SERVICE_STATUS.stubs(:new).returns({:dwCurrentState => subject::SERVICE_RUNNING})
    FFI.stubs(:errno).returns(0)
    FFI::MemoryPointer.stubs(:new).yields(pointer)
    pointer.stubs(:read_dword)
    pointer.stubs(:write_dword)
    pointer.stubs(:size)
    subject.stubs(:sleep)
  end

  describe "#exists?" do
    context "when the service control manager cannot be opened" do
      let(:scm) { FFI::Pointer::NULL_HANDLE }
      it "raises a puppet error" do
        expect{ subject.exists?(mock_service_name) }.to raise_error(Puppet::Error)
      end
    end

    context "when the service cannot be opened" do
      let(:service) { FFI::Pointer::NULL_HANDLE }

      it "returns false if it fails to open because the service does not exist" do
        FFI.stubs(:errno).returns(Puppet::Util::Windows::Service::ERROR_SERVICE_DOES_NOT_EXIST)

        expect(subject.exists?(mock_service_name)).to be false
      end

      it "raises a puppet error if it fails to open for some other reason" do
        expect{ subject.exists?(mock_service_name) }.to raise_error(Puppet::Error)
      end
    end

    context "when the service can be opened" do
      it "returns true" do
        expect(subject.exists?(mock_service_name)).to be true
      end
    end
  end

  # This shared example contains the unit tests for the wait_on_pending_state
  # helper as used by service actions like #start and #stop. Before including
  # this shared example, be sure to mock out any intermediate calls prior to
  # the pending transition, and make sure that the post-condition _after_ those
  # intermediate calls leaves the service in the pending state. Before including
  # this example in your tests, be sure to define the following variables in a `let`
  # context:
  #     * action -- The service action
  shared_examples "a service action waiting on a pending transition" do |pending_state|
    pending_state_str = Puppet::Util::Windows::Service::SERVICE_STATES[pending_state].to_s

    final_state = Puppet::Util::Windows::Service::FINAL_STATES[pending_state]
    final_state_str = Puppet::Util::Windows::Service::SERVICE_STATES[final_state].to_s

    it "raises a Puppet::Error if the service query fails" do
      subject.expects(:QueryServiceStatusEx).in_sequence(status_checks).returns(FFI::WIN32_FALSE)

      expect { subject.send(action, mock_service_name) }.to raise_error(Puppet::Error)
    end

    it "raises a Puppet::Error if the service unexpectedly transitions to a state other than #{pending_state_str} or #{final_state_str}" do
      invalid_state = (subject::SERVICE_STATES.keys - [pending_state, final_state]).first

      expect_successful_status_query_and_return(dwCurrentState: invalid_state)

      expect { subject.send(action, mock_service_name) }.to raise_error(Puppet::Error)
    end

    it "waits for at least 1 second if the wait_hint/10 is < 1 second" do
      expect_successful_status_queries_and_return(
        { :dwCurrentState => pending_state, :dwWaitHint => 0, :dwCheckPoint => 1 },
        { :dwCurrentState => final_state }
      )

      subject.expects(:sleep).with(1)

      subject.send(action, mock_service_name)
    end

    it "waits for at most 10 seconds if wait_hint/10 is > 10 seconds" do
      expect_successful_status_queries_and_return(
        { :dwCurrentState => pending_state, :dwWaitHint => 1000000, :dwCheckPoint => 1 },
        { :dwCurrentState => final_state }
      )

      subject.expects(:sleep).with(10)

      subject.send(action, mock_service_name)
    end

    it "does not raise an error if the service makes any progress while transitioning to #{final_state_str}" do
      expect_successful_status_queries_and_return(
        # The three "pending_state" statuses simulate the scenario where the service
        # makes some progress during the transition right when Puppet's about to
        # time out.
        { :dwCurrentState => pending_state, :dwWaitHint => 100000, :dwCheckPoint => 1 },
        { :dwCurrentState => pending_state, :dwWaitHint => 100000, :dwCheckPoint => 1 },
        { :dwCurrentState => pending_state, :dwWaitHint => 100000, :dwCheckPoint => 2 },

        { :dwCurrentState => final_state }
      )

      expect { subject.send(action, mock_service_name) }.to_not raise_error
    end

    it "raises a Puppet::Error if it times out while waiting for the transition to #{final_state_str}" do
      31.times do
        expect_successful_status_query_and_return(
          dwCurrentState: pending_state,
          dwWaitHint: 10000,
          dwCheckPoint: 1
        )
      end

      expect { subject.send(action, mock_service_name) }.to raise_error(Puppet::Error)
    end
  end

  # This shared example contains the unit tests for the transition_service_state
  # helper, which is the helper that all of our service actions like #start, #stop
  # delegate to. Including these tests under a shared example lets us include them in each of
  # those service action's unit tests. Before including this example in your tests, be
  # sure to define the following variables in a `let` context:
  #     * initial_state         -- The initial state of the service prior to performing the state
  #                                transition
  #
  #     * mock_state_transition -- A lambda that mocks the state transition. This should mock
  #                                any code in the block that's passed to the
  #                                transition_service_state helper
  #
  # See the unit tests for the #start method to see how this shared example's
  # included.
  #
  shared_examples "a service action that transitions the service state" do |action, valid_initial_states, pending_state, final_state|
    valid_initial_states_str = valid_initial_states.map do |state|
      Puppet::Util::Windows::Service::SERVICE_STATES[state]
    end.join(', ')
    pending_state_str = Puppet::Util::Windows::Service::SERVICE_STATES[pending_state].to_s
    final_state_str = Puppet::Util::Windows::Service::SERVICE_STATES[final_state].to_s

    it "noops if the service is already in the #{final_state} state" do
      expect_successful_status_query_and_return(dwCurrentState: final_state)

      expect { subject.send(action, mock_service_name) }.to_not raise_error
    end

    # invalid_initial_states will be empty for the #stop action
    invalid_initial_states = Puppet::Util::Windows::Service::SERVICE_STATES.keys - valid_initial_states - [final_state]
    unless invalid_initial_states.empty?
      it "raises a Puppet::Error if the service's initial state is not one of #{valid_initial_states_str}" do
        invalid_initial_state = invalid_initial_states.first
        expect_successful_status_query_and_return(dwCurrentState: invalid_initial_state)
  
        expect{ subject.send(action, mock_service_name) }.to raise_error(Puppet::Error)
      end
    end

    context "when there's a pending transition to the #{final_state} state" do
      before(:each) do
        expect_successful_status_query_and_return(dwCurrentState: pending_state)
      end

      include_examples "a service action waiting on a pending transition", pending_state do
        let(:action) { action }
      end
    end

    # If the service action accepts an unsafe pending state as one of the service's
    # initial states, then we need to test that the action waits for the service to
    # transition from that unsafe pending state before doing anything else.
    unsafe_pending_states = valid_initial_states & Puppet::Util::Windows::Service::UNSAFE_PENDING_STATES
    unless unsafe_pending_states.empty?
      unsafe_pending_state = unsafe_pending_states.first
      unsafe_pending_state_str = Puppet::Util::Windows::Service::SERVICE_STATES[unsafe_pending_state]

      context "waiting for a service with #{unsafe_pending_state_str} as its initial state" do
        before(:each) do
          # This mocks the status query to return the 'final_state' by default. Otherwise,
          # we will fail the tests in the latter parts of the code where we wait for the
          # service to finish transitioning to the 'final_state'.
          subject::SERVICE_STATUS_PROCESS.stubs(:new).returns(dwCurrentState: final_state)

          # Set our service's initial state
          expect_successful_status_query_and_return(dwCurrentState: unsafe_pending_state)

          mock_state_transition.call
        end

        include_examples "a service action waiting on a pending transition", unsafe_pending_state do
          let(:action) { action }
        end
      end
    end

    # reads e.g. "waiting for the service to transition to the SERVICE_RUNNING state after executing the 'start' action"
    #
    # NOTE: This is really unit testing the wait_on_state_transition helper
    context "waiting for the service to transition to the #{final_state_str} state after executing the '#{action}' action" do
      before(:each) do
        # Set our service's initial state prior to performing the state transition
        expect_successful_status_query_and_return(dwCurrentState: initial_state)

        mock_state_transition.call
      end

      it "raises a Puppet::Error if the service query fails" do
        subject.expects(:QueryServiceStatusEx).in_sequence(status_checks).returns(FFI::WIN32_FALSE)

        expect { subject.send(action, mock_service_name) }.to raise_error(Puppet::Error)
      end

      it "waits, then queries again until it transitions to #{final_state_str}" do
        expect_successful_status_queries_and_return(
          { :dwCurrentState => initial_state },
          { :dwCurrentState => initial_state },
          { :dwCurrentState => final_state }
        )

        subject.expects(:sleep).with(1).twice

        subject.send(action, mock_service_name)
      end

      context "when it transitions to the #{pending_state_str} state" do
        before(:each) do
          expect_successful_status_query_and_return(dwCurrentState: pending_state)
        end

        include_examples "a service action waiting on a pending transition", pending_state do
          let(:action) { action }
        end
      end

      it "raises a Puppet::Error if it times out while waiting for the transition to #{final_state_str}" do
        31.times do
          expect_successful_status_query_and_return(dwCurrentState: initial_state)
        end

        expect { subject.send(action, mock_service_name) }.to raise_error(Puppet::Error)
      end
    end
  end

  describe "#start" do
    # rspec will still try to load the tests even though
    # the :if => Puppet.features.microsoft_windows? filter
    # is passed-in to the top-level describe block on
    # non-Windows platforms; it just won't run them. However
    # on these platforms, the loading will fail because this
    # test uses a shared example that references variables
    # from the Windows::Service module when building the unit
    # tests, which is only available on Windows platforms.
    # Thus, we add the next here to ensure that rspec does not
    # attempt to load our test code. This is OK for us to do
    # because we do not want to run these tests on non-Windows
    # platforms.
    next unless Puppet.features.microsoft_windows?

    context "when the service control manager cannot be opened" do
      let(:scm) { FFI::Pointer::NULL_HANDLE }
      it "raises a puppet error" do
        expect{ subject.start(mock_service_name) }.to raise_error(Puppet::Error)
      end
    end

    context "when the service cannot be opened" do
      let(:service) { FFI::Pointer::NULL_HANDLE }
      it "raises a puppet error" do
        expect{ subject.start(mock_service_name) }.to raise_error(Puppet::Error)
      end
    end

    context "when the service can be opened" do
      # Can't use rspec's subject here because that
      # can only be referenced inside an 'it' block.
      service = Puppet::Util::Windows::Service
      valid_initial_states = [
        service::SERVICE_STOP_PENDING,
        service::SERVICE_STOPPED,
        service::SERVICE_START_PENDING
      ]
      final_state = service::SERVICE_RUNNING
  
      include_examples "a service action that transitions the service state", :start, valid_initial_states, service::SERVICE_START_PENDING, final_state do
        let(:initial_state) { subject::SERVICE_STOPPED }
        let(:mock_state_transition) do
          lambda do
            subject.stubs(:StartServiceW).returns(1)
          end
        end
      end
  
      it "raises a Puppet::Error if StartServiceW returns false" do
        expect_successful_status_query_and_return(dwCurrentState: subject::SERVICE_STOPPED)
  
        subject.expects(:StartServiceW).returns(FFI::WIN32_FALSE)

        expect { subject.start(mock_service_name) }.to raise_error(Puppet::Error)
      end
  
      it "starts the service" do
        expect_successful_status_queries_and_return(
          { dwCurrentState: subject::SERVICE_STOPPED },
          { dwCurrentState: subject::SERVICE_RUNNING }
        )
  
        subject.expects(:StartServiceW).returns(1)
  
        subject.start(mock_service_name)
      end
    end
  end

  describe "#stop" do
    next unless Puppet.features.microsoft_windows?

    context "when the service control manager cannot be opened" do
      let(:scm) { FFI::Pointer::NULL_HANDLE }
      it "raises a puppet error" do
        expect{ subject.start(mock_service_name) }.to raise_error(Puppet::Error)
      end
    end

    context "when the service cannot be opened" do
      let(:service) { FFI::Pointer::NULL_HANDLE }
      it "raises a puppet error" do
        expect{ subject.start(mock_service_name) }.to raise_error(Puppet::Error)
      end
    end

    context "when the service can be opened" do
      service = Puppet::Util::Windows::Service
      valid_initial_states = service::SERVICE_STATES.keys - [service::SERVICE_STOPPED]
      final_state = service::SERVICE_STOPPED
  
      include_examples "a service action that transitions the service state", :stop, valid_initial_states, service::SERVICE_STOP_PENDING, final_state do
        let(:initial_state) { subject::SERVICE_RUNNING }
        let(:mock_state_transition) do
          lambda do
            subject.stubs(:ControlService).returns(1)
          end
        end
      end

      it "raises a Puppet::Error if ControlService returns false" do
        expect_successful_status_query_and_return(dwCurrentState: subject::SERVICE_RUNNING)

        subject.stubs(:ControlService).returns(FFI::WIN32_FALSE)

        expect { subject.stop(mock_service_name) }.to raise_error(Puppet::Error)
      end
  
      it "stops the service" do
        expect_successful_status_queries_and_return(
          { dwCurrentState: subject::SERVICE_RUNNING },
          { dwCurrentState: subject::SERVICE_STOPPED }
        )

        subject.expects(:ControlService).returns(1)

        subject.stop(mock_service_name)
      end
    end
  end

  describe "#resume" do
    next unless Puppet.features.microsoft_windows?

    context "when the service control manager cannot be opened" do
      let(:scm) { FFI::Pointer::NULL_HANDLE }
      it "raises a puppet error" do
        expect{ subject.start(mock_service_name) }.to raise_error(Puppet::Error)
      end
    end

    context "when the service cannot be opened" do
      let(:service) { FFI::Pointer::NULL_HANDLE }
      it "raises a puppet error" do
        expect{ subject.start(mock_service_name) }.to raise_error(Puppet::Error)
      end
    end

    context "when the service can be opened" do
      service = Puppet::Util::Windows::Service
      valid_initial_states = [
        service::SERVICE_PAUSE_PENDING,
        service::SERVICE_PAUSED,
        service::SERVICE_CONTINUE_PENDING
      ]
      final_state = service::SERVICE_RUNNING
  
      include_examples "a service action that transitions the service state", :resume, valid_initial_states, service::SERVICE_CONTINUE_PENDING, final_state do
        let(:initial_state) { service::SERVICE_PAUSED }
        let(:mock_state_transition) do
          lambda do
            # We need to mock the status query because in the block for #resume, we
            # wait for the service to enter the SERVICE_PAUSED state prior to
            # performing the transition (in case it is in SERVICE_PAUSE_PENDING).
            expect_successful_status_query_and_return(dwCurrentState: subject::SERVICE_PAUSED)

            subject.stubs(:ControlService).returns(1)
          end
        end
      end

      context "waiting for the SERVICE_PAUSE_PENDING => SERVICE_PAUSED transition to finish before resuming it" do
        before(:each) do
          # This mocks the status query to return the SERVICE_RUNNING state by default.
          # Otherwise, we will fail the tests in the latter parts of the code where we
          # wait for the service to finish transitioning to the 'SERVICE_RUNNING' state.
          subject::SERVICE_STATUS_PROCESS.stubs(:new).returns(dwCurrentState: subject::SERVICE_RUNNING)

          expect_successful_status_query_and_return(dwCurrentState: subject::SERVICE_PAUSE_PENDING)

          subject.stubs(:ControlService).returns(1)
        end

        include_examples "a service action waiting on a pending transition", service::SERVICE_PAUSE_PENDING do
          let(:action) { :resume }
        end
      end

      it "raises a Puppet::Error if ControlService returns false" do
        expect_successful_status_query_and_return(dwCurrentState: subject::SERVICE_PAUSED)
        expect_successful_status_query_and_return(dwCurrentState: subject::SERVICE_PAUSED)

        subject.stubs(:ControlService).returns(FFI::WIN32_FALSE)

        expect { subject.resume(mock_service_name) }.to raise_error(Puppet::Error)
      end
  
      it "resumes the service" do
        expect_successful_status_queries_and_return(
          { dwCurrentState: subject::SERVICE_PAUSED },
          { dwCurrentState: subject::SERVICE_PAUSED },
          { dwCurrentState: subject::SERVICE_RUNNING }
        )

        subject.expects(:ControlService).returns(1)

        subject.resume(mock_service_name)
      end
    end
  end

  describe "#service_state" do
    context "when the service control manager cannot be opened" do
      let(:scm) { FFI::Pointer::NULL_HANDLE }
      it "raises a puppet error" do
        expect{ subject.service_state(mock_service_name) }.to raise_error(Puppet::Error)
      end
    end

    context "when the service cannot be opened" do
      let(:service) { FFI::Pointer::NULL_HANDLE }
      it "raises a puppet error" do
        expect{ subject.service_state(mock_service_name) }.to raise_error(Puppet::Error)
      end
    end

    context "when the service can be opened" do
      it "raises Puppet::Error if the result of the query is empty" do
        expect_successful_status_query_and_return({})
        expect{subject.service_state(mock_service_name)}.to raise_error(Puppet::Error)
      end

      it "raises Puppet::Error if the result of the query is an unknown state" do
        expect_successful_status_query_and_return({:dwCurrentState => 999})
        expect{subject.service_state(mock_service_name)}.to raise_error(Puppet::Error)
      end

      # We need to guard this section explicitly since rspec will always
      # construct all examples, even if it isn't going to run them.
      if Puppet.features.microsoft_windows?
        {
          :SERVICE_STOPPED => Puppet::Util::Windows::Service::SERVICE_STOPPED,
          :SERVICE_PAUSED => Puppet::Util::Windows::Service::SERVICE_PAUSED,
          :SERVICE_STOP_PENDING => Puppet::Util::Windows::Service::SERVICE_STOP_PENDING,
          :SERVICE_PAUSE_PENDING => Puppet::Util::Windows::Service::SERVICE_PAUSE_PENDING,
          :SERVICE_RUNNING => Puppet::Util::Windows::Service::SERVICE_RUNNING,
          :SERVICE_CONTINUE_PENDING => Puppet::Util::Windows::Service::SERVICE_CONTINUE_PENDING,
          :SERVICE_START_PENDING => Puppet::Util::Windows::Service::SERVICE_START_PENDING,
        }.each do |state_name, state|
          it "queries the service and returns #{state_name}" do
            expect_successful_status_query_and_return({:dwCurrentState => state})
            expect(subject.service_state(mock_service_name)).to eq(state_name)
          end
        end
      end
    end
  end

  describe "#service_start_type" do
    context "when the service control manager cannot be opened" do
      let(:scm) { FFI::Pointer::NULL_HANDLE }
      it "raises a puppet error" do
        expect{ subject.service_start_type(mock_service_name) }.to raise_error(Puppet::Error)
      end
    end

    context "when the service cannot be opened" do
      let(:service) { FFI::Pointer::NULL_HANDLE }
      it "raises a puppet error" do
        expect{ subject.service_start_type(mock_service_name) }.to raise_error(Puppet::Error)
      end
    end

    context "when the service can be opened" do

      # We need to guard this section explicitly since rspec will always
      # construct all examples, even if it isn't going to run them.
      if Puppet.features.microsoft_windows?
        {
          :SERVICE_AUTO_START => Puppet::Util::Windows::Service::SERVICE_AUTO_START,
          :SERVICE_BOOT_START => Puppet::Util::Windows::Service::SERVICE_BOOT_START,
          :SERVICE_SYSTEM_START => Puppet::Util::Windows::Service::SERVICE_SYSTEM_START,
          :SERVICE_DEMAND_START => Puppet::Util::Windows::Service::SERVICE_DEMAND_START,
          :SERVICE_DISABLED => Puppet::Util::Windows::Service::SERVICE_DISABLED,
        }.each do |start_type_name, start_type|
          it "queries the service and returns the service start type #{start_type_name}" do
            expect_successful_config_query_and_return({:dwStartType => start_type})
            expect(subject.service_start_type(mock_service_name)).to eq(start_type_name)
          end
        end
      end
      it "raises a puppet error if the service query fails" do
        subject.expects(:QueryServiceConfigW).in_sequence(status_checks)
        subject.expects(:QueryServiceConfigW).in_sequence(status_checks).returns(FFI::WIN32_FALSE)
        expect{ subject.service_start_type(mock_service_name) }.to raise_error(Puppet::Error)
      end
    end
  end

  describe "#set_startup_mode" do
    let(:status_checks) { sequence('status_checks') }

    context "when the service control manager cannot be opened" do
      let(:scm) { FFI::Pointer::NULL_HANDLE }
      it "raises a puppet error" do
        expect{ subject.set_startup_mode(mock_service_name, :SERVICE_DEMAND_START) }.to raise_error(Puppet::Error)
      end
    end

    context "when the service cannot be opened" do
      let(:service) { FFI::Pointer::NULL_HANDLE }
      it "raises a puppet error" do
        expect{ subject.set_startup_mode(mock_service_name, :SERVICE_DEMAND_START) }.to raise_error(Puppet::Error)
      end
    end

    context "when the service can be opened" do
      it "Raises an error on an unsuccessful change" do
        subject.expects(:ChangeServiceConfigW).returns(FFI::WIN32_FALSE)
        expect{ subject.set_startup_mode(mock_service_name, :SERVICE_DEMAND_START) }.to raise_error(Puppet::Error)
      end
    end
  end

  describe "#services" do
    let(:pointer_sequence) { sequence('pointer_sequence') }

    context "when the service control manager cannot be opened" do
      let(:scm) { FFI::Pointer::NULL_HANDLE }
      it "raises a puppet error" do
        expect{ subject.services }.to raise_error(Puppet::Error)
      end
    end

    context "when the service control manager is open" do
      let(:cursor) { [ 'svc1', 'svc2', 'svc3' ] }
      let(:svc1name_ptr) { mock() }
      let(:svc2name_ptr) { mock() }
      let(:svc3name_ptr) { mock() }
      let(:svc1displayname_ptr) { mock() }
      let(:svc2displayname_ptr) { mock() }
      let(:svc3displayname_ptr) { mock() }
      let(:svc1) { { :lpServiceName => svc1name_ptr, :lpDisplayName => svc1displayname_ptr, :ServiceStatusProcess => 'foo' } }
      let(:svc2) { { :lpServiceName => svc2name_ptr, :lpDisplayName => svc2displayname_ptr, :ServiceStatusProcess => 'foo' } }
      let(:svc3) { { :lpServiceName => svc3name_ptr, :lpDisplayName => svc3displayname_ptr, :ServiceStatusProcess => 'foo' } }

      it "Raises an error if EnumServicesStatusExW fails" do
        subject.expects(:EnumServicesStatusExW).in_sequence(pointer_sequence)
        subject.expects(:EnumServicesStatusExW).in_sequence(pointer_sequence).returns(FFI::WIN32_FALSE)
        expect{ subject.services }.to raise_error(Puppet::Error)
      end

      it "Reads the buffer using pointer arithmetic to create a hash of service entries" do
        # the first read_dword is for reading the bytes required, let that return 3 too.
        # the second read_dword will actually read the number of services returned
        pointer.expects(:read_dword).twice.returns(3)
        FFI::Pointer.expects(:new).with(subject::ENUM_SERVICE_STATUS_PROCESSW, pointer).returns(cursor)
        subject::ENUM_SERVICE_STATUS_PROCESSW.expects(:new).in_sequence(pointer_sequence).with('svc1').returns(svc1)
        subject::ENUM_SERVICE_STATUS_PROCESSW.expects(:new).in_sequence(pointer_sequence).with('svc2').returns(svc2)
        subject::ENUM_SERVICE_STATUS_PROCESSW.expects(:new).in_sequence(pointer_sequence).with('svc3').returns(svc3)
        svc1name_ptr.expects(:read_arbitrary_wide_string_up_to).returns('svc1')
        svc2name_ptr.expects(:read_arbitrary_wide_string_up_to).returns('svc2')
        svc3name_ptr.expects(:read_arbitrary_wide_string_up_to).returns('svc3')
        svc1displayname_ptr.expects(:read_arbitrary_wide_string_up_to).returns('service 1')
        svc2displayname_ptr.expects(:read_arbitrary_wide_string_up_to).returns('service 2')
        svc3displayname_ptr.expects(:read_arbitrary_wide_string_up_to).returns('service 3')
        expect(subject.services).to eq({
          'svc1' => { :display_name => 'service 1', :service_status_process => 'foo' },
          'svc2' => { :display_name => 'service 2', :service_status_process => 'foo' },
          'svc3' => { :display_name => 'service 3', :service_status_process => 'foo' }
        })
      end
    end
  end
end