text:
.. _finalize-obs:

Finalize installation for openSUSE and SUSE Linux Enterprise
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. note::

   Default configuration files vary by distribution. You might need
   to add these sections and options rather than modifying existing
   sections and options. Also, an ellipsis (``...``) in the configuration
   snippets indicates potential default configuration options that you
   should retain.

This section applies to openSUSE Leap 42.2 and SUSE Linux Enterprise Server
12 SP2.

#. Edit the ``/etc/swift/swift.conf`` file and complete the following
   actions:

   * In the ``[swift-hash]`` section, configure the hash path prefix and
     suffix for your environment.

     .. code-block:: none

        [swift-hash]
        ...
        swift_hash_path_suffix = HASH_PATH_SUFFIX
        swift_hash_path_prefix = HASH_PATH_PREFIX

     Replace HASH_PATH_PREFIX and HASH_PATH_SUFFIX with unique values.

     .. warning::

        Keep these values secret and do not change or lose them.

   * In the ``[storage-policy:0]`` section, configure the default
     storage policy:

     .. code-block:: none

        [storage-policy:0]
        ...
        name = Policy-0
        default = yes

#. Copy the ``swift.conf`` file to the ``/etc/swift`` directory on
   each storage node and any additional nodes running the proxy service.

3. On all nodes, ensure proper ownership of the configuration directory:

   .. code-block:: console

      # chown -R root:swift /etc/swift

4. On the controller node and any other nodes running the proxy service,
   start the Object Storage proxy service including its dependencies and
   configure them to start when the system boots:

   .. code-block:: console

      # systemctl enable openstack-swift-proxy.service memcached.service
      # systemctl start openstack-swift-proxy.service memcached.service

5. On the storage nodes, start the Object Storage services and configure
   them to start when the system boots:

   .. code-block:: console

      # systemctl enable openstack-swift-account.service openstack-swift-account-auditor.service \
        openstack-swift-account-reaper.service openstack-swift-account-replicator.service
      # systemctl start openstack-swift-account.service openstack-swift-account-auditor.service \
        openstack-swift-account-reaper.service openstack-swift-account-replicator.service
      # systemctl enable openstack-swift-container.service openstack-swift-container-auditor.service \
        openstack-swift-container-replicator.service openstack-swift-container-updater.service
      # systemctl start openstack-swift-container.service openstack-swift-container-auditor.service \
        openstack-swift-container-replicator.service openstack-swift-container-updater.service
      # systemctl enable openstack-swift-object.service openstack-swift-object-auditor.service \
        openstack-swift-object-replicator.service openstack-swift-object-updater.service
      # systemctl start openstack-swift-object.service openstack-swift-object-auditor.service \
        openstack-swift-object-replicator.service openstack-swift-object-updater.service


text:
enduro_admin_app.factory('modal_service', function modal_service ($rootScope, $q) {
	var modal_service = {}

	modal_service.close = function () {
		$('body').removeClass('modal-open')
		$rootScope.modal = ''
	}

	modal_service.open = function (modal_name) {
		return $q(function (resolve, reject) {

			var modal_fullpath = '/admin/modals/' + modal_name + '/index.html'

			$rootScope.modal = modal_fullpath
			$rootScope.$on('$includeContentLoaded', function (event, template_name) {
				if (template_name == modal_fullpath) {
					resolve()
				}
			})
		})
	}

	return modal_service
})

redpajama_set_name: RedPajamaGithub


text:
from context import photobox
from unittest import TestCase
from photobox.folder import Folder
from test_photofolder import MockFolder

class TestFolder(TestCase):
    def test_getextension_shouldreturn_thecorrectextension(self):
        folder = Folder(MockFolder([]))
        self.assertEqual(".png", folder.getextension("photo.png"))

    def test_getfilename(self):
        folder = Folder(MockFolder([]))
        self.assertEqual("photo", folder.getfilename("photo.png"))


text:
pub mod compress;
pub mod exception;
pub mod file;
pub mod file_upload;
pub mod filesystem;
pub mod index;
pub mod mkdir;
pub mod proxy;

pub use exception::notfound_handler;
pub use filesystem::fs_handler;
pub use proxy::{method_maybe_proxy, proxy_handler};


text:
CREATE TABLE "accounts" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "ancestry" varchar(255), "name" varchar(255), "created_at" datetime, "updated_at" datetime, "type" varchar(255));
CREATE TABLE "contacts" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "self" boolean DEFAULT 'f', "name" varchar(255), "contact_name" varchar(255), "address" text, "city" varchar(255), "state" varchar(255), "postal_code" varchar(255), "country" varchar(255), "country_code" varchar(2), "tax_number" varchar(255), "created_at" datetime, "updated_at" datetime, "email" varchar(255), "phone_number" varchar(255));
CREATE TABLE "delayed_jobs" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "priority" integer DEFAULT 0, "attempts" integer DEFAULT 0, "handler" text, "last_error" text, "run_at" datetime, "locked_at" datetime, "failed_at" datetime, "locked_by" varchar(255), "created_at" datetime, "updated_at" datetime);
CREATE TABLE "exchange_rates" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "currency" varchar(255), "rate" decimal(20,4), "recorded_on" date);
CREATE TABLE "imports" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "account_id" integer, "file_name" varchar(255), "message" varchar(255), "status" varchar(255), "created_at" datetime, "updated_at" datetime, "mapping_id" integer, "ending_balance" decimal(20,4));
CREATE TABLE "ledger_items" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "sender_id" integer, "recipient_id" integer, "transacted_on" date, "total_amount" decimal, "tax_amount" decimal DEFAULT 0.0, "currency" varchar(3) NOT NULL, "description" varchar(255), "account_id" integer, "match_id" integer, "created_at" datetime, "updated_at" datetime);
CREATE TABLE "mappings" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "name" varchar(255), "currency" varchar(3), "date_row" integer, "total_amount_row" integer, "tax_amount_row" integer, "description_row" integer, "second_description_row" integer, "has_title_row" boolean, "day_follows_month" boolean, "reverses_sign" boolean, "created_at" datetime, "updated_at" datetime);
CREATE TABLE "matches" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "created_at" datetime, "updated_at" datetime);
CREATE TABLE "people" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "is_self" boolean DEFAULT 'f', "name" varchar(255), "contact_name" varchar(255), "address" text, "city" varchar(255), "state" varchar(255), "postal_code" varchar(255), "country" varchar(255), "country_code" varchar(2), "tax_number" varchar(255), "created_at" datetime, "updated_at" datetime);
CREATE TABLE "rules" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "new_sender_id" integer, "new_recipient_id" integer, "account_id" integer, "new_account_id" integer, "matched_description" varchar(255), "matched_debit" boolean, "created_at" datetime, "updated_at" datetime, "matched_sender_id" integer, "matched_recipient_id" integer);
CREATE TABLE "schema_migrations" ("version" varchar(255) NOT NULL);
CREATE TABLE "sessions" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "session_id" varchar(255) NOT NULL, "data" text, "created_at" datetime, "updated_at" datetime);
CREATE TABLE "transactions" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "sender_id" integer, "recipient_id" integer, "issued_on" date, "total_amount" decimal(20,4), "tax_amount" decimal(20,4), "currency" varchar(3) NOT NULL, "description" varchar(255), "identifier" varchar(255), "account_id" integer, "match_id" integer, "created_at" datetime, "updated_at" datetime);
CREATE TABLE "users" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "login" varchar(255) NOT NULL, "email" varchar(255) NOT NULL, "crypted_password" varchar(255) NOT NULL, "password_salt" varchar(255) NOT NULL, "persistence_token" varchar(255) NOT NULL, "single_access_token" varchar(255) NOT NULL, "perishable_token" varchar(255) NOT NULL, "login_count" integer DEFAULT 0 NOT NULL, "failed_login_count" integer DEFAULT 0 NOT NULL, "current_login_at" datetime, "last_login_at" datetime, "current_login_ip" varchar(255), "last_login_ip" varchar(255), "created_at" datetime, "updated_at" datetime);
CREATE INDEX "index_accounts_on_ancestry" ON "accounts" ("ancestry");
CREATE INDEX "index_accounts_on_type" ON "accounts" ("type");
CREATE INDEX "index_exchange_rates_on_currency" ON "exchange_rates" ("currency");
CREATE INDEX "index_exchange_rates_on_recorded_on" ON "exchange_rates" ("recorded_on");
CREATE INDEX "index_ledger_items_on_account_id" ON "ledger_items" ("account_id");
CREATE INDEX "index_ledger_items_on_recipient_id" ON "ledger_items" ("recipient_id");
CREATE INDEX "index_ledger_items_on_sender_id" ON "ledger_items" ("sender_id");
CREATE INDEX "index_ledger_items_on_total_amount" ON "ledger_items" ("total_amount");
CREATE INDEX "index_ledger_items_on_transacted_on" ON "ledger_items" ("transacted_on");
CREATE INDEX "index_sessions_on_session_id" ON "sessions" ("session_id");
CREATE INDEX "index_sessions_on_updated_at" ON "sessions" ("updated_at");
CREATE INDEX "index_transactions_on_account_id" ON "transactions" ("account_id");
CREATE INDEX "index_transactions_on_identifier" ON "transactions" ("identifier");
CREATE INDEX "index_transactions_on_issued_on" ON "transactions" ("issued_on");
CREATE INDEX "index_transactions_on_recipient_id" ON "transactions" ("recipient_id");
CREATE INDEX "index_transactions_on_sender_id" ON "transactions" ("sender_id");
CREATE INDEX "index_transactions_on_total_amount" ON "transactions" ("total_amount");
CREATE UNIQUE INDEX "unique_schema_migrations" ON "schema_migrations" ("version");
INSERT INTO schema_migrations (version) VALUES ('20100329113324');

INSERT INTO schema_migrations (version) VALUES ('20091006134353');

INSERT INTO schema_migrations (version) VALUES ('20091021153918');

INSERT INTO schema_migrations (version) VALUES ('20091022121318');

INSERT INTO schema_migrations (version) VALUES ('20091022152641');

INSERT INTO schema_migrations (version) VALUES ('20091025165424');

INSERT INTO schema_migrations (version) VALUES ('20091025165557');

INSERT INTO schema_migrations (version) VALUES ('20091025191438');

INSERT INTO schema_migrations (version) VALUES ('20091027094008');

INSERT INTO schema_migrations (version) VALUES ('20091116111536');

INSERT INTO schema_migrations (version) VALUES ('20091120174124');

INSERT INTO schema_migrations (version) VALUES ('20091203123815');

INSERT INTO schema_migrations (version) VALUES ('20091206014351');

INSERT INTO schema_migrations (version) VALUES ('20091218154431');

INSERT INTO schema_migrations (version) VALUES ('20091221171832');

INSERT INTO schema_migrations (version) VALUES ('20091224002832');

INSERT INTO schema_migrations (version) VALUES ('20100205150120');

INSERT INTO schema_migrations (version) VALUES ('20100329091654');

INSERT INTO schema_migrations (version) VALUES ('20100329105341');


text:
using namespace foundation;

namespace renderer
{

//
// VignetteApplier class implementation.
//

VignetteApplier::VignetteApplier(
    const float frame_width,
    const float frame_height,
    const float intensity,
    const float anisotropy)
  : m_intensity(intensity)
  , m_resolution(Vector2f(frame_width, frame_height))
  , m_vignette_resolution(
        Vector2f(
            lerp(frame_height, frame_width, anisotropy),    // vignette_width
            frame_height))                                  // vignette_height
{
    //
    // We normalize pixel coordinates when applying the effect so that they range from -1 to 1 vertically.
    //
    // Horizontally, we divide frame_width by the frame_height for a perfectly rounded vignette (i.e. no anisotropy), and by
    // the frame_width to respect the frame's aspect ratio (i.e. full anisotropy), hence the lerp in m_vignette_resolution.x.
    //
    // See "Normalizing coordinates" in https://shadertoyunofficial.wordpress.com/2019/01/02/programming-tricks-in-shadertoy-glsl/
    //
}

void VignetteApplier::release()
{
    delete this;
}

void VignetteApplier::apply(
    Image&              image,
    const std::size_t   tile_x,
    const std::size_t   tile_y) const
{
    assert(tile_x < image.properties().m_tile_count_x);
    assert(tile_y < image.properties().m_tile_count_y);

    Tile& tile = image.tile(tile_x, tile_y);
    const std::size_t tile_width = tile.get_width();
    const std::size_t tile_height = tile.get_height();
    const Vector2u tile_offset(
        tile_x * image.properties().m_tile_width,
        tile_y * image.properties().m_tile_height);

    for (std::size_t y = 0; y < tile_height; ++y)
    {
        for (std::size_t x = 0; x < tile_width; ++x)
        {
            const Vector2f pixel_coord = static_cast<Vector2f>(Vector2u(x, y) + tile_offset);

            // Pixel coordinate normalized to be in the [-1, 1] range vertically.
            const Vector2f coord = (2.0f * pixel_coord - m_resolution) / m_vignette_resolution;

            //
            // Port of Keijiro Takahashi's natural vignetting effect for Unity.
            // Recreates natural illumination falloff, which is approximated by the "cosine fourth" law of illumination falloff.
            //
            // References:
            //
            //   https://github.com/keijiro/KinoVignette
            //   https://en.wikipedia.org/wiki/Vignetting#Natural_vignetting
            //

            const float linear_radial_falloff = norm(coord) * m_intensity;
            const float quadratic_radial_falloff = linear_radial_falloff * linear_radial_falloff + 1.0f;

            // Inversely proportional to the fourth power of the distance from the pixel to the image center.
            const float inverse_biquadratic_radial_falloff = 1.0f / (quadratic_radial_falloff * quadratic_radial_falloff);

            Color4f pixel;
            tile.get_pixel(x, y, pixel);

            pixel.rgb() *= inverse_biquadratic_radial_falloff;
            tile.set_pixel(x, y, pixel);
        }
    }
}

}   // namespace renderer


text:
#include <aws/dynamodb/model/AttributeAction.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>

using namespace Aws::Utils;

namespace Aws
{
  namespace DynamoDB
  {
    namespace Model
    {
      namespace AttributeActionMapper
      {

        static const int ADD_HASH = HashingUtils::HashString("ADD");
        static const int PUT_HASH = HashingUtils::HashString("PUT");
        static const int DELETE__HASH = HashingUtils::HashString("DELETE");

        AttributeAction GetAttributeActionForName(const Aws::String& name)
        {
          int hashCode = HashingUtils::HashString(name.c_str());
          if (hashCode == ADD_HASH)
          {
            return AttributeAction::ADD;
          }
          else if (hashCode == PUT_HASH)
          {
            return AttributeAction::PUT;
          }
          else if (hashCode == DELETE__HASH)
          {
            return AttributeAction::DELETE_;
          }
          EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
          if(overflowContainer)
          {
            overflowContainer->StoreOverflow(hashCode, name);
            return static_cast<AttributeAction>(hashCode);
          }

          return AttributeAction::NOT_SET;
        }

        Aws::String GetNameForAttributeAction(AttributeAction enumValue)
        {
          switch(enumValue)
          {
          case AttributeAction::ADD:
            return "ADD";
          case AttributeAction::PUT:
            return "PUT";
          case AttributeAction::DELETE_:
            return "DELETE";
          default:
            EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
            if(overflowContainer)
            {
              return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
            }

            return "";
          }
        }

      } // namespace AttributeActionMapper
    } // namespace Model
  } // namespace DynamoDB
} // namespace Aws


text:
import {APP_INITIALIZER, ChangeDetectorRef, Compiler, Component, Directive, ElementRef, ErrorHandler, getNgModuleById, inject, Inject, Injectable, InjectFlags, InjectionToken, InjectOptions, Injector, Input, LOCALE_ID, ModuleWithProviders, NgModule, Optional, Pipe, Type, ViewChild, ɵsetClassMetadata as setClassMetadata, ɵɵdefineComponent as defineComponent, ɵɵdefineInjector as defineInjector, ɵɵdefineNgModule as defineNgModule, ɵɵelementEnd as elementEnd, ɵɵelementStart as elementStart, ɵɵsetNgModuleScope as setNgModuleScope, ɵɵtext as text} from '@angular/core';
import {TestBed, TestBedImpl} from '@angular/core/testing/src/test_bed';
import {By} from '@angular/platform-browser';
import {expect} from '@angular/platform-browser/testing/src/matchers';

import {TEARDOWN_TESTING_MODULE_ON_DESTROY_DEFAULT, THROW_ON_UNKNOWN_ELEMENTS_DEFAULT, THROW_ON_UNKNOWN_PROPERTIES_DEFAULT} from '../testing/src/test_bed_common';

const NAME = new InjectionToken<string>('name');

@Injectable({providedIn: 'root'})
class SimpleService {
  static ngOnDestroyCalls: number = 0;
  id: number = 1;
  ngOnDestroy() {
    SimpleService.ngOnDestroyCalls++;
  }
}

// -- module: HWModule
@Component({
  selector: 'hello-world',
  template: '<greeting-cmp></greeting-cmp>',
})
export class HelloWorld {
}

// -- module: Greeting
@Component({
  selector: 'greeting-cmp',
  template: 'Hello {{ name }}',
})
export class GreetingCmp {
  name: string;

  constructor(
      @Inject(NAME) @Optional() name: string,
      @Inject(SimpleService) @Optional() service: SimpleService) {
    this.name = name || 'nobody!';
  }
}

@Component({
  selector: 'cmp-with-providers',
  template: '<hello-world></hello-world>',
  providers: [
    SimpleService,  //
    {provide: NAME, useValue: `from Component`}
  ]
})
class CmpWithProviders {
}

@NgModule({
  declarations: [GreetingCmp],
  exports: [GreetingCmp],
})
export class GreetingModule {
}

@Component({selector: 'simple-cmp', template: 'simple'})
export class SimpleCmp {
}

@Component({selector: 'with-refs-cmp', template: '

'})
export class WithRefsCmp {
}

@Component({selector: 'inherited-cmp', template: 'inherited'})
export class InheritedCmp extends SimpleCmp {
}

@Directive({selector: '[hostBindingDir]', host: {'[id]': 'id'}})
export class HostBindingDir {
  id = 'one';
}

@Component({
  selector: 'component-with-prop-bindings',
  template: `

  `
})
export class ComponentWithPropBindings {
  title = 'some title';
  label = 'some label';
}

@Component({
  selector: 'simple-app',
  template: `
    <simple-cmp></simple-cmp> - <inherited-cmp></inherited-cmp>
  `
})
export class SimpleApp {
}

@Component({selector: 'inline-template', template: '
Hello
'})
export class ComponentWithInlineTemplate {
}

@NgModule({
  declarations: [
    HelloWorld, SimpleCmp, WithRefsCmp, InheritedCmp, SimpleApp, ComponentWithPropBindings,
    HostBindingDir, CmpWithProviders
  ],
  imports: [GreetingModule],
  providers: [
    {provide: NAME, useValue: 'World!'},
  ]
})
export class HelloWorldModule {
}

describe('TestBed', () => {
  // This test is extracted to an individual `describe` block to avoid any extra TestBed
  // initialization logic that happens in the `beforeEach` functions in other `describe` sections.
  it('should apply scopes correctly for components in the lazy-loaded module', () => {
    // Reset TestBed to the initial state, emulating an invocation of a first test.
    // Check `TestBed.checkGlobalCompilationFinished` for additional info.
    TestBedImpl.INSTANCE.globalCompilationChecked = false;

    @Component({
      selector: 'root',
      template: '

',
    })
    class Root {
    }
    @Directive({
      selector: '[dirA]',
      host: {'title': 'Test title'},
    })
    class DirA {
    }

    // Note: this module is not directly reference in the test intentionally.
    // Its presence triggers a side-effect of patching correct scopes on the declared components.
    @NgModule({
      declarations: [Root, DirA],
    })
    class Module {
    }

    TestBed.configureTestingModule({});
    // Trigger TestBed initialization.
    TestBed.inject(Injector);

    // Emulate the end of a test (trigger module scoping queue flush).
    TestBed.resetTestingModule();

    // Emulate a lazy-loading scenario by creating a component
    // without importing a module into a TestBed testing module.
    TestBed.configureTestingModule({});
    const fixture = TestBed.createComponent(Root);
    fixture.detectChanges();
    expect(fixture.nativeElement.firstChild.getAttribute('title')).toEqual('Test title');
  });
});

describe('TestBed with Standalone types', () => {
  beforeEach(() => {
    TestBed.resetTestingModule();
  });

  it('should override providers on standalone component itself', () => {
    const A = new InjectionToken('A');

    @Component({
      standalone: true,
      template: '{{ a }}',
      providers: [{provide: A, useValue: 'A'}],
    })
    class MyStandaloneComp {
      constructor(@Inject(A) public a: string) {}
    }

    // NOTE: the `TestBed.configureTestingModule` is load-bearing here: it instructs
    // TestBed to examine and override providers in dependencies.
    TestBed.configureTestingModule({imports: [MyStandaloneComp]});
    TestBed.overrideProvider(A, {useValue: 'Overridden A'});

    const fixture = TestBed.createComponent(MyStandaloneComp);
    fixture.detectChanges();

    expect(fixture.nativeElement.innerHTML).toBe('Overridden A');
  });

  it('should override providers in standalone component dependencies via overrideProvider', () => {
    const A = new InjectionToken('A');
    @NgModule({
      providers: [{provide: A, useValue: 'A'}],
    })
    class ComponentDependenciesModule {
    }

    @Component({
      standalone: true,
      template: '{{ a }}',
      imports: [ComponentDependenciesModule],
    })
    class MyStandaloneComp {
      constructor(@Inject(A) public a: string) {}
    }

    // NOTE: the `TestBed.configureTestingModule` is load-bearing here: it instructs
    // TestBed to examine and override providers in dependencies.
    TestBed.configureTestingModule({imports: [MyStandaloneComp]});
    TestBed.overrideProvider(A, {useValue: 'Overridden A'});

    const fixture = TestBed.createComponent(MyStandaloneComp);
    fixture.detectChanges();

    expect(fixture.nativeElement.innerHTML).toBe('Overridden A');
  });

  it('should override providers in standalone component dependencies via overrideModule', () => {
    const A = new InjectionToken('A');
    @NgModule({
      providers: [{provide: A, useValue: 'A'}],
    })
    class ComponentDependenciesModule {
    }

    @Component({
      standalone: true,
      template: '{{ a }}',
      imports: [ComponentDependenciesModule],
    })
    class MyStandaloneComp {
      constructor(@Inject(A) public a: string) {}
    }

    // NOTE: the `TestBed.configureTestingModule` is *not* needed here, since the TestBed
    // knows which NgModule was overridden and needs re-compilation.
    TestBed.overrideModule(
        ComponentDependenciesModule, {set: {providers: [{provide: A, useValue: 'Overridden A'}]}});

    const fixture = TestBed.createComponent(MyStandaloneComp);
    fixture.detectChanges();

    expect(fixture.nativeElement.innerHTML).toBe('Overridden A');
  });

  it('should allow overriding a template of a standalone component', () => {
    @Component({
      standalone: true,
      template: 'Original',
    })
    class MyStandaloneComp {
    }

    // NOTE: the `TestBed.configureTestingModule` call is *not* required here, since TestBed already
    // knows that the `MyStandaloneComp` should be overridden/recompiled.
    TestBed.overrideComponent(MyStandaloneComp, {set: {template: 'Overridden'}});

    const fixture = TestBed.createComponent(MyStandaloneComp);
    fixture.detectChanges();

    expect(fixture.nativeElement.innerHTML).toBe('Overridden');
  });

  it('should allow overriding the set of directives and pipes used in a standalone component',
     () => {
       @Directive({
         selector: '[dir]',
         standalone: true,
         host: {'[id]': 'id'},
       })
       class MyStandaloneDirectiveA {
         id = 'A';
       }

       @Directive({
         selector: '[dir]',
         standalone: true,
         host: {'[id]': 'id'},
       })
       class MyStandaloneDirectiveB {
         id = 'B';
       }

       @Pipe({name: 'pipe', standalone: true})
       class MyStandalonePipeA {
         transform(value: string): string {
           return `transformed ${value} (A)`;
         }
       }
       @Pipe({name: 'pipe', standalone: true})
       class MyStandalonePipeB {
         transform(value: string): string {
           return `transformed ${value} (B)`;
         }
       }

       @Component({
         standalone: true,
         template: '
{{ name | pipe }}
',
         imports: [MyStandalonePipeA, MyStandaloneDirectiveA],
       })
       class MyStandaloneComp {
         name = 'MyStandaloneComp';
       }

       // NOTE: the `TestBed.configureTestingModule` call is *not* required here, since TestBed
       // already knows that the `MyStandaloneComp` should be overridden/recompiled.
       TestBed.overrideComponent(
           MyStandaloneComp, {set: {imports: [MyStandalonePipeB, MyStandaloneDirectiveB]}});

       const fixture = TestBed.createComponent(MyStandaloneComp);
       fixture.detectChanges();

       const rootElement = fixture.nativeElement.firstChild;
       expect(rootElement.id).toBe('B');
       expect(rootElement.innerHTML).toBe('transformed MyStandaloneComp (B)');
     });

  it('should reflect overrides on imported standalone directive', () => {
    @Directive({
      selector: '[dir]',
      standalone: true,
      host: {'[id]': 'id'},
    })
    class DepStandaloneDirective {
      id = 'A';
    }

    @Component({
      selector: 'standalone-cmp',
      standalone: true,
      template: 'Original MyStandaloneComponent',
    })
    class DepStandaloneComponent {
      id = 'A';
    }

    @Component({
      standalone: true,
      template: '<standalone-cmp dir>Hello world!</standalone-cmp>',
      imports: [DepStandaloneDirective, DepStandaloneComponent],
    })
    class RootStandaloneComp {
    }

    // NOTE: the `TestBed.configureTestingModule` call is *not* required here, since TestBed
    // already knows which Components/Directives are overridden and should be recompiled.
    TestBed.overrideComponent(
        DepStandaloneComponent, {set: {template: 'Overridden MyStandaloneComponent'}});
    TestBed.overrideDirective(DepStandaloneDirective, {set: {host: {'[id]': '\'Overridden\''}}});

    const fixture = TestBed.createComponent(RootStandaloneComp);
    fixture.detectChanges();

    const rootElement = fixture.nativeElement.firstChild;

    expect(rootElement.id).toBe('Overridden');
    expect(rootElement.innerHTML).toBe('Overridden MyStandaloneComponent');
  });

  it('should make overridden providers available in pipes', () => {
    const TOKEN_A = new InjectionToken('TOKEN_A');
    @Pipe({
      name: 'testPipe',
      standalone: true,
    })
    class TestPipe {
      constructor(@Inject(TOKEN_A) private token: string) {}

      transform(value: string): string {
        return `transformed ${value} using ${this.token} token`;
      }
    }
    @NgModule({
      imports: [TestPipe],
      exports: [TestPipe],
      providers: [{provide: TOKEN_A, useValue: 'A'}],
    })
    class TestNgModule {
    }

    @Component({
      selector: 'test-component',
      standalone: true,
      imports: [TestNgModule],
      template: `{{ 'original value' | testPipe }}`
    })
    class TestComponent {
    }

    TestBed.configureTestingModule({
      imports: [TestComponent],
    });
    TestBed.overrideProvider(TOKEN_A, {useValue: 'Overridden A'});

    const fixture = TestBed.createComponent(TestComponent);
    fixture.detectChanges();

    const hostElement = fixture.nativeElement.firstChild;
    expect(hostElement.textContent).toBe('transformed original value using Overridden A token');
  });

  describe('NgModules as dependencies', () => {
    @Component({
      selector: 'test-cmp',
      template: '...',
    })
    class TestComponent {
      testField = 'default';
    }

    @Component({
      selector: 'test-cmp',
      template: '...',
    })
    class MockTestComponent {
      testField = 'overridden';
    }

    @NgModule({
      declarations: [TestComponent],
      exports: [TestComponent],
    })
    class TestModule {
    }

    @Component({
      standalone: true,
      selector: 'app-root',
      template: `<test-cmp #testCmpCtrl></test-cmp>`,
      imports: [TestModule],
    })
    class AppComponent {
      @ViewChild('testCmpCtrl', {static: true}) testCmpCtrl!: TestComponent;
    }

    it('should allow declarations and exports overrides on an imported NgModule', () => {
      // replace TestComponent with MockTestComponent
      TestBed.overrideModule(TestModule, {
        remove: {declarations: [TestComponent], exports: [TestComponent]},
        add: {declarations: [MockTestComponent], exports: [MockTestComponent]}
      });
      const fixture = TestBed.createComponent(AppComponent);
      fixture.detectChanges();

      const app = fixture.componentInstance;
      expect(app.testCmpCtrl.testField).toBe('overridden');
    });

    it('should allow removing an import via `overrideModule`', () => {
      const fooToken = new InjectionToken<string>('foo');

      @NgModule({
        providers: [{provide: fooToken, useValue: 'FOO'}],
      })
      class ImportedModule {
      }

      @NgModule({
        imports: [ImportedModule],
      })
      class ImportingModule {
      }

      TestBed.configureTestingModule({
        imports: [ImportingModule],
      });

      TestBed.overrideModule(ImportingModule, {
        remove: {
          imports: [ImportedModule],
        },
      });

      expect(TestBed.inject(fooToken, 'BAR')).toBe('BAR');

      // Emulate an end of a test.
      TestBed.resetTestingModule();

      // Emulate the start of a next test, make sure previous overrides
      // are not persisted across tests.
      TestBed.configureTestingModule({
        imports: [ImportingModule],
      });
      expect(TestBed.inject(fooToken, 'BAR')).toBe('FOO');
    });
  });
});

describe('TestBed', () => {
  beforeEach(() => {
    TestBed.resetTestingModule();
    TestBed.configureTestingModule({imports: [HelloWorldModule]});
  });

  it('should compile and render a component', () => {
    const hello = TestBed.createComponent(HelloWorld);
    hello.detectChanges();

    expect(hello.nativeElement).toHaveText('Hello World!');
  });

  it('should not allow overrides of the `standalone` field', () => {
    @Component({
      standalone: true,
      selector: 'standalone-comp',
      template: '...',
    })
    class StandaloneComponent {
    }

    @Component({
      selector: 'non-standalone-comp',
      template: '...',
    })
    class NonStandaloneComponent {
    }

    @Directive({standalone: true})
    class StandaloneDirective {
    }

    @Directive({})
    class NonStandaloneDirective {
    }

    @Pipe({standalone: true, name: 'test'})
    class StandalonePipe {
    }

    @Pipe({name: 'test'})
    class NonStandalonePipe {
    }

    const getExpectedError = (typeName: string) =>
        `An override for the ${typeName} class has the \`standalone\` flag. ` +
        `Changing the \`standalone\` flag via TestBed overrides is not supported.`;

    const overrides = [
      {set: {standalone: false}},
      {add: {standalone: false}},
      {remove: {standalone: true}},
    ];

    const scenarios = [
      [TestBed.overrideComponent, StandaloneComponent, NonStandaloneComponent],
      [TestBed.overrideDirective, StandaloneDirective, NonStandaloneDirective],
      [TestBed.overridePipe, StandalonePipe, NonStandalonePipe]
    ];

    overrides.forEach(override => {
      scenarios.forEach(([fn, standaloneType, nonStandaloneType]) => {
        expect(() => (fn as Function)(standaloneType, override))
            .toThrowError(getExpectedError(standaloneType.name));
        expect(() => (fn as Function)(nonStandaloneType, override))
            .toThrowError(getExpectedError(nonStandaloneType.name));
      });
    });
  });

  it('should give access to the component instance', () => {
    const hello = TestBed.createComponent(HelloWorld);
    hello.detectChanges();

    expect(hello.componentInstance).toBeAnInstanceOf(HelloWorld);
  });

  it('should give the ability to query by css', () => {
    const hello = TestBed.createComponent(HelloWorld);
    hello.detectChanges();

    const greetingByCss = hello.debugElement.query(By.css('greeting-cmp'));
    expect(greetingByCss.nativeElement).toHaveText('Hello World!');
    expect(greetingByCss.componentInstance).toBeAnInstanceOf(GreetingCmp);
  });

  it('should give the ability to trigger the change detection', () => {
    const hello = TestBed.createComponent(HelloWorld);

    hello.detectChanges();
    const greetingByCss = hello.debugElement.query(By.css('greeting-cmp'));
    expect(greetingByCss.nativeElement).toHaveText('Hello World!');

    greetingByCss.componentInstance.name = 'TestBed!';
    hello.detectChanges();
    expect(greetingByCss.nativeElement).toHaveText('Hello TestBed!');
  });

  it('should give the ability to access property bindings on a node', () => {
    const fixture = TestBed.createComponent(ComponentWithPropBindings);
    fixture.detectChanges();

    const divElement = fixture.debugElement.query(By.css('div'));
    expect(divElement.properties.id).toEqual('one');
    expect(divElement.properties.title).toEqual('some title');
  });

  it('should give the ability to access interpolated properties on a node', () => {
    const fixture = TestBed.createComponent(ComponentWithPropBindings);
    fixture.detectChanges();

    const paragraphEl = fixture.debugElement.query(By.css('p'));
    expect(paragraphEl.properties.title).toEqual('( some label - some title )');
    expect(paragraphEl.properties.id).toEqual('[ some label ] [ some title ]');
  });

  it('should give access to the node injector', () => {
    const fixture = TestBed.createComponent(HelloWorld);
    fixture.detectChanges();
    const injector = fixture.debugElement.query(By.css('greeting-cmp')).injector;

    // from the node injector
    const greetingCmp = injector.get(GreetingCmp);
    expect(greetingCmp.constructor).toBe(GreetingCmp);

    // from the node injector (inherited from a parent node)
    const helloWorldCmp = injector.get(HelloWorld);
    expect(fixture.componentInstance).toBe(helloWorldCmp);

    const nameInjected = injector.get(NAME);
    expect(nameInjected).toEqual('World!');
  });

  it('should give access to the node injector for root node', () => {
    const hello = TestBed.createComponent(HelloWorld);
    hello.detectChanges();
    const injector = hello.debugElement.injector;

    // from the node injector
    const helloInjected = injector.get(HelloWorld);
    expect(helloInjected).toBe(hello.componentInstance);

    // from the module injector
    const nameInjected = injector.get(NAME);
    expect(nameInjected).toEqual('World!');
  });

  it('should give access to local refs on a node', () => {
    const withRefsCmp = TestBed.createComponent(WithRefsCmp);
    const firstDivDebugEl = withRefsCmp.debugElement.query(By.css('div'));
    // assert that a native element is referenced by a local ref
    expect(firstDivDebugEl.references.firstDiv.tagName.toLowerCase()).toBe('div');
  });

  it('should give the ability to query by directive', () => {
    const hello = TestBed.createComponent(HelloWorld);
    hello.detectChanges();

    const greetingByDirective = hello.debugElement.query(By.directive(GreetingCmp));
    expect(greetingByDirective.componentInstance).toBeAnInstanceOf(GreetingCmp);
  });

  it('should allow duplicate NgModule registrations with the same id', () => {
    const id = 'registered';
    @NgModule({id})
    class ModuleA {
    }

    expect(getNgModuleById(id)).toBe(ModuleA);

    // This would ordinarily error, if not in a test scenario.
    @NgModule({id})
    class ModuleB {
    }
    expect(getNgModuleById(id)).toBe(ModuleB);
  });

  it('allow to override a template', () => {
    // use original template when there is no override
    let hello = TestBed.createComponent(HelloWorld);
    hello.detectChanges();
    expect(hello.nativeElement).toHaveText('Hello World!');

    // override the template
    TestBed.resetTestingModule();
    TestBed.configureTestingModule({imports: [HelloWorldModule]});
    TestBed.overrideComponent(GreetingCmp, {set: {template: `Bonjour {{ name }}`}});
    hello = TestBed.createComponent(HelloWorld);
    hello.detectChanges();
    expect(hello.nativeElement).toHaveText('Bonjour World!');

    // restore the original template by calling `.resetTestingModule()`
    TestBed.resetTestingModule();
    TestBed.configureTestingModule({imports: [HelloWorldModule]});
    hello = TestBed.createComponent(HelloWorld);
    hello.detectChanges();
    expect(hello.nativeElement).toHaveText('Hello World!');
  });

  // https://github.com/angular/angular/issues/42734
  it('should override a component which is declared in an NgModule which is imported as a `ModuleWithProviders`',
     () => {
       // This test verifies that an overridden component that is declared in an NgModule that has
       // been imported as a `ModuleWithProviders` continues to have access to the declaration scope
       // of the NgModule.
       TestBed.resetTestingModule();

       const moduleWithProviders:
           ModuleWithProviders<HelloWorldModule> = {ngModule: HelloWorldModule};
       TestBed.configureTestingModule({imports: [moduleWithProviders]});
       TestBed.overrideComponent(
           HelloWorld, {set: {template: 'Overridden <greeting-cmp></greeting-cmp>'}});

       const hello = TestBed.createComponent(HelloWorld);
       hello.detectChanges();
       expect(hello.nativeElement).toHaveText('Overridden Hello World!');
     });

  it('should run `APP_INITIALIZER` before accessing `LOCALE_ID` provider', () => {
    let locale: string = '';
    @NgModule({
      providers: [
        {provide: APP_INITIALIZER, useValue: () => locale = 'fr-FR', multi: true},
        {provide: LOCALE_ID, useFactory: () => locale}
      ]
    })
    class TestModule {
    }

    TestBed.configureTestingModule({imports: [TestModule]});
    expect(TestBed.inject(LOCALE_ID)).toBe('fr-FR');
  });

  it('allow to override a provider', () => {
    TestBed.overrideProvider(NAME, {useValue: 'injected World!'});
    const hello = TestBed.createComponent(HelloWorld);
    hello.detectChanges();
    expect(hello.nativeElement).toHaveText('Hello injected World!');
  });

  it('uses the most recent provider override', () => {
    TestBed.overrideProvider(NAME, {useValue: 'injected World!'});
    TestBed.overrideProvider(NAME, {useValue: 'injected World a second time!'});
    const hello = TestBed.createComponent(HelloWorld);
    hello.detectChanges();
    expect(hello.nativeElement).toHaveText('Hello injected World a second time!');
  });

  it('overrides a providers in an array', () => {
    TestBed.configureTestingModule({
      imports: [HelloWorldModule],
      providers: [
        [{provide: NAME, useValue: 'injected World!'}],
      ]
    });
    TestBed.overrideProvider(NAME, {useValue: 'injected World a second time!'});
    const hello = TestBed.createComponent(HelloWorld);
    hello.detectChanges();
    expect(hello.nativeElement).toHaveText('Hello injected World a second time!');
  });

  it('should not call ngOnDestroy for a service that was overridden', () => {
    SimpleService.ngOnDestroyCalls = 0;

    TestBed.overrideProvider(SimpleService, {useValue: {id: 2, ngOnDestroy: () => {}}});
    const fixture = TestBed.createComponent(CmpWithProviders);
    fixture.detectChanges();

    const service = TestBed.inject(SimpleService);
    expect(service.id).toBe(2);

    fixture.destroy();

    // verify that original `ngOnDestroy` was not called
    expect(SimpleService.ngOnDestroyCalls).toBe(0);
  });

  it('should be able to create a fixture if a test module is reset mid-compilation', async () => {
    const token = new InjectionToken<number>('value');

    @Component({template: 'hello {{_token}}'})
    class TestComponent {
      constructor(@Inject(token) public _token: number) {}
    }

    TestBed.resetTestingModule();  // Reset the state from `beforeEach`.

    function compile(tokenValue: number) {
      return TestBed
          .configureTestingModule({
            declarations: [TestComponent],
            providers: [{provide: token, useValue: tokenValue}],
            teardown: {destroyAfterEach: true}
          })
          .compileComponents();
    }

    const initialCompilation = compile(1);
    TestBed.resetTestingModule();
    await initialCompilation;
    await compile(2);
    const fixture = TestBed.createComponent(TestComponent);
    fixture.detectChanges();
    expect(fixture.nativeElement).toHaveText('hello 2');
  });

  describe('module overrides using TestBed.overrideModule', () => {
    @Component({
      selector: 'test-cmp',
      template: '...',
    })
    class TestComponent {
      testField = 'default';
    }

    @NgModule({
      declarations: [TestComponent],
      exports: [TestComponent],
    })
    class TestModule {
    }

    @Component({
      selector: 'app-root',
      template: `<test-cmp #testCmpCtrl></test-cmp>`,
    })
    class AppComponent {
      @ViewChild('testCmpCtrl', {static: true}) testCmpCtrl!: TestComponent;
    }

    @NgModule({
      declarations: [AppComponent],
      imports: [TestModule],
    })
    class AppModule {
    }
    @Component({
      selector: 'test-cmp',
      template: '...',
    })
    class MockTestComponent {
      testField = 'overwritten';
    }

    it('should allow declarations override', () => {
      TestBed.configureTestingModule({
        imports: [AppModule],
      });
      // replace TestComponent with MockTestComponent
      TestBed.overrideModule(TestModule, {
        remove: {declarations: [TestComponent], exports: [TestComponent]},
        add: {declarations: [MockTestComponent], exports: [MockTestComponent]}
      });
      const fixture = TestBed.createComponent(AppComponent);
      const app = fixture.componentInstance;
      expect(app.testCmpCtrl.testField).toBe('overwritten');
    });
  });

  describe('nested module overrides using TestBed.overrideModule', () => {
    // Set up an NgModule hierarchy with two modules, A and B, each with their own component.
    // Module B additionally re-exports module A. Also declare two mock components which can be
    // used in tests to verify that overrides within this hierarchy are working correctly.

    // ModuleA content:

    @Component({
      selector: 'comp-a',
      template: 'comp-a content',
    })
    class CompA {
    }

    @Component({
      selector: 'comp-a',
      template: 'comp-a mock content',
    })
    class MockCompA {
    }

    @NgModule({
      declarations: [CompA],
      exports: [CompA],
    })
    class ModuleA {
    }

    // ModuleB content:

    @Component({
      selector: 'comp-b',
      template: 'comp-b content',
    })
    class CompB {
    }

    @Component({
      selector: 'comp-b',
      template: 'comp-b mock content',
    })
    class MockCompB {
    }

    @NgModule({
      imports: [ModuleA],
      declarations: [CompB],
      exports: [CompB, ModuleA],
    })
    class ModuleB {
    }

    // AppModule content:

    @Component({
      selector: 'app',
      template: `
        <comp-a></comp-a>
        <comp-b></comp-b>
      `,
    })
    class App {
    }

    @NgModule({
      imports: [ModuleB],
      exports: [ModuleB],
    })
    class AppModule {
    }

    it('should detect nested module override', () => {
      TestBed
          .configureTestingModule({
            declarations: [App],
            // AppModule -> ModuleB -> ModuleA (to be overridden)
            imports: [AppModule],
          })
          .overrideModule(ModuleA, {
            remove: {declarations: [CompA], exports: [CompA]},
            add: {declarations: [MockCompA], exports: [MockCompA]}
          })
          .compileComponents();

      const fixture = TestBed.createComponent(App);
      fixture.detectChanges();

      // CompA is overridden, expect mock content.
      expect(fixture.nativeElement.textContent).toContain('comp-a mock content');

      // CompB is not overridden, expect original content.
      expect(fixture.nativeElement.textContent).toContain('comp-b content');
    });

    it('should detect chained modules override', () => {
      TestBed
          .configureTestingModule({
            declarations: [App],
            // AppModule -> ModuleB (to be overridden) -> ModuleA (to be overridden)
            imports: [AppModule],
          })
          .overrideModule(ModuleA, {
            remove: {declarations: [CompA], exports: [CompA]},
            add: {declarations: [MockCompA], exports: [MockCompA]}
          })
          .overrideModule(ModuleB, {
            remove: {declarations: [CompB], exports: [CompB]},
            add: {declarations: [MockCompB], exports: [MockCompB]}
          })
          .compileComponents();

      const fixture = TestBed.createComponent(App);
      fixture.detectChanges();

      // Both CompA and CompB are overridden, expect mock content for both.
      expect(fixture.nativeElement.textContent).toContain('comp-a mock content');
      expect(fixture.nativeElement.textContent).toContain('comp-b mock content');
    });
  });

  describe('multi providers', () => {
    const multiToken = new InjectionToken<string[]>('multiToken');
    const singleToken = new InjectionToken<string>('singleToken');
    const multiTokenToOverrideAtModuleLevel =
        new InjectionToken<string[]>('moduleLevelMultiOverride');
    @NgModule({providers: [{provide: multiToken, useValue: 'valueFromModule', multi: true}]})
    class MyModule {
    }

    @NgModule({
      providers: [
        {provide: singleToken, useValue: 't1'}, {
          provide: multiTokenToOverrideAtModuleLevel,
          useValue: 'multiTokenToOverrideAtModuleLevelOriginal',
          multi: true
        },
        {provide: multiToken, useValue: 'valueFromModule2', multi: true},
        {provide: multiToken, useValue: 'secondValueFromModule2', multi: true}
      ]
    })
    class MyModule2 {
    }

    beforeEach(() => {
      TestBed.configureTestingModule({
        imports: [
          MyModule, {
            ngModule: MyModule2,
            providers:
                [{provide: multiTokenToOverrideAtModuleLevel, useValue: 'override', multi: true}]
          }
        ],
      });
    });

    it('is preserved when other provider is overridden', () => {
      TestBed.overrideProvider(singleToken, {useValue: ''});
      expect(TestBed.inject(multiToken).length).toEqual(3);
      expect(TestBed.inject(multiTokenToOverrideAtModuleLevel).length).toEqual(2);
      expect(TestBed.inject(multiTokenToOverrideAtModuleLevel)).toEqual([
        'multiTokenToOverrideAtModuleLevelOriginal', 'override'
      ]);
    });

    it('overridden with an array', () => {
      const overrideValue = ['override'];
      TestBed.overrideProvider(multiToken, {useValue: overrideValue, multi: true} as any);

      const value = TestBed.inject(multiToken);
      expect(value.length).toEqual(overrideValue.length);
      expect(value).toEqual(overrideValue);
    });

    it('overridden with a non-array', () => {
      // This is actually invalid because multi providers return arrays. We have this here so we can
      // ensure Ivy behaves the same as VE does currently.
      const overrideValue = 'override';
      TestBed.overrideProvider(multiToken, {useValue: overrideValue, multi: true} as any);

      const value = TestBed.inject(multiToken);
      expect(value.length).toEqual(overrideValue.length);
      expect(value).toEqual(overrideValue as {} as string[]);
    });
  });

  describe('overrides providers in ModuleWithProviders', () => {
    const TOKEN = new InjectionToken<string[]>('token');
    @NgModule()
    class MyMod {
      static multi = false;

      static forRoot() {
        return {
          ngModule: MyMod,
          providers: [{provide: TOKEN, multi: MyMod.multi, useValue: 'forRootValue'}]
        };
      }
    }

    beforeEach(() => MyMod.multi = true);

    it('when provider is a "regular" provider', () => {
      MyMod.multi = false;
      @NgModule({imports: [MyMod.forRoot()]})
      class MyMod2 {
      }
      TestBed.configureTestingModule({imports: [MyMod2]});
      TestBed.overrideProvider(TOKEN, {useValue: ['override']});
      expect(TestBed.inject(TOKEN)).toEqual(['override']);
    });

    it('when provider is multi', () => {
      @NgModule({imports: [MyMod.forRoot()]})
      class MyMod2 {
      }
      TestBed.configureTestingModule({imports: [MyMod2]});
      TestBed.overrideProvider(TOKEN, {useValue: ['override']});
      expect(TestBed.inject(TOKEN)).toEqual(['override']);
    });

    it('restores the original value', () => {
      @NgModule({imports: [MyMod.forRoot()]})
      class MyMod2 {
      }
      TestBed.configureTestingModule({imports: [MyMod2]});
      TestBed.overrideProvider(TOKEN, {useValue: ['override']});
      expect(TestBed.inject(TOKEN)).toEqual(['override']);

      TestBed.resetTestingModule();
      TestBed.configureTestingModule({imports: [MyMod2]});
      expect(TestBed.inject(TOKEN)).toEqual(['forRootValue']);
    });
  });

  it('should allow overriding a provider defined via ModuleWithProviders (using TestBed.overrideProvider)',
     () => {
       const serviceOverride = {
         get() {
           return 'override';
         },
       };

       @Injectable({providedIn: 'root'})
       class MyService {
         get() {
           return 'original';
         }
       }

       @NgModule({})
       class MyModule {
         static forRoot(): ModuleWithProviders<MyModule> {
           return {
             ngModule: MyModule,
             providers: [MyService],
           };
         }
       }
       TestBed.overrideProvider(MyService, {useValue: serviceOverride});
       TestBed.configureTestingModule({
         imports: [MyModule.forRoot()],
       });

       const service = TestBed.inject(MyService);
       expect(service.get()).toEqual('override');
     });

  it('should handle overrides for a provider that has `ChangeDetectorRef` as a dependency', () => {
    @Injectable({providedIn: 'root'})
    class MyService {
      token = 'original';
      constructor(public cdr: ChangeDetectorRef) {}
    }

    TestBed.configureTestingModule({});
    TestBed.overrideProvider(MyService, {useValue: {token: 'override'}});

    const service = TestBed.inject(MyService);
    expect(service.token).toBe('override');
  });

  it('should allow overriding a provider defined via ModuleWithProviders (using TestBed.configureTestingModule)',
     () => {
       const serviceOverride = {
         get() {
           return 'override';
         },
       };

       @Injectable({providedIn: 'root'})
       class MyService {
         get() {
           return 'original';
         }
       }

       @NgModule({})
       class MyModule {
         static forRoot(): ModuleWithProviders<MyModule> {
           return {
             ngModule: MyModule,
             providers: [MyService],
           };
         }
       }
       TestBed.configureTestingModule({
         imports: [MyModule.forRoot()],
         providers: [{provide: MyService, useValue: serviceOverride}],
       });

       const service = TestBed.inject(MyService);
       expect(service.get()).toEqual('override');
     });

  it('should allowing overriding a module with a cyclic structure in its metadata', () => {
    class Cyclic {
      cycle = this;

      constructor(public name: string) {}
    }

    const CYCLES = new InjectionToken<Cyclic[]>('cycles', {factory: () => []});

    @NgModule({
      providers: [
        {provide: CYCLES, useValue: new Cyclic('a'), multi: true},
        {provide: CYCLES, useValue: new Cyclic('b'), multi: true},
      ],
    })
    class TestModule {
    }

    TestBed
        .configureTestingModule({
          imports: [TestModule],
        })
        .overrideModule(TestModule, {
          remove: {
            providers: [
              // Removing the cycle named "a" should result in removing the provider for "a".
              // Note: although this removes a different instance than the one provided, metadata
              // overrides compare objects by value, not by reference.
              {provide: CYCLES, useValue: new Cyclic('a'), multi: true},

              // Also attempt to remove a cycle named "B" (which does not exist) to verify that
              // objects are correctly compared by value.
              {provide: CYCLES, useValue: new Cyclic('B'), multi: true},
            ],
          },
          add: {
            providers: [
              {provide: CYCLES, useValue: new Cyclic('c'), multi: true},
            ],
          },
        })
        .compileComponents();

    const values = TestBed.inject(CYCLES);
    expect(values.map(v => v.name)).toEqual(['b', 'c']);
  });

  it('overrides injectable that is using providedIn: AModule', () => {
    @NgModule()
    class ServiceModule {
    }
    @Injectable({providedIn: ServiceModule})
    class Service {
    }

    const fake = 'fake';
    TestBed.overrideProvider(Service, {useValue: fake});
    // Create an injector whose source is the ServiceModule, not DynamicTestModule.
    const ngModuleFactory = TestBed.inject(Compiler).compileModuleSync(ServiceModule);
    const injector = ngModuleFactory.create(TestBed.inject(Injector)).injector;

    const service = injector.get(Service);
    expect(service).toBe(fake);
  });

  it('allow to override multi provider', () => {
    const MY_TOKEN = new InjectionToken('MyProvider');
    class MyProvider {}

    @Component({selector: 'my-comp', template: ``})
    class MyComp {
      constructor(@Inject(MY_TOKEN) public myProviders: MyProvider[]) {}
    }

    TestBed.configureTestingModule({
      declarations: [MyComp],
      providers: [{provide: MY_TOKEN, useValue: {value: 'old provider'}, multi: true}]
    });

    const multiOverride = {useValue: [{value: 'new provider'}], multi: true};
    TestBed.overrideProvider(MY_TOKEN, multiOverride as any);

    const fixture = TestBed.createComponent(MyComp);
    expect(fixture.componentInstance.myProviders).toEqual([{value: 'new provider'}]);
  });

  it('should resolve components that are extended by other components', () => {
    // SimpleApp uses SimpleCmp in its template, which is extended by InheritedCmp
    const simpleApp = TestBed.createComponent(SimpleApp);
    simpleApp.detectChanges();
    expect(simpleApp.nativeElement).toHaveText('simple - inherited');
  });

  it('should not trigger change detection for ComponentA while calling TestBed.createComponent for ComponentB',
     () => {
       const log: string[] = [];
       @Component({
         selector: 'comp-a',
         template: '...',
       })
       class CompA {
         @Input() inputA: string = '';
         ngOnInit() {
           log.push('CompA:ngOnInit', this.inputA);
         }
       }

       @Component({
         selector: 'comp-b',
         template: '...',
       })
       class CompB {
         @Input() inputB: string = '';
         ngOnInit() {
           log.push('CompB:ngOnInit', this.inputB);
         }
       }

       TestBed.configureTestingModule({declarations: [CompA, CompB]});

       log.length = 0;
       const appA = TestBed.createComponent(CompA);
       appA.componentInstance.inputA = 'a';
       appA.autoDetectChanges();
       expect(log).toEqual(['CompA:ngOnInit', 'a']);

       log.length = 0;
       const appB = TestBed.createComponent(CompB);
       appB.componentInstance.inputB = 'b';
       appB.autoDetectChanges();
       expect(log).toEqual(['CompB:ngOnInit', 'b']);
     });

  it('should resolve components without async resources synchronously', (done) => {
    TestBed
        .configureTestingModule({
          declarations: [ComponentWithInlineTemplate],
        })
        .compileComponents()
        .then(done)
        .catch(error => {
          // This should not throw any errors. If an error is thrown, the test will fail.
          // Specifically use `catch` here to mark the test as done and *then* throw the error
          // so that the test isn't treated as a timeout.
          done();
          throw error;
        });

    // Intentionally call `createComponent` before `compileComponents` is resolved. We want this to
    // work for components that don't have any async resources (templateUrl, styleUrls).
    TestBed.createComponent(ComponentWithInlineTemplate);
  });

  it('should be able to override the ErrorHandler via an import', () => {
    class CustomErrorHandler {}

    @NgModule({providers: [{provide: ErrorHandler, useClass: CustomErrorHandler}]})
    class ProvidesErrorHandler {
    }

    TestBed.resetTestingModule();
    TestBed.configureTestingModule({imports: [ProvidesErrorHandler, HelloWorldModule]});

    expect(TestBed.inject(ErrorHandler)).toEqual(jasmine.any(CustomErrorHandler));
  });

  it('should throw errors in CD', () => {
    @Component({selector: 'my-comp', template: ''})
    class MyComp {
      name!: {hello: string};

      ngOnInit() {
        // this should throw because this.name is undefined
        this.name.hello = 'hello';
      }
    }

    TestBed.configureTestingModule({declarations: [MyComp]});

    expect(() => {
      const fixture = TestBed.createComponent(MyComp);
      fixture.detectChanges();
    }).toThrowError();
  });

  // TODO(FW-1245): properly fix issue where errors in listeners aren't thrown and don't cause
  // tests to fail. This is an issue in both View Engine and Ivy, and may require a breaking
  // change to completely fix (since simple re-throwing breaks handlers in ngrx, etc).
  xit('should throw errors in listeners', () => {
    @Component({selector: 'my-comp', template: '<button (click)="onClick()">Click me</button>'})
    class MyComp {
      name!: {hello: string};

      onClick() {
        // this should throw because this.name is undefined
        this.name.hello = 'hello';
      }
    }

    TestBed.configureTestingModule({declarations: [MyComp]});
    const fixture = TestBed.createComponent(MyComp);
    fixture.detectChanges();

    expect(() => {
      const button = fixture.nativeElement.querySelector('button');
      button.click();
    }).toThrowError();
  });

  it('should allow both the declaration and import of a component into the testing module', () => {
    // This test validates that a component (Outer) which is both declared and imported
    // (via its module) in the testing module behaves correctly. That is:
    //
    // 1) the component should be compiled in the scope of its original module.
    //
    // This condition is tested by having the component (Outer) use another component
    // (Inner) within its template. Thus, if it's compiled in the correct scope then the
    // text 'Inner' from the template of (Inner) should appear in the result.
    //
    // 2) the component should be available in the TestingModule scope.
    //
    // This condition is tested by attempting to use the component (Outer) inside a test
    // fixture component (Fixture) which is declared in the testing module only.

    @Component({
      selector: 'inner',
      template: 'Inner',
    })
    class Inner {
    }

    @Component({
      selector: 'outer',
      template: '<inner></inner>',
    })
    class Outer {
    }

    @NgModule({
      declarations: [Inner, Outer],
    })
    class Module {
    }

    @Component({
      template: '<outer></outer>',
      selector: 'fixture',
    })
    class Fixture {
    }

    TestBed.configureTestingModule({
      declarations: [Outer, Fixture],
      imports: [Module],
    });

    const fixture = TestBed.createComponent(Fixture);
    // The Outer component should have its template stamped out, and that template should
    // include a correct instance of the Inner component with the 'Inner' text from its
    // template.
    expect(fixture.nativeElement.innerHTML).toEqual('<outer><inner>Inner</inner></outer>');
  });

  describe('checking types before compiling them', () => {
    @Directive({
      selector: 'my-dir',
    })
    class MyDir {
    }

    @NgModule()
    class MyModule {
    }

    // [decorator, type, overrideFn]
    const cases: [string, Type<any>, string][] = [
      ['Component', MyDir, 'overrideComponent'],
      ['NgModule', MyDir, 'overrideModule'],
      ['Pipe', MyModule, 'overridePipe'],
      ['Directive', MyModule, 'overrideDirective'],
    ];
    cases.forEach(([decorator, type, overrideFn]) => {
      it(`should throw an error in case invalid type is used in ${overrideFn} function`, () => {
        TestBed.configureTestingModule({declarations: [MyDir]});
        expect(() => {
          (TestBed as any)[overrideFn](type, {});
          TestBed.createComponent(type);
        }).toThrowError(new RegExp(`class doesn't have @${decorator} decorator`, 'g'));
      });
    });
  });

  describe('AOT pre-compiled components', () => {
    /**
     * Function returns a class that represents AOT-compiled version of the following Component:
     *
     * @Component({
     *  standalone: true|false,
     *  imports: [...],  // for standalone only
     *  selector: 'comp',
     *  templateUrl: './template.ng.html',
     *  styleUrls: ['./style.css']
     * })
     * class ComponentClass {}
     *
     * This is needed to closer match the behavior of AOT pre-compiled components (compiled
     * outside of TestBed) without changing TestBed state and/or Component metadata to compile
     * them via TestBed with external resources.
     */
    const getAOTCompiledComponent = (standalone: boolean = false, dependencies: any[] = []) => {
      class ComponentClass {
        static ɵfac = () => new ComponentClass();
        static ɵcmp = defineComponent({
          standalone,
          type: ComponentClass,
          selectors: [['comp']],
          decls: 2,
          vars: 0,
          dependencies,
          consts: [['dir']],
          template:
              (rf: any, ctx: any) => {
                if (rf & 1) {
                  elementStart(0, 'div', 0);
                  text(1, 'Some template');
                  elementEnd();
                }
              },
          styles: ['body { margin: 0; }']
        });
      }
      setClassMetadata(
          ComponentClass, [{
            type: Component,
            args: [{
              standalone,
              imports: dependencies,
              selector: 'comp',
              templateUrl: './template.ng.html',
              styleUrls: ['./style.css'],
            }]
          }],
          null, null);
      return ComponentClass;
    };

    it('should allow to override a provider used in a dependency of a standalone component', () => {
      const A = new InjectionToken('A');

      @Directive({
        selector: '[dir]',
        providers: [{provide: A, useValue: 'A'}],
      })
      class SomeDir {
        constructor(@Inject(A) private tokenA: string, private elementRef: ElementRef) {}

        ngAfterViewInit() {
          this.elementRef.nativeElement.innerHTML = this.tokenA;
        }
      }

      const SomeComponent = getAOTCompiledComponent(true, [SomeDir]);
      TestBed.configureTestingModule({imports: [SomeComponent]});
      TestBed.overrideProvider(A, {useValue: 'Overridden A'});
      const fixture = TestBed.createComponent(SomeComponent);
      fixture.detectChanges();

      expect(fixture.nativeElement.textContent).toBe('Overridden A');
    });

    it('should have an ability to override template', () => {
      const SomeComponent = getAOTCompiledComponent();
      TestBed.configureTestingModule({declarations: [SomeComponent]});
      TestBed.overrideTemplateUsingTestingModule(SomeComponent, 'Template override');
      const fixture = TestBed.createComponent(SomeComponent);
      expect(fixture.nativeElement.innerHTML).toBe('Template override');
    });

    it('should have an ability to override template with empty string', () => {
      const SomeComponent = getAOTCompiledComponent();
      TestBed.configureTestingModule({declarations: [SomeComponent]});
      TestBed.overrideTemplateUsingTestingModule(SomeComponent, '');
      const fixture = TestBed.createComponent(SomeComponent);
      expect(fixture.nativeElement.innerHTML).toBe('');
    });

    it('should allow component in both in declarations and imports', () => {
      const SomeComponent = getAOTCompiledComponent();

      // This is an AOT compiled module which declares (but does not export) SomeComponent.
      class ModuleClass {
        static ɵmod = defineNgModule({
          type: ModuleClass,
          declarations: [SomeComponent],
        });
      }

      @Component({
        template: '<comp></comp>',

        selector: 'fixture',
      })
      class TestFixture {
      }

      TestBed.configureTestingModule({
        // Here, SomeComponent is both declared, and then the module which declares it is
        // also imported. This used to be a duplicate declaration error, but is now interpreted
        // to mean:
        // 1) Compile (or reuse) SomeComponent in the context of its original NgModule
        // 2) Make SomeComponent available in the scope of the testing module, even if it wasn't
        //    originally exported from its NgModule.
        //
        // This allows TestFixture to use SomeComponent, which is asserted below.
        declarations: [SomeComponent, TestFixture],
        imports: [ModuleClass],
      });
      const fixture = TestBed.createComponent(TestFixture);
      // The regex avoids any issues with styling attributes.
      expect(fixture.nativeElement.innerHTML)
          .toMatch(/<comp[^>]*>
]*>Some template<\/div><\/comp>/);
    });
  });

  describe('resetting ng defs', () => {
    it('should restore ng defs to their initial states', () => {
      @Pipe({name: 'somePipe', pure: true})
      class SomePipe {
        transform(value: string): string {
          return `transformed ${value}`;
        }
      }

      @Directive({selector: 'someDirective'})
      class SomeDirective {
        someProp = 'hello';
      }

      @Component({selector: 'comp', template: 'someText'})
      class SomeComponent {
      }

      @NgModule({declarations: [SomeComponent]})
      class SomeModule {
      }

      TestBed.configureTestingModule({imports: [SomeModule]});

      // adding Pipe and Directive via metadata override
      TestBed.overrideModule(
          SomeModule, {set: {declarations: [SomeComponent, SomePipe, SomeDirective]}});
      TestBed.overrideComponent(
          SomeComponent, {set: {template: `<span someDirective>{{'hello' | somePipe}}</span>`}});
      TestBed.createComponent(SomeComponent);

      const cmpDefBeforeReset = (SomeComponent as any).ɵcmp;
      expect(cmpDefBeforeReset.pipeDefs().length).toEqual(1);
      expect(cmpDefBeforeReset.directiveDefs().length).toEqual(2);  // directive + component

      const modDefBeforeReset = (SomeModule as any).ɵmod;
      const transitiveScope = modDefBeforeReset.transitiveCompileScopes.compilation;
      expect(transitiveScope.pipes.size).toEqual(1);
      expect(transitiveScope.directives.size).toEqual(2);

      TestBed.resetTestingModule();

      const cmpDefAfterReset = (SomeComponent as any).ɵcmp;
      expect(cmpDefAfterReset.pipeDefs).toBe(null);
      expect(cmpDefAfterReset.directiveDefs).toBe(null);

      const modDefAfterReset = (SomeModule as any).ɵmod;
      expect(modDefAfterReset.transitiveCompileScopes).toBe(null);
    });

    it('should cleanup ng defs for classes with no ng annotations (in case of inheritance)', () => {
      @Component({selector: 'someDirective', template: '...'})
      class SomeComponent {
      }

      class ComponentWithNoAnnotations extends SomeComponent {}

      @Directive({selector: 'some-directive'})
      class SomeDirective {
      }

      class DirectiveWithNoAnnotations extends SomeDirective {}

      @Pipe({name: 'some-pipe'})
      class SomePipe {
      }

      class PipeWithNoAnnotations extends SomePipe {}

      TestBed.configureTestingModule({
        declarations:
            [ComponentWithNoAnnotations, DirectiveWithNoAnnotations, PipeWithNoAnnotations]
      });
      TestBed.createComponent(ComponentWithNoAnnotations);

      expect(ComponentWithNoAnnotations.hasOwnProperty('ɵcmp')).toBeTruthy();
      expect(SomeComponent.hasOwnProperty('ɵcmp')).toBeTruthy();

      expect(DirectiveWithNoAnnotations.hasOwnProperty('ɵdir')).toBeTruthy();
      expect(SomeDirective.hasOwnProperty('ɵdir')).toBeTruthy();

      expect(PipeWithNoAnnotations.hasOwnProperty('ɵpipe')).toBeTruthy();
      expect(SomePipe.hasOwnProperty('ɵpipe')).toBeTruthy();

      TestBed.resetTestingModule();

      // ng defs should be removed from classes with no annotations
      expect(ComponentWithNoAnnotations.hasOwnProperty('ɵcmp')).toBeFalsy();
      expect(DirectiveWithNoAnnotations.hasOwnProperty('ɵdir')).toBeFalsy();
      expect(PipeWithNoAnnotations.hasOwnProperty('ɵpipe')).toBeFalsy();

      // ng defs should be preserved on super types
      expect(SomeComponent.hasOwnProperty('ɵcmp')).toBeTruthy();
      expect(SomeDirective.hasOwnProperty('ɵdir')).toBeTruthy();
      expect(SomePipe.hasOwnProperty('ɵpipe')).toBeTruthy();
    });

    it('should cleanup scopes (configured via `TestBed.configureTestingModule`) between tests',
       () => {
         @Component({
           selector: 'child',
           template: 'Child comp',
         })
         class ChildCmp {
         }

         @Component({
           selector: 'root',
           template: '<child></child>',
         })
         class RootCmp {
         }

         // Case #1: `RootCmp` and `ChildCmp` are both included in the `declarations` field of
         // the testing module, so `ChildCmp` is in the scope of `RootCmp`.
         TestBed.configureTestingModule({
           declarations: [RootCmp, ChildCmp],
         });

         let fixture = TestBed.createComponent(RootCmp);
         fixture.detectChanges();

         let childCmpInstance = fixture.debugElement.query(By.directive(ChildCmp));
         expect(childCmpInstance.componentInstance).toBeAnInstanceOf(ChildCmp);
         expect(fixture.nativeElement.textContent).toBe('Child comp');

         TestBed.resetTestingModule();

         const spy = spyOn(console, 'error');

         // Case #2: the `TestBed.configureTestingModule` was not invoked, thus the `ChildCmp`
         // should not be available in the `RootCmp` scope and no child content should be
         // rendered.
         fixture = TestBed.createComponent(RootCmp);
         // also an error should be logged to the user informing them that
         // the child component is not part of the module
         expect(spy).toHaveBeenCalledTimes(1);
         fixture.detectChanges();

         childCmpInstance = fixture.debugElement.query(By.directive(ChildCmp));
         expect(childCmpInstance).toBeNull();
         expect(fixture.nativeElement.textContent).toBe('');

         TestBed.resetTestingModule();

         // Case #3: `ChildCmp` is included in the `declarations` field, but `RootCmp` is not,
         // so `ChildCmp` is NOT in the scope of `RootCmp` component.
         TestBed.configureTestingModule({
           declarations: [ChildCmp],
         });

         fixture = TestBed.createComponent(RootCmp);
         fixture.detectChanges();

         childCmpInstance = fixture.debugElement.query(By.directive(ChildCmp));
         expect(childCmpInstance).toBeNull();
         expect(fixture.nativeElement.textContent).toBe('');
       });

    it('should clean up overridden providers for modules that are imported more than once', () => {
      @Injectable()
      class Token {
        name: string = 'real';
      }

      @NgModule({
        providers: [Token],
      })
      class Module {
      }

      TestBed.configureTestingModule({imports: [Module, Module]});
      TestBed.overrideProvider(Token, {useValue: {name: 'fake'}});

      expect(TestBed.inject(Token).name).toEqual('fake');

      TestBed.resetTestingModule();

      // The providers for the module should have been restored to the original array, with
      // no trace of the overridden providers.
      expect((Module as any).ɵinj.providers).toEqual([Token]);
    });

    it('should clean up overridden providers on components whose modules are compiled more than once',
       async () => {
         @Injectable()
         class SomeInjectable {
           id: string|undefined;
         }

         @Component({providers: [SomeInjectable]})
         class ComponentWithProvider {
           constructor(readonly injectable: SomeInjectable) {}
         }

         @NgModule({declarations: [ComponentWithProvider]})
         class MyModule {
         }

         TestBed.configureTestingModule({imports: [MyModule]});
         const originalResolver = (ComponentWithProvider as any).ɵcmp.providersResolver;
         TestBed.overrideProvider(SomeInjectable, {useValue: {id: 'fake'}});

         const compiler = TestBed.inject(Compiler);
         await compiler.compileModuleAsync(MyModule);
         compiler.compileModuleSync(MyModule);

         TestBed.resetTestingModule();
         expect((ComponentWithProvider as any).ɵcmp.providersResolver).toEqual(originalResolver);
       });
  });

  describe('overrides provider', () => {
    it('with empty provider object', () => {
      @Injectable()
      class Service {
      }
      TestBed.overrideProvider(Service, {});
      // Should be able to get a Service instance because it has no dependencies that can't be
      // resolved
      expect(TestBed.inject(Service)).toBeDefined();
    });
  });

  it('should handle provider overrides when module imports are provided as a function', () => {
    class InjectedString {
      value?: string;
    }

    @Component({template: '{{injectedString.value}}'})
    class AppComponent {
      constructor(public injectedString: InjectedString) {}
    }

    @NgModule({})
    class DependencyModule {
    }

    // We need to write the compiler output manually here,
    // because it depends on code generated by ngcc.
    class TestingModule {
      static ɵmod = defineNgModule({type: TestingModule});
      static ɵinj = defineInjector({imports: [DependencyModule]});
    }
    setNgModuleScope(TestingModule, {imports: () => [DependencyModule]});

    TestBed
        .configureTestingModule({
          imports: [TestingModule],
          declarations: [AppComponent],
          providers: [{provide: InjectedString, useValue: {value: 'initial'}}],
        })
        .compileComponents();

    TestBed.overrideProvider(InjectedString, {useValue: {value: 'changed'}}).compileComponents();

    const fixture = TestBed.createComponent(AppComponent);
    fixture.detectChanges();
    expect(fixture!.nativeElement.textContent).toContain('changed');
  });

  describe('TestBed.inject', () => {
    describe('injection flags', () => {
      it('should be able to optionally inject a token', () => {
        const TOKEN = new InjectionToken<string>('TOKEN');

        expect(TestBed.inject(TOKEN, undefined, {optional: true})).toBeNull();
        expect(TestBed.inject(TOKEN, undefined, InjectFlags.Optional)).toBeNull();

        expect(TestBed.inject(TOKEN, undefined, {optional: true})).toBeNull();
        expect(TestBed.inject(TOKEN, undefined, InjectFlags.Optional)).toBeNull();
      });

      it('should include `null` into the result type when the optional flag is used', () => {
        const TOKEN = new InjectionToken<string>('TOKEN');

        const flags: InjectOptions = {optional: true};
        let result = TestBed.inject(TOKEN, undefined, flags);
        expect(result).toBe(null);

        // Verify that `null` can be a valid value (from typing standpoint),
        // the line below would fail a type check in case the result doesn't
        // have `null` in the type.
        result = null;
      });

      it('should be able to use skipSelf injection', () => {
        const TOKEN = new InjectionToken<string>('TOKEN');
        TestBed.configureTestingModule({
          providers: [{provide: TOKEN, useValue: 'from TestBed'}],
        });

        expect(TestBed.inject(TOKEN)).toBe('from TestBed');

        expect(TestBed.inject(TOKEN, undefined, {skipSelf: true, optional: true})).toBeNull();
        expect(TestBed.inject(TOKEN, undefined, InjectFlags.SkipSelf | InjectFlags.Optional))
            .toBeNull();
      });
    });
  });

  it('should be able to call Testbed.runInInjectionContext in tests', () => {
    const expectedValue = 'testValue';
    @Injectable({providedIn: 'root'})
    class SomeInjectable {
      readonly instanceValue = expectedValue;
    }

    function functionThatUsesInject(): string {
      return inject(SomeInjectable).instanceValue;
    }

    expect(TestBed.runInInjectionContext(functionThatUsesInject)).toEqual(expectedValue);
  });
});

describe('TestBed module teardown', () => {
  beforeEach(() => {
    TestBed.resetTestingModule();
  });

  it('should tear down the test module by default', () => {
    expect(TestBedImpl.INSTANCE.shouldTearDownTestingModule()).toBe(true);
  });

  it('should be able to configure the teardown behavior', () => {
    TestBed.configureTestingModule({teardown: {destroyAfterEach: false}});
    expect(TestBedImpl.INSTANCE.shouldTearDownTestingModule()).toBe(false);
  });

  it('should reset the teardown behavior back to the default when TestBed is reset', () => {
    TestBed.configureTestingModule({teardown: {destroyAfterEach: false}});
    expect(TestBedImpl.INSTANCE.shouldTearDownTestingModule()).toBe(false);
    TestBed.resetTestingModule();
    expect(TestBedImpl.INSTANCE.shouldTearDownTestingModule()).toBe(true);
  });

  it('should destroy test module providers when test module teardown is enabled', () => {
    SimpleService.ngOnDestroyCalls = 0;
    TestBed.configureTestingModule({
      providers: [SimpleService],
      declarations: [GreetingCmp],
      teardown: {destroyAfterEach: true}
    });
    TestBed.createComponent(GreetingCmp);

    expect(SimpleService.ngOnDestroyCalls).toBe(0);
    TestBed.resetTestingModule();
    expect(SimpleService.ngOnDestroyCalls).toBe(1);
  });

  it('should remove the fixture root element from the DOM when module teardown is enabled', () => {
    TestBed.configureTestingModule({
      declarations: [SimpleCmp],
      teardown: {destroyAfterEach: true},
    });
    const fixture = TestBed.createComponent(SimpleCmp);
    const fixtureDocument = fixture.nativeElement.ownerDocument;

    expect(fixtureDocument.body.contains(fixture.nativeElement)).toBe(true);
    TestBed.resetTestingModule();
    expect(fixtureDocument.body.contains(fixture.nativeElement)).toBe(false);
  });

  it('should re-throw errors that were thrown during fixture cleanup', () => {
    @Component({template: ''})
    class ThrowsOnDestroy {
      ngOnDestroy() {
        throw Error('oh no');
      }
    }

    TestBed.configureTestingModule({
      declarations: [ThrowsOnDestroy],
      teardown: {destroyAfterEach: true},
    });
    TestBed.createComponent(ThrowsOnDestroy);

    const spy = spyOn(console, 'error');
    expect(() => TestBed.resetTestingModule())
        .toThrowError('1 component threw errors during cleanup');
    expect(spy).toHaveBeenCalledTimes(1);
  });

  it('should not interrupt fixture destruction if an error is thrown', () => {
    @Component({template: ''})
    class ThrowsOnDestroy {
      ngOnDestroy() {
        throw Error('oh no');
      }
    }

    TestBed.configureTestingModule({
      declarations: [ThrowsOnDestroy],
      teardown: {destroyAfterEach: true},
    });

    for (let i = 0; i < 3; i++) {
      TestBed.createComponent(ThrowsOnDestroy);
    }

    const spy = spyOn(console, 'error');
    expect(() => TestBed.resetTestingModule())
        .toThrowError('3 components threw errors during cleanup');
    expect(spy).toHaveBeenCalledTimes(3);
  });

  it('should re-throw errors that were thrown during module teardown by default', () => {
    @Injectable()
    class ThrowsOnDestroy {
      ngOnDestroy() {
        throw Error('oh no');
      }
    }

    @Component({template: ''})
    class App {
      constructor(_service: ThrowsOnDestroy) {}
    }

    TestBed.configureTestingModule({
      providers: [ThrowsOnDestroy],
      declarations: [App],
      teardown: {destroyAfterEach: true},
    });
    TestBed.createComponent(App);

    expect(() => TestBed.resetTestingModule()).toThrowError('oh no');
  });

  it('should be able to opt out of rethrowing of errors coming from module teardown', () => {
    @Injectable()
    class ThrowsOnDestroy {
      ngOnDestroy() {
        throw Error('oh no');
      }
    }

    @Component({template: ''})
    class App {
      constructor(_service: ThrowsOnDestroy) {}
    }

    TestBed.configureTestingModule({
      providers: [ThrowsOnDestroy],
      declarations: [App],
      teardown: {destroyAfterEach: true, rethrowErrors: false},
    });
    TestBed.createComponent(App);

    const spy = spyOn(console, 'error');
    expect(() => TestBed.resetTestingModule()).not.toThrow();
    expect(spy).toHaveBeenCalledTimes(1);
  });

  it('should remove the styles associated with a test component when the test module is torn down',
     () => {
       @Component({
         template: 'Hello',
         styles: [`span {color: hotpink;}`],
       })
       class StyledComp1 {
       }

       @Component({
         template: '
Hello
',
         styles: [`div {color: red;}`],
       })
       class StyledComp2 {
       }

       TestBed.configureTestingModule({
         declarations: [StyledComp1, StyledComp2],
         teardown: {destroyAfterEach: true},
       });

       const fixtures = [
         TestBed.createComponent(StyledComp1),
         TestBed.createComponent(StyledComp2),
       ];
       const fixtureDocument = fixtures[0].nativeElement.ownerDocument;
       const styleCountBefore = fixtureDocument.querySelectorAll('style').length;

       // Note that we can only assert that the behavior works as expected by checking that the
       // number of stylesheets has decreased. We can't expect that they'll be zero, because there
       // may by stylesheets leaking in from other tests that don't use the module teardown
       // behavior.
       expect(styleCountBefore).toBeGreaterThan(0);
       TestBed.resetTestingModule();
       expect(fixtureDocument.querySelectorAll('style').length).toBeLessThan(styleCountBefore);
     });

  it('should remove the fixture root element from the DOM when module teardown is enabled', () => {
    TestBed.configureTestingModule({
      declarations: [SimpleCmp],
      teardown: {destroyAfterEach: true},
    });
    const fixture = TestBed.createComponent(SimpleCmp);
    const fixtureDocument = fixture.nativeElement.ownerDocument;

    expect(fixtureDocument.body.contains(fixture.nativeElement)).toBe(true);
    TestBed.resetTestingModule();
    expect(fixtureDocument.body.contains(fixture.nativeElement)).toBe(false);
  });

  it('should rethrow errors based on the default teardown behavior', () => {
    expect(TestBedImpl.INSTANCE.shouldRethrowTeardownErrors())
        .toBe(TEARDOWN_TESTING_MODULE_ON_DESTROY_DEFAULT);
  });

  it('should rethrow errors if the option is omitted and test teardown is enabled', () => {
    TestBed.configureTestingModule({teardown: {destroyAfterEach: true}});
    expect(TestBedImpl.INSTANCE.shouldRethrowTeardownErrors()).toBe(true);
  });

  it('should not rethrow errors if the option is omitted and test teardown is disabled', () => {
    TestBed.configureTestingModule({teardown: {destroyAfterEach: false}});
    expect(TestBedImpl.INSTANCE.shouldRethrowTeardownErrors()).toBe(false);
  });

  it('should rethrow errors if the option is enabled, but teardown is disabled', () => {
    TestBed.configureTestingModule({teardown: {destroyAfterEach: false, rethrowErrors: true}});
    expect(TestBedImpl.INSTANCE.shouldRethrowTeardownErrors()).toBe(true);
  });

  it('should not rethrow errors if the option is disabled, but teardown is enabled', () => {
    TestBed.configureTestingModule({teardown: {destroyAfterEach: true, rethrowErrors: false}});
    expect(TestBedImpl.INSTANCE.shouldRethrowTeardownErrors()).toBe(false);
  });
});

describe('TestBed module `errorOnUnknownElements`', () => {
  beforeEach(() => {
    TestBed.resetTestingModule();
  });

  it('should not throw based on the default behavior', () => {
    expect(TestBedImpl.INSTANCE.shouldThrowErrorOnUnknownElements())
        .toBe(THROW_ON_UNKNOWN_ELEMENTS_DEFAULT);
  });

  it('should not throw if the option is omitted', () => {
    TestBed.configureTestingModule({});
    expect(TestBedImpl.INSTANCE.shouldThrowErrorOnUnknownElements()).toBe(false);
  });

  it('should be able to configure the option', () => {
    TestBed.configureTestingModule({errorOnUnknownElements: true});
    expect(TestBedImpl.INSTANCE.shouldThrowErrorOnUnknownElements()).toBe(true);
  });

  it('should reset the option back to the default when TestBed is reset', () => {
    TestBed.configureTestingModule({errorOnUnknownElements: true});
    expect(TestBedImpl.INSTANCE.shouldThrowErrorOnUnknownElements()).toBe(true);
    TestBed.resetTestingModule();
    expect(TestBedImpl.INSTANCE.shouldThrowErrorOnUnknownElements()).toBe(false);
  });
});

describe('TestBed module `errorOnUnknownProperties`', () => {
  beforeEach(() => {
    TestBed.resetTestingModule();
  });

  it('should not throw based on the default behavior', () => {
    expect(TestBedImpl.INSTANCE.shouldThrowErrorOnUnknownProperties())
        .toBe(THROW_ON_UNKNOWN_PROPERTIES_DEFAULT);
  });

  it('should not throw if the option is omitted', () => {
    TestBed.configureTestingModule({});
    expect(TestBedImpl.INSTANCE.shouldThrowErrorOnUnknownProperties()).toBe(false);
  });

  it('should be able to configure the option', () => {
    TestBed.configureTestingModule({errorOnUnknownProperties: true});
    expect(TestBedImpl.INSTANCE.shouldThrowErrorOnUnknownProperties()).toBe(true);
  });

  it('should reset the option back to the default when TestBed is reset', () => {
    TestBed.configureTestingModule({errorOnUnknownProperties: true});
    expect(TestBedImpl.INSTANCE.shouldThrowErrorOnUnknownProperties()).toBe(true);
    TestBed.resetTestingModule();
    expect(TestBedImpl.INSTANCE.shouldThrowErrorOnUnknownProperties()).toBe(false);
  });
});


text:
Anno | 2012

Luogo | Grunerlokka, Oslo (Norvegia)

Designers | [Timo Arnall](http://www.elasticspace.com/) and [Voyoslo Studio](http://voyoslo.com/)

Video | [+](https://vimeo.com/20412632)

Articoli | [+](http://voyoslo.com/projects/immaterials-wifi-light-painting/)
[+](http://www.designboom.com/design/immaterials-light-painting-wifi-by-timo-arnall-jorn-knutsen-einar-sneve-martinussen/)
[+](http://onlinelibrary.wiley.com/store/10.1111/j.1740-9713.2013.00683.x/asset/j.1740-9713.2013.00683.x.pdf;jsessionid=59514BD3BCDAF3B661EE990359E0F7AE.f02t03?v=1&t=j0ze4a20&s=92fd4a1950509d60c8c44615119e6f814018c4f3)

![light painting wifi](https://i.vimeocdn.com/video/130418741_1280x720.jpg)

#### What's?
L'obiettivo di questa installazione, realizzata nella città di Oslo, è quello di rendere quasi tangibile ciò che in realtà è per propria natura invisibile. In termini pratici si tratta di rendere visibile il flusso delle reti Wifi presenti in alcuni ambienti della città mescolando quindi la materialità di alcuni elementi all'immaterialità di altri.

#### How it  works?
L'installazione prevede l'utilizzo di assi di legno lunghe 4 metri sulle quali sono stati applicate delle strisce led formate da 80 diodi. I led, attivati mediante una scheda di rete collegata ad un computer, mostreranno a seconda del segnale ricevuto la potenza del wifi rilevato. Attraverso il movimento dell'asta di led è stato possibile con la tecnica del light painting fotografare il muro di luce.

#### What does it mean?
Si tratta di porre l'accento sull'importanza della tecnologia e in particolare delle reti wifi, dimostrandoci che pur essendo totalmente immersi all'interno di questa massa di informazioni non ce ne rendiamo conto.

#### What if...
Sarebbe stato interessante aggiungere altre variabili come la capacità di download o di upload delle reti tramutando queste informazioni in differenti colorazioni.

## Related project
### Bleecker Street Documents

Anno | 2013

Luogo | Vienna (Austria)

Designer | [Peter Jellitsch](http://www.peterjellitsch.com/)

Video | [+](https://vimeo.com/88443248)

Articoli | [+](https://www.theverge.com/2013/1/17/3885984/peter-jellitsch-bleecker-street-documents-wifi-sculpture)
[+](https://creators.vice.com/en_us/article/pgzne9/wi-fi-signal-visualized-as-a-sculpture)
[+](https://www.fastcodesign.com/1671628/infographic-sculptures-made-by-measuring-wi-fi-signals)

![Bleecker Street Documents](http://www.peterjellitsch.com/wp-content/uploads/2012/12/BSD_Installation_LowRes.jpg)

Per la maggior parte delle persone, la forza di un segnale Wi-Fi non è altro che un numero, una metrica isolata e completamente utilitaristica. Ma per l'artista e l'architetto austriaco Peter Jellitsch, questi dati fanno parte di un insieme più ampio di forze invisibili che ci avvolgono silenziosamente. È questo spazio invisibile _"frammentato"_ che Jellitsch ha cercato di catturare nel suo ultimo lavoro, _"Bleecker Street Documents"_.
L'artista dopo aver soggiornato 45 giorni a New York, ha creato questa installazione che vuole essere in parti scultura, diario e visualizzazione dei dati. Ogni giorno durante il suo soggiorno, Jellitsch avrebbe misurato e registrato la potenza del segnale wifi nel suo appartamento, tracciando ogni punto dati in ordine cronologico su un piano bianco piatto.
Quando il segnale era forte, ha sollevato la parte del piano corrispondente a quel particolare giorno, mentre quando debole lo ha lasciato piatto.
La scultura risultante è un modello 3D, ottenuto tramite una macchina CNC, che richiama la forma di montagne poligonali che Jellitsch definisce una _"descrizione spaziale frammentata"_.

### Light Bridge

Anno | 2011

Luogo | Boston, Massachusetts (USA)

Designers | [Susanne Seitinger](http://susanneseitinger.com/) and [Pol Pla](http://polpla.cat/)

Video | [+](https://vimeo.com/23963465)

Articoli | [+](https://arts.mit.edu/events/susanne-seitinger-and-pol-pla-lightbridge/)
[+](http://blog.netd.it/article/LightBridge_il_ponte_luminoso)

![Light bridge](http://polpla.cat/projects/img/LightBridge1.jpg)

LightBridge è un display urbano interattivo per celebrare il 150° anniversario della MIT. L'installazione, che si è svolta presso _l'Harvard Bridge_ nel maggio 2011, è composta da 10.000 luci a LED indirizzabili individualmente che reagiscono a diversi elementi dell'ambiente. Dalla visualizzazione dei modelli di vento alla creazione di interazioni coinvolgenti con i pedoni, il comportamento del ponte si è evoluto per tutta la notte.
Il display a 10.000 pixel è stato attivato da sensori (sensori di prossimità, telecamere, pulsanti, microfoni, telefoni cellulari) che hanno risposto al movimento e alle attività degli spettatori della zona. Combinando sensori e illuminazione programmabili. Il progetto ha illustrato il potenziale di schermi urbani orientati all'utente e nuove configurazioni di display a bassa risoluzione per sfocare i confini tra la tradizionale illuminazione cittadina e le infrastrutture reattive di domani.

### Spirit Photographs - Wireless Spectre

Anno | 2013

Luogo | (U.K.)

Designers | [Luis Hernan](http://www.digitalethereal.com/)

Video | [+](https://vimeo.com/81541763)

Articoli | [+](https://www.seeker.com/digital-spectres-reveal-invisible-wireless-world-1768581350.html)
[+](http://blog.netd.it/article/LightBridge_il_ponte_luminoso)

![Digital](http://www.digitalethereal.com/assets/portfolio/group1-camera2.jpg)

Poche forze formano il mondo moderno più di Internet e tuttavia è una presenza invisibile di cui conosciamo solo l'esistenza. Luis Hernan ha cercato di rendere tangibile tale presenza mediante un sistema che esegue la scansione delle reti wireless e crea delle immagini in cui il grado di intensità del segnale wifi è messo in relazione a luci LED colorate. Questo ci permette di vedere i seganli WiFi intorno a noi.
_"Spirit Photographs - Wireless Spectre"_ è un'esplorazione performativa e fotografica dello spazio hertziano.
Le immagini risultano dalla descrizione dello spazio attraverso una prestazione del _"dispositivo Kirlian"_, che trasforma la forza del segnale in colore chiaro (rosso per alta intensità, azzurro a bassa intensità).
Accoppiato con la fotografia a lunga esposizione, è possibile registrare le qualità mutevoli delle reti wireless.
Questo progetto mette in relazione le tecnologie digitali e l'infrastruttura invisibile che lo fonda.


text:
package com.routeme.service;

import java.util.List;
import java.util.Optional;

import com.routeme.dto.EventDTO;
import com.routeme.dto.UserDTO;

public interface UserService {

    Optional<UserDTO> create(UserDTO user);

    Optional<UserDTO> findByCredentials(String email, String password);

    UserDTO delete(String id);

    List<UserDTO> findAll();

    UserDTO findById(String id);

    UserDTO update(UserDTO user);

    UserDTO likeRoute(EventDTO eventEntry);

    UserDTO dislikeRoute(EventDTO eventEntry);

    UserDTO setPreferences(UserDTO preferencesEntry);

}