> ## Documentation Index
> Fetch the complete documentation index at: https://docs.devinenterprise.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Esegui test E2E notturni in staging

export const UseCaseHero = ({title, description, prompt, category, features, devinUrl, agent, intent, playbookId, type}) => {
  const encodedPrompt = encodeURIComponent(prompt || '');
  const tag = 'docs-use-case-gallery';
  const utm = 'utm_source=docs&utm_medium=use-case-gallery&utm_campaign=hero-cta';
  const agentParams = (agent ? '&agent=' + agent : '') + (intent ? '&intent=' + intent : '') + (playbookId ? '&playbookId=' + playbookId : '');
  const devinHref = type === 'schedule' ? 'https://app.devin.ai/settings/schedules/create?' + utm + agentParams + (prompt ? '&prompt=' + encodedPrompt : '') : type === 'review' ? 'https://app.devin.ai/review?' + utm : agent === 'ada' ? 'https://app.devin.ai/search?' + utm + '&noSubmit=true' + (prompt ? '&prompt=' + encodedPrompt : '') : devinUrl ? devinUrl.includes('?') ? devinUrl + '&' + utm + agentParams : devinUrl + '?' + utm + agentParams : prompt ? 'https://app.devin.ai/?tags=' + tag + '&' + utm + agentParams + '&prompt=' + encodedPrompt : 'https://app.devin.ai/?' + utm + agentParams;
  const buttonLabel = type === 'schedule' ? 'Schedule in Devin ↗' : type === 'review' ? 'Set Up Devin Review ↗' : agent === 'advanced' ? 'Try in Devin ↗' : agent === 'dana' ? 'Try in Dana ↗' : agent === 'ada' ? 'Try in Ask Devin ↗' : 'Try in Devin ↗';
  const featureList = features ? features.split(',').map(f => f.trim()) : [];
  return <div className="uc-hero">
      <div className="uc-hero-inner">
        <div className="uc-hero-left">
          <h1 className="uc-hero-title">{title}</h1>
          <p className="uc-hero-desc">{description}</p>
          <div>
            <a href={devinHref} target="_blank" rel="noopener noreferrer" className="try-in-devin-btn">
              {buttonLabel}
            </a>
          </div>
        </div>
        <div className="uc-hero-meta">
          <div className="uc-meta-item">
            <span className="uc-meta-label">Author</span>
            <span className="uc-meta-value">Cognition</span>
          </div>
          <div className="uc-meta-item">
            <span className="uc-meta-label">Category</span>
            <span className="uc-meta-value">{category}</span>
          </div>
          {featureList.length > 0 && <div className="uc-meta-item">
              <span className="uc-meta-label">Features</span>
              <span className="uc-meta-value">{featureList.join(', ')}</span>
            </div>}
        </div>
      </div>
    </div>;
};

export const PromptBlock = ({children, type, agent, intent, playbookId}) => {
  var utm = 'utm_source=docs&utm_medium=use-case-gallery&utm_campaign=prompt-block';
  var tag = 'docs-use-case-gallery';
  var agentParams = (agent ? '&agent=' + agent : '') + (intent ? '&intent=' + intent : '') + (playbookId ? '&playbookId=' + playbookId : '');
  var label = type === 'schedule' ? 'Schedule in Devin' : type === 'playbook' ? 'Create Playbook' : type === 'knowledge' ? 'Add to Knowledge' : agent === 'advanced' ? 'Try in Devin' : agent === 'dana' ? 'Try in Dana' : agent === 'ada' ? 'Try in Ask Devin' : 'Try in Devin';
  var buildUrl = function (text) {
    var encoded = encodeURIComponent(text);
    if (type === 'schedule') return 'https://app.devin.ai/settings/schedules/create?' + utm + agentParams + '&prompt=' + encoded;
    if (type === 'playbook') return 'https://app.devin.ai/settings/playbooks/create?' + utm + '&body=' + encoded;
    if (type === 'knowledge') return 'https://app.devin.ai/knowledge?' + utm + '&body=' + encoded;
    if (agent === 'ada') return 'https://app.devin.ai/search?' + utm + '&noSubmit=true&prompt=' + encoded;
    return 'https://app.devin.ai/?tags=' + tag + '&' + utm + agentParams + '&prompt=' + encoded;
  };
  const ref = React.useRef(null);
  const [href, setHref] = React.useState('#');
  React.useEffect(() => {
    if (!ref.current) return;
    var codeEl = ref.current.querySelector('pre code');
    if (codeEl) {
      var text = codeEl.textContent.trim();
      if (text) setHref(buildUrl(text));
    }
    var header = ref.current.querySelector('[data-component-part="code-block-header"]');
    if (header && !header.querySelector('.prompt-block-devin-link')) {
      var link = document.createElement('a');
      link.href = href;
      link.target = '_blank';
      link.rel = 'noopener noreferrer';
      link.className = 'prompt-block-devin-link';
      link.style.cssText = 'display:inline-flex;align-items:center;gap:6px;text-decoration:none;color:#fff;font-size:11px;font-weight:500;padding:4px 10px;border-radius:6px;white-space:nowrap;background:#317CFF;transition:background 0.2s;margin-left:8px;';
      link.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg> ' + label;
      link.onmouseenter = function () {
        link.style.background = '#2968D9';
      };
      link.onmouseleave = function () {
        link.style.background = '#317CFF';
      };
      header.appendChild(link);
    }
    var existingLink = ref.current.querySelector('.prompt-block-devin-link');
    if (existingLink && href !== '#') existingLink.href = href;
  });
  return <div className="prompt-block" ref={ref}>{children}</div>;
};

<UseCaseHero title="Esegui test E2E notturni sull'ambiente di staging" description="Pianifica Devin perché esegua la tua suite di test end-to-end sull'ambiente di staging ogni notte e apra ticket per i test falliti." prompt="Aiutami a configurare una pianificazione notturna di Devin che esegua la nostra suite di test E2E sull'ambiente di staging. Segui la guida all'indirizzo https://docs.devin.ai/use-cases/gallery/api-scheduled-sessions e guidami in ogni passaggio: creazione di un utente di servizio, scrittura del playbook di test e creazione della pianificazione tramite le API." category="Automazioni" features="API, Pianificazioni, Playbook" />

<div className="uc-detail-wrapper">
  <Tip>Preferisci non configurare tutto manualmente? Incolla un collegamento a questa pagina in una sessione di Devin e chiedigli di configurare tutto per te.</Tip>

  Questa guida illustra come gestire le pianificazioni tramite le [API v3](/it/api-reference/v3/overview), utili per flussi di lavoro di automazione e infrastructure-as-code. È anche possibile creare e gestire le pianificazioni direttamente nell'[interfaccia utente di Devin](https://app.devin.ai/settings/schedules?utm_source=docs\&utm_medium=use-case-gallery) senza alcuna configurazione API.

  <Steps>
    <Step title="Configura un utente di servizio per l'accesso alle API">
      Le sessioni pianificate create tramite l'API richiedono un service user con le autorizzazioni appropriate. Ne configurerai uno una volta sola, quindi userai la sua API key in tutte le chiamate riportate di seguito.

      1. Vai su [app.devin.ai](https://app.devin.ai/?utm_source=docs\&utm_medium=use-case-gallery) > **Settings** > **Service Users** e fai clic su **Create Service User**
      2. Assegna un ruolo che includa l'autorizzazione `ManageOrgSchedules`
      3. Salva l'API key mostrata dopo la creazione — viene visualizzata una sola volta e la utilizzerai come token `Bearer`

      Per ottenere il tuo **organization ID**, chiama l'endpoint [List Organizations](/it/api-reference/v3/organizations/enterprise-organizations) con il token del tuo service user:

      ```bash theme={null}
      curl "https://api.devin.ai/v3/enterprise/organizations" \
        -H "Authorization: Bearer $DEVIN_API_KEY"
      ```

      Esporta entrambi i valori in modo che i comandi in questa guida funzionino senza modifiche:

      ```bash theme={null}
      export DEVIN_API_KEY="sk-your-service-user-key"
      export ORG_ID="your-org-id"
      ```

      Consulta la [documentazione sull'autenticazione delle API](/it/api-reference/authentication) per ulteriori informazioni sugli utenti di servizio e sulle autorizzazioni.
    </Step>

    <Step title="Crea un playbook per l'esecuzione del test">
      Prima di creare la pianificazione, scrivi un [playbook](/it/product-guides/creating-playbooks) che indichi a Devin esattamente come eseguire la tua suite E2E e cosa fare con i risultati. Vai su [**Settings > Playbooks**](https://app.devin.ai/settings/playbooks?utm_source=docs\&utm_medium=use-case-gallery) e crea un nuovo playbook — oppure chiedi a Devin di generarne uno per te a partire da una descrizione del tuo flusso di lavoro di test. Ecco un esempio per una suite Playwright:

      <PromptBlock type="playbook">
        ```txt Nightly E2E test playbook theme={null}
        You are running the nightly E2E test suite for acme/web-app against staging.

        Steps:
        1. Run the Playwright E2E suite targeting staging:
           `PLAYWRIGHT_BASE_URL=https://staging.acme.dev npx playwright test --reporter=json`
        2. Parse the JSON results. For each failing test:
           - Create a Linear ticket in the "QA" team with:
             - Title: "[Nightly E2E] <test name>"
             - Description: the full error message, stack trace, and the test file path
             - Label: "nightly-e2e-failure"
             - Priority: High if the test is in tests/critical/*, otherwise Medium
           - Attach any failure screenshots from the Playwright report
        3. If all tests pass, post a summary to the #qa-results Slack channel:
           "Nightly E2E: all <N> tests passed against staging (<date>)"
        4. If any tests fail, post to #qa-results:
           "Nightly E2E: <N> of <total> tests failed — <count> Linear tickets created"
           Include a list of the failing test names.
        ```
      </PromptBlock>

      Prendi nota dell'ID del playbook dopo averlo salvato: ti servirà per la chiamata all'API. Puoi trovarlo nell'URL quando visualizzi il playbook (`app.devin.ai/.../playbooks/{playbook_id}`).

      <Tip>Installa l'[integrazione Linear](/it/integrations/linear) in modo che Devin possa creare ticket come parte del playbook. Quando [crei la pianificazione](https://app.devin.ai/settings/schedules/create?utm_source=docs\&utm_medium=use-case-gallery), puoi anche impostare un **canale Slack** (ad esempio `#qa-results`) in modo che il tuo team riceva notifiche automatiche. Fornisci a Devin accesso in sola lettura ai secret del tuo ambiente di staging (URL del database, API key) tramite i [secret dell'organizzazione](/it/product-guides/secrets), se i tuoi test ne hanno bisogno.</Tip>
    </Step>

    <Step title="Crea la pianificazione notturna tramite l’API">
      Ora utilizza l'endpoint `POST /v3/organizations/{org_id}/schedules` per registrare la pianificazione. In questo esempio viene eseguito ogni notte alle 2:00 UTC:

      ```bash theme={null}
      curl -X POST "https://api.devin.ai/v3/organizations/$ORG_ID/schedules" \
        -H "Authorization: Bearer $DEVIN_API_KEY" \
        -H "Content-Type: application/json" \
        -d '{
          "title": "Nightly E2E — staging",
          "prompt": "Run the nightly E2E test suite against staging. Follow the playbook exactly.",
          "schedule_type": "recurring",
          "frequency": "0 2 * * *",
          "playbook_id": "your-playbook-id"
        }'
      ```

      La risposta include uno `schedule_id` che utilizzerai per gestire questa pianificazione in seguito. Salvalo:

      ```bash theme={null}
      export SCHEDULE_ID="a1b2c3d4-e5f6-7890-abcd-ef1234567890"  # dalla risposta
      ```

      Il campo `frequency` utilizza la sintassi cron standard. Alcune alternative utili:

      | Pattern       | Quando viene eseguito             |
      | ------------- | --------------------------------- |
      | `0 2 * * *`   | Ogni notte alle 2:00 UTC          |
      | `0 2 * * 1-5` | Solo nei giorni feriali (lun-ven) |
      | `0 6 * * 1`   | Ogni lunedì alle 6:00 UTC         |

      Perché le 2:00? Vuoi che i test vengano eseguiti dopo che l'ultimo deploy della giornata si è stabilizzato in staging, ma abbastanza presto perché eventuali errori siano visibili quando gli ingegneri iniziano a lavorare. Regola l'orario in base al fuso orario del tuo team e alla frequenza dei deploy.

      Consulta la [documentazione dell'endpoint Create schedule](/it/api-reference/v3/schedules/post-organizations-schedules) per tutti i campi disponibili.
    </Step>

    <Step title="Verifica la prima esecuzione e ottimizza il prompt">
      Dopo che la pianificazione è scattata per la prima volta, controlla la sessione per assicurarti che Devin abbia eseguito i test correttamente e che l’output corrisponda alle tue aspettative.

      1. Apri la dashboard di Devin e trova la sessione sotto **Past Sessions** — sarà etichettata con il nome della pianificazione
      2. La suite Playwright è stata eseguita? Sono stati creati ticket in Linear per i reali errori (non per i test instabili)?
      3. Controlla il canale Slack `#qa-results` per il messaggio di riepilogo

      Problemi comuni alla prima esecuzione e come risolverli:

      * **Devin non può accedere allo staging**: aggiungi le variabili d’ambiente dell’ambiente di staging (come `STAGING_API_KEY` o `DATABASE_URL`) come [segreti dell’organizzazione](/it/product-guides/secrets) in modo che siano disponibili in ogni sessione pianificata
      * **Troppi ticket dovuti a test instabili (flaky)**: aggiungi un retry al tuo playbook: "Esegui nuovamente qualsiasi test non superato una volta prima di aprire un ticket. Apri ticket solo per i test che falliscono due volte."
      * **I test richiedono troppo tempo**: limita l’ambito della suite — ad es., "Esegui solo i test in `tests/critical/` e `tests/smoke/`" — oppure aumenta il timeout della sessione

      <PromptBlock agent="advanced">
        ```txt Prompt tweak: filter out flaky tests theme={null}
        Aggiorna il playbook E2E notturno: prima di creare un ticket Linear per un test
        non superato, rieseguilo una volta con `npx playwright test <test-file> --retries=1`.
        Crea un ticket solo se il test fallisce nuovamente al retry. Aggiungi un'etichetta "flaky"
        a qualsiasi test che sia passato al retry e menzionalo nel riepilogo su Slack.
        ```
      </PromptBlock>
    </Step>

    <Step title="Gestisci le pianificazioni come codice">
      Una volta che l'esecuzione notturna è stabile, vorrai gestirla insieme alle altre pianificazioni — mettendola in pausa durante i periodi di blocco dei deploy, aggiornando il prompt quando la tua suite di test cambia o avviando una seconda pianificazione per un ambiente diverso.

      **Metti in pausa la pianificazione** durante un periodo di blocco dei deploy o una finestra di manutenzione:

      ```bash theme={null}
      curl -X PATCH "https://api.devin.ai/v3/organizations/$ORG_ID/schedules/$SCHEDULE_ID" \
        -H "Authorization: Bearer $DEVIN_API_KEY" \
        -H "Content-Type: application/json" \
        -d '{"enabled": false}'
      ```

      **Riattivala** quando termina il freeze:

      ```bash theme={null}
      curl -X PATCH "https://api.devin.ai/v3/organizations/$ORG_ID/schedules/$SCHEDULE_ID" \
        -H "Authorization: Bearer $DEVIN_API_KEY" \
        -H "Content-Type: application/json" \
        -d '{"enabled": true}'
      ```

      **Elenca tutte le pianificazioni** per controllare cosa è in esecuzione:

      ```bash theme={null}
      curl "https://api.devin.ai/v3/organizations/$ORG_ID/schedules" \
        -H "Authorization: Bearer $DEVIN_API_KEY"
      ```

      Per i team che gestiscono più pianificazioni, chiedete a Devin di creare una CLI che sincronizzi le definizioni di pianificazione da un file di configurazione YAML, così da poter versionare le pianificazioni insieme alla configurazione dei test:

      <PromptBlock>
        ```txt Schedules-as-code CLI theme={null}
        Write a Python script that reads schedule definitions from a file called
        devin-schedules.yaml and syncs them to the Devin API.

        The YAML file should look like:
          schedules:
            - title: "Nightly E2E — staging"
              prompt: "Run the nightly E2E suite against staging."
              frequency: "0 2 * * *"
              playbook_id: "a1b2c3d4e5f6789012345678"
            - title: "Nightly E2E — preview"
              prompt: "Run the E2E suite against the preview environment."
              frequency: "0 3 * * 1-5"
              playbook_id: "a1b2c3d4e5f6789012345678"

        The script should:
        1. Compare the YAML definitions against existing schedules from the API
        2. Create new schedules, update changed ones, and disable schedules
           removed from the file
        3. Support a --dry-run flag that shows what would change
        4. Use the endpoints at /v3/organizations/{org_id}/schedules
        ```
      </PromptBlock>
    </Step>
  </Steps>
</div>
