2015-02-03 6 views
4

이것은 Rails 4.0.11에 있습니다. 나는 API와 상호 작용하는 작업자를 위해 minitest와 webmock을 사용하여 테스트를 작성하고있다. 테스트 파일에는 두 가지 테스트 케이스가 있습니다 (지금까지). 두 테스트를 모두 실행하면 두 번째 테스트 (제목에 "성공"이있는 테스트)가 실패합니다. 통과 테스트 (제목에 "재시도"가있는 테스트)를 주석 처리하면 실패한 테스트 케이스가 전달됩니다. 테스트 케이스가 서로 간섭하는 것 같지만 어떻게 보이지 않습니다. 하나의 테스트 케이스가 다른 테스트 케이스를 간섭하는 것 같습니다

여기 테스트입니다 (!. 나는 안녕 감독이 코드 예제에서 회사의 기밀 데이터를 난독 화 한) :

class FoocorpVipCheckStatusWorker 
    @queue = :short_running 

    # Foocorp VIP returns an order-level status code and description 
    # and a line-level status code and description. The comments describing 
    # the status codes in STATUS_CODE_MATRIX are from Foocorp's Docs. 
    # 
    # Array format for status codes is: 
    # ["(order-level status code)", "(line-level status code)"] 

    STATUS_CODE_MATRIX = { 
    :success => [ 
     ["00057", "00051"] # Request Processed Successfully 
    ], 
    :retry => [ 
     ["00057", "00053"], # No Status Yet 
     ["00057", "00054"], # Order processed successfully but activation is pending. 
     ["00099", ""],  # Unexpected error occurred during processing e.g. null pointer exception which causes thread to terminate. 
     ["00059", ""],  # Server time out occurred. 
     ["10009", ""],  # Back End call returned invalid agent data. 
     ["10010", ""],  # Application fails to load ECPD profile details. 
     ["00058", "10013"], # Backend calls fails to load Billing information for account. It may be due to some internal issue. 
     ["00058", "10032"], # Exception occurred in Bulk Service write 
     ["00058", "10033"], # Error occurred in Bulk Service write for reassign 
     ["00058", "10040"], # Sub Account create failed 
     ["00058", "10144"] # UNABLE TO RETRIEVE CREDIT INFORMATION 
    ] 
    } 

    def perform 

    ActivityProcessorStep.where(state: "waiting").where("vip_ref_num IS NOT NULL").each do |activity_processor_step| 

     client = Remote::Clients::FoocorpVipClient.new(
     :params => { 
      :ecpd_id  => activity_processor_step.activity.carrier_account.parent_account.api_access_id, 
      :vip_ref_num => activity_processor_step.vip_ref_num 
     } 
    ) 
     response = client.check_status 
     #TODO: Remove debugging code 
     #binding.pry 
     order_status_code = response.first[:order_status_code] 
     order_status_desc = response.first[:order_status_desc] 
     line_status_code = response.last[:line_status_code] 
     line_status_desc = response.last[:line_status_desc] 

     status_codes  = [order_status_code, line_status_code] 
     response_message = line_status_desc.present? ? line_status_desc : order_status_desc 
     response_message ||= "No status description given" 

     success    = STATUS_CODE_MATRIX[:success].detect{ |codes_array| codes_array == [order_status_code, line_status_code]}.present? 
     retry_status_check = STATUS_CODE_MATRIX[:retry].detect{ |codes_array| codes_array == [order_status_code, line_status_code]}.present? 
     stale_request  = retry_status_check && Time.now > (activity_processor_step.created_at + activity_processor_step.days_to_expire.days) 

     if success 
     activity_processor_step.update_activity_status('Complete', nil, nil, response_message) 
     elsif stale_request 
     activity_processor_step.update_activity_status('Failure', nil, nil, "Activity processor step expired.") 
     elsif !retry_status_check 
     activity_processor_step.update_activity_status('Failure', nil, nil, response_message) 
     end 

    end 
    end 
end 

가 여기 내 터미널의 : 여기

require 'test_helper' 

class FoocorpCheckStatusWorkerTest < ActiveSupport::TestCase 

    REQUEST_HEADERS = {'Accept'=>'*/*', 'Accept-Encoding'=>'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type'=>'text/xml', 'User-Agent'=>'Ruby'} 
    EXPECTED_BODY = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<POSBizServices xmlns=\"http://api.foocorp.com\">\n <POSBizServiceHeader>\n <userId>ABC</userId>\n <password>abc123</password>\n <clientId>123</clientId>\n <action>CHECKSTATUS</action>\n <responseFormat>XML</responseFormat>\n </POSBizServiceHeader>\n <request>\n <checkStatus>\n  <ecpdId>123</ecpdId>\n  <refNum>12345678</refNum>\n </checkStatus>\n </request>\n</POSBizServices>\n" 

    def sample_response_body(order_level_status_code: '', line_level_status_code: '') 

    return <<-SAMPLE_RESPONSE_BODY 
     <?xml version="1.0" encoding="UTF-8"?> 
     <POSBizServices xmlns="http://api.foocorp.com"> 
     <POSBizServiceHeader> 
      <userId>ABC</userId> 
      <password>abc123</password> 
      <clientId>123</clientId> 
      <statusCode>#{order_level_status_code}</statusCode> 
      <statusDescription>2015-01-29 14:03:07 [QA13:MS_WSQA4_ONEPOS_01:01] : Request Processed Successfully</statusDescription> 
      <action>CHECKSTATUS</action> 
      <responseFormat>XML</responseFormat> 
     </POSBizServiceHeader> 
     <response> 
      <statusResponse> 
      <count>1</count> 
      <orderStatus> 
       <orderId>12345678</orderId> 
       <orderDate>01/27/2015</orderDate> 
       <stats>1,0</stats> 
       <aceOrderNo></aceOrderNo> 
       <locationCode></locationCode> 
       <lineInfoList> 
       <count>1</count> 
       <lineStatus> 
        <lineSeq>1</lineSeq> 
        <statusCode>#{line_level_status_code}</statusCode> 
        <statusDesc>No Status Yet.</statusDesc> 
       </lineStatus> 
       </lineInfoList> 
      </orderStatus> 
      </statusResponse> 
     </response> 
     </POSBizServices> 
    SAMPLE_RESPONSE_BODY 
    end 

    test "retry codes leave activity processor step in waiting state and activity in auto_processing state" do 

    activity_processor_step = activity_processor_steps(:vip_vm_password_reset_step) 
    activity = activity_processor_step.activity 

    FoocorpVipCheckStatusWorker::STATUS_CODE_MATRIX[:retry].each do |status_code_pair| 

     stub_request(:post, FOOCORP_VIP_CONFIG[:base_url]). 
     with(:body => /^.*$/, 
      :headers => REQUEST_HEADERS 
      ). 
      to_return(:status => 200, :body => sample_response_body(order_level_status_code: status_code_pair.first, line_level_status_code: status_code_pair.last), :headers => {}) 

     FoocorpVipCheckStatusWorker.new.perform 

     activity.reload 
     assert_equal("auto_processing", activity.state) 

     activity_processor_step.reload 
     assert_equal("waiting", activity_processor_step.state) 

    end 
    end 

    test "success codes complete activity and activity processor step" do 

    activity_processor_step = activity_processor_steps(:vip_vm_password_reset_step) 
    activity = activity_processor_step.activity 

    FoocorpVipCheckStatusWorker::STATUS_CODE_MATRIX[:success].each do |status_code_pair| 

     stub_request(:post, FOOCORP_VIP_CONFIG[:base_url]). 
     with(:body => /^.*$/, 
      :headers => REQUEST_HEADERS 
      ). 
      to_return(:status => 200, :body => sample_response_body(order_level_status_code: status_code_pair.first, line_level_status_code: status_code_pair.last), :headers => {}) 

     FoocorpVipCheckStatusWorker.new.perform 

     activity.reload 
     assert_equal("completed", activity.state) 

     activity_processor_step.reload 
     assert_equal("completed", activity_processor_step.state) 
    end 
    end 
end 

작업자의 출력 :

두 테스트 사례 모두 실행 :

[email protected] ~/my-project (feature_foocorp_check_status_worker=)$ be rake test TEST=test/workers/foocorp_check_status_worker_test.rb 
Run options: --seed 58882 

# Running tests: 

.F 

Fabulous tests in 2.009658s, 0.9952 tests/s, 11.4447 assertions/s. 

    1) Failure: 
FoocorpCheckStatusWorkerTest#test_success_codes_complete_activity_and_activity_processor_step  [/Users/steven/Development/my-company/my_company/test/workers/foocorp_check_status_worker_test.rb:86]: 
Expected: "completed" 
    Actual: "auto_processing" 

2 tests, 23 assertions, 1 failures, 0 errors, 0 skips 

첫 번째 ("다시 시도") 테스트 케이스를 언급 :

[email protected] ~/my-project (feature_foocorp_check_status_worker=)$ be rake test TEST=test/workers/foocorp_check_status_worker_test.rb 
Run options: --seed 14937 

# Running tests: 

. 

Fabulous tests in 3.474386s, 0.2878 tests/s, 0.5756 assertions/s. 

1 tests, 2 assertions, 0 failures, 0 errors, 0 skips 

나는 함께 두 테스트를 실행하고 동안 response의 값을 검사하는 작업자에 (여기 주석) binding.pry를 사용하는 경우 "성공"테스트 케이스 (실패한 테스트 케이스)에서 다음 두 가지 결과를 얻습니다. 두 경우 모두 동일한 결과 (두 번째 것)를 기대합니다.

실행 모두 테스트 케이스 :

[1] pry(#<VerizonVipCheckStatusWorker>)> response 
=> [{:order_status_code=>"00057", 
    :order_status_desc=>"", 
    :_summary=>{:order_status_code=>"00057", :order_status_desc=>""}}, 
{:line_status_code=>"00053", 
    :line_status_desc=>"No Status Yet.", 
    :_summary=>{}}] 

첫 번째 ("다시 시도") 테스트 케이스를 언급 :

[2] pry(#<VerizonVipCheckStatusWorker>)> response 
=> [{:order_status_code=>"00057", 
    :order_status_desc=>"", 
    :_summary=>{:order_status_code=>"00057", :order_status_desc=>""}}, 
{:line_status_code=>"00051", 
    :line_status_desc=>"No Status Yet.", 
    :_summary=>{}}] 

마지막 예에서 응답의 값은 I가 그것을 기대하는 무엇인가 "재시도"테스트 케이스의 첫 번째 반복 동안 "성공"케이스가 아니라.

설치 방법을 상수로 이동하고 여기에 표시되는 sample_response_body 방법을 시도해 보았습니다. 나는이 분해 방법을 추가했지만, 그것은 도움이되지 않았다 : 나는 노동자와 처음부터 테스트를 모두 쓰고 있어요

def teardown 
    WebMock.reset! 
end 

, 그래서 내가 어딘가에 바보 같은 구문/논리 오류가 전적으로 가능하다. 아마도 지나치게 자세한 질문인데 죄송합니다. 그러나 이것은 정말로 저의 머리카락을 찢어지게합니다. 귀하의 도움을 주시면 감사하겠습니다. 감사.

답변

1

어댑터 클래스에서 응답을 캐싱하는 것으로 밝혀 졌으므로 WebMock에서 제공 한 응답을 무시했습니다.