
    !8                         d Z ddlmZ ddlmZ ddlmZ ddl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dlmZ dd
lmZ ddlZd Z G d de      Zy)z2Create Android test matrices in Firebase Test Lab.    )absolute_import)division)unicode_literalsN)
exceptions)matrix_creator_common)
matrix_ops)util)logc                 z    t        | ||||      }|j                  t        j                         j                        S )a  Creates a new matrix test in Firebase Test Lab from the user's params.

  Args:
    args: an argparse namespace. All the arguments that were provided to this
      gcloud command invocation (i.e. group and command arguments combined).
    context: {str:obj} dict containing the gcloud command context, which
      includes the Testing API client+messages libs generated by Apitools.
    history_id: {str} A history ID to publish Tool Results to.
    gcs_results_root: the root dir for a matrix within the GCS results bucket.
    release_track: the release track that the command is invoked from.

  Returns:
    A TestMatrix object created from the supplied matrix configuration values.
  )MatrixCreatorCreateTestMatrixuuiduuid4hex)argscontext
history_idgcs_results_rootrelease_trackcreators         Blib/googlecloudsdk/api_lib/firebase/test/android/matrix_creator.pyCreateMatrixr   #   s7     $5E')'		!	!$**,"2"2	33    c                   v    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d Zd Zd Zd Zy)r   zCCreates a single test matrix based on user-supplied test arguments.c                     t        j                         | _        || _        || _        || _        |d   | _        |d   | _        || _        y)af  Construct a MatrixCreator to be used to create a single test matrix.

    Args:
      args: an argparse namespace. All the arguments that were provided to this
        gcloud command invocation (i.e. group and command arguments combined).
      context: {str:obj} dict containing the gcloud command context, which
        includes the Testing API client+messages libs generated by Apitools.
      history_id: {str} A history ID to publish Tool Results to.
      gcs_results_root: the root dir for a matrix within the GCS results bucket.
      release_track: the release track that the command is invoked from.
    testing_clienttesting_messagesN)	r	   
GetProject_project_args_history_id_gcs_results_root_client	_messages_release_track)selfr   r   r   r   r   s         r   __init__zMatrixCreator.__init__:   sK     OO%DMDJ!D-D+,DL/0DN'Dr   c                    |j                  d      rJd| j                  j                  | j                  t        j
                  j                  |                  fS | j                  t        j
                  j                  |            dfS )zABuilds either a FileReference or an AppBundle message for a file.z.aabN)bundleLocation)endswithr$   	AppBundle_BuildFileReferenceospathbasenamer&   filenames     r   _BuildAppReferencez MatrixCreator._BuildAppReferenceO   sz     4>>++11"''2B2B82LM , O O O %%bgg&6&6x&@A4GGr   c                     | j                   j                  t        j                  j	                  | j
                  |            S )z9Build a FileReference pointing to the GCS copy of a file.gcsPath)r$   FileReferencer-   r.   joinr"   r0   s     r   r,   z!MatrixCreator._BuildFileReferenceW   s8    >>''T33X> ( @ @r   c                     | j                   j                  j                  }| j                  j                  |j
                  S | j                  j                  r|j                  S |j                  S )N)r$   AndroidInstrumentationTest!OrchestratorOptionValueValuesEnumr    use_orchestratorORCHESTRATOR_OPTION_UNSPECIFIEDUSE_ORCHESTRATORDO_NOT_USE_ORCHESTRATOR)r&   orchestrator_optionss     r   _GetOrchestratorOptionz$MatrixCreator._GetOrchestratorOption\   s]    11	*	*  zz""*!AAA		$	$!222!999r   c           
      |   g }| j                   j                  j                  }|j                  |j                  |j
                  d}t        j                  |xs i       D ]Y  \  }}t        j                  |      \  }}|j                  | j                   j                  |||j                  |                   [ |S )z9Build a list of RoboDirectives from the dictionary input.)clicktextignore)resourceName	inputText
actionType)r$   RoboDirectiveActionTypeValueValuesEnumSINGLE_CLICK
ENTER_TEXTIGNOREsix	iteritemsr	   ParseRoboDirectiveKeyappendget)	r&   robo_directives_dictrobo_directivesaction_typesaction_type_mappingkeyvalueaction_typeresource_names	            r   _BuildRoboDirectivesz"MatrixCreator._BuildRoboDirectivesg   s    O>>//IIL**''%%
 mm%9%?RA
U%)%?%?%D"{M
..
&
&(,00= ' ?@ B r   c                 (   | j                         }| j                  | j                  j                        \  }}| j                  j                  ||| j                  t        j                  j                  | j                  j                              | j                  j                  | j                  j                  | j                  j                  | j                  j                  xs g | j                         | j!                         	      |_        |S )z<Build a TestSpecification for an AndroidInstrumentationTest.)	appApk	appBundletestApkappPackageIdtestPackageIdtestRunnerClasstestTargetsorchestratorOptionshardingOption)_BuildGenericTestSpecr2   r    appr$   r9   r,   r-   r.   r/   testapp_packagetest_packagetest_runner_classtest_targetsr@   _BuildShardingOptionandroidInstrumentationTestr&   specapp_apk
app_bundles       r   $_BuildAndroidInstrumentationTestSpecz2MatrixCreator._BuildAndroidInstrumentationTestSpecy   s    %%'D11$**..AGZ&*nn&O&O(()9)9$**//)JKZZ++jj--

44ZZ,,2668002 'P 	'4D# Kr   c                    | j                         }| j                  | j                  j                        \  }}| j                  j
                  j                  }t        | j                  dd      r|j                  n|j                  }| j                  j                  ||| j                  j                  | j                  | j                  j                        |      |_        t        | j                  dd      rQ| j                  t        j                   j#                  | j                  j$                              |j                  _        |S )z1Build a TestSpecification for an AndroidRoboTest.resignT)r\   r]   r_   roboDirectivesroboModerobo_scriptN)re   r2   r    rf   r$   AndroidRoboTestRoboModeValueValuesEnumgetattrROBO_VERSION_2ROBO_VERSION_1rh   rZ   rS   androidRoboTestr,   r-   r.   r/   rw   
roboScript)r&   ro   rp   rq   
robo_modes	robo_modes         r   _BuildAndroidRoboTestSpecz'MatrixCreator._BuildAndroidRoboTestSpec   s   %%'D11$**..AGZ//GGJ-4

Hd.$
)))3)B)B >>99ZZ++001K1KL : D tzz=$/(,(@(@
''

4::11
2)4d%Kr   c                    | j                         }| j                  | j                  j                        \  }}| j                  j                  ||| j                  j                        |_        | j                  j                  r%| j                  j                  |j                  _	        | j                  j                  r%| j                  j                  |j                  _        |S )z1Build a TestSpecification for an AndroidTestLoop.)r\   r]   r_   )re   r2   r    rf   r$   AndroidTestLooprh   androidTestLoopscenario_numbers	scenariosscenario_labelsscenarioLabelsrn   s       r   _BuildAndroidGameLoopTestSpecz+MatrixCreator._BuildAndroidGameLoopTestSpec   s    %%'D11$**..AGZ>>99ZZ++ : -D zz""'+zz'B'Bd$zz!!,0JJ,F,Fd)Kr   c                 |   g }| j                   j                  xs g D ]v  }t        j                  j	                  |      }|j                  | j                  j                  | j                  j                  || j                  |                         x t        | j                   dd      xs i }|j                         D ]j  }|j                  | j                  j                  | j                  j                  | j                  t        j                  |            |                   l g }| j                   j                  r]t!        j"                  | j                   j                        D ]1  \  }}|j                  | j                  j%                  ||             3 | j                   j&                  xs g }	d}
| j                   j(                  r4| j                  j+                  | j                  j-                               }
t        | j                   d	g       xs g D cg c]J  }| j                  j/                  | j                  t        j                  j	                  |            
      L }}t        | j                   dd      dk(  }| j                  j1                  ||
||	t        | j                   dd      ||       }| j                  j3                  t5        j6                  | j                   j8                        || j                   j:                   | j                   j<                         S c c}w )z>Build a generic TestSpecification without test-type specifics.)obbFileNameobb)obbFileother_filesN)content
devicePath)regularFile)rV   rW   )
googleAutoadditional_apks)locationgrant_permissionsallnetwork_profile)filesToPushaccountenvironmentVariablesdirectoriesToPullnetworkProfileadditionalApksdontAutograntPermissions)testTimeout	testSetupdisableVideoRecordingdisablePerformanceMetrics)r    	obb_filesr-   r.   r/   rP   r$   
DeviceFileObbFiler,   rz   keysRegularFiler	   GetRelativeDevicePathenvironment_variablesrM   rN   EnvironmentVariabledirectories_to_pullauto_google_loginAccount
GoogleAutoApk	TestSetupTestSpecificationr   ReformatDurationtimeoutrecord_videoperformance_metrics)r&   device_filesobb_fileobb_file_namer   device_pathr   rV   rW   r   r   additional_apkr   r   setups                  r   re   z#MatrixCreator._BuildGenericTestSpec   s   LJJ((.B.gg&&x0m
..
#
#nn,,+..}= - ? $ @A / $**mT:@bK"'')
..
#
#..442200=?( 5 * $ +, * zz''djj&F&FG*#u$$NN..3e.D	F H **88>BGzz##&&$..2K2K2M&Ng
 &djj2CRHNBN ON 	--bgg.>.>~.NO 	 	QN    

,? %'*/0 NN$$ 2-tzz+<dC&%6!6 % 8E >>++//

0B0BC"&**"9"99&*jj&D&D"D	 , F F%s   &AL9c                 r   t        | j                  di       rJ| j                  j                  | j                  j	                  | j                  j
                              S t        | j                  di       r?| j                  j                  | j                  | j                  j                              S y)z9Build a ShardingOption for an AndroidInstrumentationTest.num_uniform_shards)	numShards)uniformShardingtest_targets_for_shard)manualShardingN)rz   r    r$   ShardingOptionUniformShardingr   _BuildManualShardr   )r&   s    r   rl   z"MatrixCreator._BuildShardingOption   s    tzz/4^^**..88

55 9 7 + 8 8 
5r	:^^**//jj//1 + 2 2 
;r   c                     |D cg c]  }| j                  |       }}| j                  j                  |      S c c}w )z)Build a ManualShard for a ShardingOption.)testTargetsForShard)_BuildTestTargetsForShardr$   ManualSharding)r&   r   test_targetrk   s       r   r   zMatrixCreator._BuildManualShard   sN     21K 	&&{31   >>((\(JJ	s   ;c                     | j                   j                  |j                  d      D cg c]  }|| c}      S c c}w )N;)rb   )r$   TestTargetsForShardsplit)r&   test_targets_for_each_shardtargets      r   r   z'MatrixCreator._BuildTestTargetsForShard   sM    >>--8>>sC;C6 	C;-   ;s   <c                     |dk(  r| j                         S |dk(  r| j                         S |dk(  r| j                         S t        j                  ddj                  |            )zAMap a test type into its corresponding TestSpecification message.instrumentationroboz	game-looptypezUnknown test type "{}".)rr   r   r   r   InvalidArgumentExceptionformat)r&   	test_types     r   _TestSpecFromTypezMatrixCreator._TestSpecFromType   sl    %%6688	f	++--	k	!//11//
+229=? ?r   c                    | j                   j                  ri| j                   j                  D cg c]  }| j                  |       }}| j                  j	                  | j                  j                  |            }n| j                  j	                  | j                  j                  | j                   j                  | j                   j                  | j                   j                  | j                   j                              }| j                  j                  | j                        }| j                  j                  | j                  | j                        }| j                  j!                  ||      }t#        j$                  | j                  t'        | j                   di       xs i | j(                        }| j                  j+                  ||||| j                   j,                  xs d	
      S c c}w )zBuild just the user-specified parts of a TestMatrix message.

    Args:
      spec: a TestSpecification message corresponding to the test type.

    Returns:
      A TestMatrix message.
    )androidDevices)androidDeviceList)androidModelIdsandroidVersionIdslocalesorientations)androidMatrixr4   )	projectId	historyId)googleCloudStoragetoolResultsHistoryclient_detailsr   )testSpecificationenvironmentMatrix
clientInforesultStorageflakyTestAttempts)r    device_BuildAndroidDevicer$   EnvironmentMatrixAndroidDeviceListAndroidMatrix
device_idsos_version_idsr   r   GoogleCloudStorager"   ToolResultsHistoryr   r!   ResultStorager   BuildClientInforz   r%   
TestMatrixnum_flaky_test_attempts)	r&   ro   ddevicesenvironment_matrixgcshistresultsclient_infos	            r   _BuildTestMatrixzMatrixCreator._BuildTestMatrix  s    zz6:jj6G6GH6G))!,6GgH>>;; NN<<$ = & < '  >>;;44"jj33 $

 9 9jj((::22	 5 4 < 5 ..
+
+D4J4J
+
KC>>,,t}}7;7G7G - IDnn**c>B + DG (77

,b17R9L9LNK >>$$,**<<A % C C- Is   G9c                 X    | j                   j                  |d   |d   |d   |d         S )Nmodelversionlocaleorientation)androidModelIdandroidVersionIdr  r  )r$   AndroidDevice)r&   
device_maps     r   r   z!MatrixCreator._BuildAndroidDevice+  s>    >>''!'*#I.(#}-	 ( / /r   c                     | j                  | j                  j                        }| j                  j	                  | j
                  | j                  |      |      S )zBuild a TestingProjectsTestMatricesCreateRequest for a test matrix.

    Args:
      request_id: {str} a unique ID for the CreateTestMatrixRequest.

    Returns:
      A TestingProjectsTestMatricesCreateRequest message.
    )r   
testMatrix	requestId)r   r    r   r$   (TestingProjectsTestMatricesCreateRequestr   r   )r&   
request_idro   s      r   _BuildTestMatrixRequestz%MatrixCreator._BuildTestMatrixRequest2  sQ     !!$**//2D>>BB--((. C  r   c                    | j                  |      }t        j                  dj                  |             	 | j                  j
                  j                  |      }t        j                  dj                  |             t        j                  j                  dj                  |j                               |S # t        j                  $ r2}dt        j                  |      z   }t        j                  |      d}~ww xY w)a>  Invoke the Testing service to create a test matrix from the user's args.

    Args:
      request_id: {str} a unique ID for the CreateTestMatrixRequest.

    Returns:
      The TestMatrix response message from the TestMatrices.Create rpc.

    Raises:
      HttpException if the test service reports an HttpError.
    z!TestMatrices.Create request:
{0}
z"TestMatrices.Create response:
{0}
z'Http error while creating test matrix: Nz1Test [{id}] has been created in the Google Cloud.)id)r  r
   debugr   r#   projects_testMatricesCreateapitools_exceptions	HttpErrorr	   GetErrorr   HttpExceptionstatusPrinttestMatrixId)r&   r  requestresponseerrormsgs         r   r   zMatrixCreator.CreateTestMatrixA  s     **:6GII3::7CD*33::7Ch	ii6==hGH
 JJHf 5 5f68O (( *5e8LLc$$S))*s   A	B; ;D -C;;D N)__name__
__module____qualname____doc__r'   r2   r,   r@   rZ   rr   r   r   re   rl   r   r   r   r   r   r  r    r   r   r   r   7   sa    K(*H@
	:$ $4Fl	2K
?%CN/r   r   )r!  
__future__r   r   r   r-   r   apitools.base.pyr   r  $googlecloudsdk.api_lib.firebase.testr   r   r	   googlecloudsdk.calliopegooglecloudsdk.corer
   rM   r   objectr   r"  r   r   <module>r)     sA     9 &  ' 	  > F ; 5 . # 
4(aF ar   