
    B              
          d Z ddlmZ ddlmZ ddlmZ ddlZddlmZ ddl	m
Z
 ddlmZ ddlmZ d	Zd
ZdZdZ G d d ej$                  dg d            ZdZdZdZdZdZededededediZd Z G d de      Zd Zd Zd Zd  Z d! Z!y)"z*A library to build a test results summary.    )absolute_import)division)unicode_literalsN)
exceptions)util)logzNative crashzFor test execution [{0}], a native process crashed on the device. This could be caused by your app, by an app dependency, or by an unrelated cause.zInfrastructure failurezNeed help for test execution [{0}]? Please join the #test-lab Slack channel at https://firebase.community/ and include test matrix ID [{1}] with your question.c                       e Zd ZdZy)TestOutcomea  A tuple to hold the outcome for a single test axis value.

  Fields:
    outcome: string containing the test outcome (e.g. 'Passed')
    axis_value: string representing one axis value within the matrix.
    test_details: string with extra details (e.g. "Incompatible architecture")
  N)__name__
__module____qualname____doc__     ;lib/googlecloudsdk/api_lib/firebase/test/results_summary.pyr
   r
   (   s    r   r
   outcome
axis_valuetest_detailsPassedFlakyFailedInconclusiveSkipped
         (   2   c                 h    t        t        | j                     | j                  | j                  g      S )zCTransform a TestOutcome to a tuple yielding the desired sort order.)tuple_OUTCOME_SORTINGr   r   r   )xs    r   _TestOutcomeSortKeyr$   E   s&    	 +Q^^Q\\J	KKr   c                   ^    e Zd ZdZd Zd Zd Zd Zd Zd Z	d Z
d	 Zd
 Zd Zd Zd Zd Zy)ToolResultsSummaryFetcherzACreates Test Results summary using data from the ToolResults API.c           
         || _         || _        || _        |j                  | _        |j
                  | _        || _        |j                  j                  j                  t        |j                  j                  j                  t        |j                  j                  j                  t        |j                  j                  j                   t"        |j                  j                  j$                  t&        i| _        y)a{  Constructs a ToolResultsSummaryFetcher.

    Args:
      project: string containing the GCE project id.
      client: ToolResults API client lib generated by apitools.
      messages: ToolResults API message classes generated by apitools.
      tool_results_ids: a ToolResultsIds object holding history & execution IDs.
      test_matrix_id: test matrix ID from Testing API.
    N)_project_client	_messages
history_id_history_idexecution_id_execution_id_test_matrix_idOutcomeSummaryValueValuesEnumsuccess_SUCCESSfailure_FAILUREflaky_FLAKYskipped_SKIPPEDinconclusive_INCONCLUSIVE_outcome_names)selfprojectclientmessagestool_results_idstest_matrix_ids         r   __init__z"ToolResultsSummaryFetcher.__init__M   s     DMDLDN'22D)66D)D//77//77//55v//77//<<mDr   c                 n   | j                   j                  | j                  | j                  | j                        }	 | j
                  j                  j                  |      }|j                  S # t        j                  $ r2}dt        j                  |      z   }t        j                  |      d}~ww xY w)a   Gets a test execution's rolled-up outcome from the ToolResults service.

    Returns:
      The rolled-up test execution outcome (type: toolresults_v1beta3.Outcome).

    Raises:
      HttpException if the ToolResults service reports a back-end error.
    )	projectId	historyIdexecutionIdz*Http error fetching test roll-up outcome: N)r*   0ToolresultsProjectsHistoriesExecutionsGetRequestr(   r,   r.   r)   projects_histories_executionsGetr   apitools_exceptions	HttpErrorr   GetErrorr   HttpException)r=   requestresponseerrormsgs        r   FetchMatrixRollupOutcomez2ToolResultsSummaryFetcher.FetchMatrixRollupOutcomef   s     nnMM--""&& N (G*;;??Hh(( *84==;OOc$$S))*s   0A/ /B4-B//B4c                    g }| j                         }|st        j                  d       |S |D ]  }|j                  }| j	                  |      }|j
                  s%t        j                  dj                  |             Q| j                  |      }| j                  ||       |j
                  j                  }| j                  |      }|j                  t        |||              t        |t              S )a  Fetches test results and creates a test outcome summary.

    Lists all the steps in an execution and creates a high-level outcome summary
    for each step (pass/fail/inconclusive). Each step represents a test run on
    a single device (e.g. running the tests on a Nexus 5 in portrait mode using
    the en locale and API level 18).

    Returns:
      A list of TestOutcome objects.

    Raises:
      HttpException if the ToolResults service reports a back-end error.
    zFNo test results found, something went wrong. Try re-running the tests.z$Step for [{0}] had no outcome value.r   key)_ListAllStepsr   warningdimensionValue_GetAxisValuer   format_GetStepOutcomeDetails_LogWarningssummary_GetOutcomeSummaryDisplayNameappendr
   sortedr$   )	r=   outcomesstepsstepdimension_valuer   detailsoutcome_summaryoutcome_strs	            r   $CreateMatrixOutcomeSummaryUsingStepsz>ToolResultsSummaryFetcher.CreateMatrixOutcomeSummaryUsingStepsz   s     H E	kk
R o++o%%o6j \\:AA*MN--d3':.,,..88I#%$&	' $ ( 344r   c                 X   g }| j                         }|s%t        j                  d       | j                         S |D ]  }|j                  }| j                  |      }|j                  j                  s6t        j                  dj                  |             | j                         c S | j                  |      }| j                  ||       |j                  j                  j                  }| j                  |      }|j                  t        |||              t        |t               S )a5  Fetches test results and creates a test outcome summary.

    Lists all the environments in an execution and creates a high-level outcome
    summary for each environment (pass/flaky/fail/skipped/inconclusive). Each
    environment represents a combination of one or more test executions with the
    same device configuration (e.g. running the tests on a Nexus 5 in portrait
    mode using the en locale and API level 18).

    Returns:
      A list of TestOutcome objects.

    Raises:
      HttpException if the ToolResults service reports a back-end error.
    zSEnvironment has no results, something went wrong. Displaying step outcomes instead.zMEnvironment for [{0}] had no outcome value. Displaying step outcomes instead.r   rU   )_ListAllEnvironmentsr   rX   ri   rY   rZ   environmentResultr   r[   _GetEnvironmentOutcomeDetailsr]   r^   r_   r`   r
   ra   r$   )	r=   rb   environmentsenvironmentre   r   rf   rg   rh   s	            r   +CreateMatrixOutcomeSummaryUsingEnvironmentszEToolResultsSummaryFetcher.CreateMatrixOutcomeSummaryUsingEnvironments   s    H,,.L 	kk 6688##22o%%o6j **22 --3VJ-?	A88::22;?g
,#55==EEo66Gkoo
!jwPQ $$ ( 344r   c                     t         |v r(t        j                  t        j	                  |             t
        |v r4t        j                  t        j	                  || j                               yy)zALog warnings if there was native crash or infrustructure failure.N)_NATIVE_CRASHr   rX   _NATIVE_CRASH_DETAILED_FORMATr[   _INFRASTRUCTURE_FAILURE'_INFRASTRUCTURE_FAILURE_DETAILED_FORMATr/   )r=   rf   r   s      r   r]   z&ToolResultsSummaryFetcher._LogWarnings   sT    	kk/66zBC')	kk
1
8
8$..01 *r   c           	          i }|D ]  }|j                   ||j                  <    dj                  |j                  dd      |j                  dd      |j                  dd      |j                  dd            S )Nz{m}-{v}-{l}-{o}Model?VersionLocaleOrientation)mvlo)valuerV   r[   get)r=   dimensionvalueaxes	dimensions       r   rZ   z'ToolResultsSummaryFetcher._GetAxisValue   ss    D#	%OOd9== $$$
((7C
 
((9c
"
((8S
!
((=#
&	 % ( )r   c                     | j                  d      }g }|j                  |j                         |j                  rC| j                  |j                        }|j                  |j                         |j                  rC|S )zLists all steps for a test execution using the ToolResults service.

    Returns:
      The full list of steps for a test execution.
    N)
_ListStepsextendrc   nextPageToken)r=   rP   rc   s      r   rW   z'ToolResultsSummaryFetcher._ListAllSteps   sf     t$HE	LL 

 
 !7!78hll8>>" 
 
  Lr   c                 Z   | j                   j                  | j                  | j                  | j                  d|      }	 | j
                  j                  j                  |      S # t        j                  $ r2}dt        j                  |      z   }t        j                  |      d}~ww xY w)ag  Lists one page of steps using the ToolResults service.

    Args:
      page_token: A page token to attach to the List request. If it's None, then
        it returns at most the first 200 steps.

    Returns:
      A ListStepsResponse containing a single page's steps.

    Raises:
      HttpException if the ToolResults service reports a back-end error.
    d   rE   rF   rG   pageSize	pageTokenz0Http error while listing test results of steps: N)r*   6ToolresultsProjectsHistoriesExecutionsStepsListRequestr(   r,   r.   r)   #projects_histories_executions_stepsListrK   rL   r   rM   r   rN   r=   
page_tokenrO   rQ   rR   s        r   r   z$ToolResultsSummaryFetcher._ListSteps   s     	MMmm&&**  	N 	" *\\==BB7KK(( *>
B c$$S))*    $A% %B*8-B%%B*c                     | j                  d      }g }|j                  |j                         |j                  rC| j                  |j                        }|j                  |j                         |j                  rC|S )zLists all environments of a test execution using the ToolResults service.

    Returns:
      A ListEnvironmentsResponse containing all environments within execution.
    N)_ListEnvironmentsr   rn   r   )r=   rP   rn   s      r   rk   z.ToolResultsSummaryFetcher._ListAllEnvironments  ss     %%d+HL--.

 
 ''(>(>?h(//0 
 
  r   c                 Z   | j                   j                  | j                  | j                  | j                  d|      }	 | j
                  j                  j                  |      S # t        j                  $ r2}dt        j                  |      z   }t        j                  |      d}~ww xY w)a~  Lists one page of environments using the ToolResults service.

    Args:
      page_token: A page token to attach to the List request. If it's None, then
        it returns a maximum of 200 Environments.

    Returns:
      A ListEnvironmentsResponse containing a single page's environments.

    Raises:
      HttpException if the ToolResults service reports a back-end error.
    r   r   z'Http error while listing test results: N)r*   =ToolresultsProjectsHistoriesExecutionsEnvironmentsListRequestr(   r,   r.   r)   *projects_histories_executions_environmentsr   rK   rL   r   rM   r   rN   r   s        r   r   z+ToolResultsSummaryFetcher._ListEnvironments  s     		F	Fmm&&**  
G 
" *\\DDII
 (( *5e8LLc$$S))*r   c                 @    	 | j                   |   S # t        $ r Y yw xY w)zTransforms the outcome enum to a human readable outcome.

    Args:
      outcome: An Outcome.SummaryValueValuesEnum value.

    Returns:
      A string containing a human readable outcome.
    Unknown)r<   
ValueError)r=   r   s     r   r_   z7ToolResultsSummaryFetcher._GetOutcomeSummaryDisplayName<  s*      )) s    	c                 h   |j                   }| j                  j                  j                  }|j                  j
                  }|j                  |j                  k(  rFt        |      }|j                  r-|j                  j                  rdj                  |t              S |S |j                  |j                  k(  r0|j                  rt        ||      S |j                  syt!        |      S |j                  |j"                  k(  rt%        |      S |j                  |j&                  k(  rt)        |      S y)CTurn test outcome counts and details into something human readable.	{d} ({c})dczUnknown failureUnknown outcome)r   r*   r0   r1   testExecutionSteptestSuiteOverviewsr^   r2   _GetSuccessCountDetailssuccessDetailotherNativeCrashr[   rr   r4   failureDetail_GetFailureDetail_GetFailureOrFlakyCountDetailsr:   _GetInconclusiveDetailr8   _GetSkippedDetail)r=   rd   r   summary_enumtest_suite_overviewsrf   s         r   r\   z0ToolResultsSummaryFetcher._GetStepOutcomeDetailsJ  s   llG>>))@@L11DD,...'(<=g			7#8#8#I#I!!G}!==	L00	0			 *>??## +,@AA	L55	5#G,,	L00	0w'' r   c                    |j                   j                  }| j                  j                  j                  }|j                   j
                  }|j                  |j                  k(  rFt        |      }|j                  r-|j                  j                  rdj                  |t              S |S |j                  |j                  k(  s|j                  |j                  k(  r#|j                  rt!        ||      S t#        |      S |j                  |j$                  k(  rt'        |      S |j                  |j(                  k(  rt+        |      S y)r   r   r   r   )rl   r   r*   r0   r1   r   r^   r2   r   r   r   r[   rr   r4   r6   r   r   r   r:   r   r8   r   )r=   ro   r   r   r   rf   s         r   rm   z7ToolResultsSummaryFetcher._GetEnvironmentOutcomeDetailsg  s   ++33G>>))@@L&88KK,...'(<=g			7#8#8#I#I!!G}!==	L00	0GOO|GYGY4Y			 *>??+,@AA	L55	5#G,,	L00	0w'' r   N)r   r   r   r   rC   rS   ri   rp   r]   rZ   rW   r   rk   r   r_   r\   rm   r   r   r   r&   r&   J   sH    I2*((5T+5Z1) *6 *::r   r&   c                 *   d}| j                   j                  rd}n1| j                   j                  rd}n| j                   j                  rd}| j                   j                  rt
        nd}|r|rdj                  ||      S |r|S |r|S t        |      S )z-Build a string with failureDetail if present. zApplication crashedzTest timed outzApp failed to installr   r   )r   crashedtimedOutnotInstalledr   rr   r[   r   )r   r   rf   crashs       r   r   r     s    '""#G%%G))%G"00AA-r%511NL	'(<	==r   c                     | j                   rF| j                   j                  ry| j                   j                  r	 y| j                   j                  ryy)z-Build a string with skippedDetail if present.z"Incompatible device/OS combinationzGApp architecture or requested options are incompatible with this devicez#App does not support the OS versionUnknown reason)skippedDetailincompatibleDeviceincompatibleArchitectureincompatibleAppVersionr   s    r   r   r     sM    //155 332	r   c                     | j                   r3| j                   j                  rt        S | j                   j                  ryy)z2Build a string with inconclusiveDetail if present.zTest run aborted by userr   )inconclusiveDetailinfrastructureFailurert   abortedByUserr   s    r   r   r     s5    !!77$$!!//'	r   c                     d}d}| D ](  }||j                   xs dz  }||j                  xs dz  }* ||z
  }|r)dj                  |      }|rdj                  ||      }|S y)=Build a string with status count sums for testSuiteOverviews.r   z{p} test cases passed)p{m}, {s} skippedr|   sz--)
totalCountskippedCountr[   )r   totalr8   overviewpassedrR   s         r   r   r     s    
%'&h	X  %A%Ex$$))G ' 7?&
!
(
(6
(
2C%%w%7cJ	r   c                    d}d}d}d}d}| D ]a  }||j                   xs dz  }||j                  xs dz  }||j                  xs dz  }||j                  xs dz  }||j                  xs dz  }c |rdj                  |      }||z
  |z
  |z
  |z
  }|r|rdj                  ||      }|r|sdj                  |      }|rdj                  ||      }|rd	j                  ||
      }|rdj                  ||      }|S y)r   r   z{f} test cases failed)fz{m}, {f} flaky)r|   r   z{f} test cases flakyz{m}, {p} passed)r|   r   z{m}, {e} errors)r|   er   r   zTest failed to run)r   
errorCountfailureCountr   
flakyCountr[   )	r   r   rQ   failedr8   r6   r   rR   r   s	            r   r   r     s@   
%
%&'
%&h	X  %A%E	X  %A%E
h##(q(Fx$$))G	X  %A%E ' 
!
(
(6
(
2CU]V#g-5F##cU#3cV"))E)2c$$sf$5c$$se$4c%%w%7cJr   )"r   
__future__r   r   r   collectionsapitools.base.pyr   rK   $googlecloudsdk.api_lib.firebase.testr   googlecloudsdk.calliopegooglecloudsdk.corer   rr   rs   rt   ru   
namedtupler
   r3   r7   r5   r;   r9   r"   r$   objectr&   r   r   r   r   r   r   r   r   <module>r      s    1 &  '  > 5 . #!J  3 + '	K=DF	 	 b
Bb2b L
v vr	>*  r   