Repository: strawberry-graphql/strawberry

Issue:
Strawberry cli commands fail with error: strawberry.exe\__main__.py not found
After upgrading strawberry to latest version (0.154.1), I am unable to run any strawberry cli commands.

## Describe the Bug
- Upgraded strawberry from 0.152.0 to 0.154.1
```
poetry add strawberry-graphql[debug-server]@0.154.1
```
- Executed below commands:
```
strawberry server myapp.schema
strawberry export-schema myapp.schema:schema
```
- Both these commands are failing in below error:

**FileNotFoundError: [WinError 3] The system cannot find the path specified: 'C:\\Users\\myyuser\\AppData\\Local\\pypoetry\\Cache\\virtualenvs\\straw-k47ybk7v-py3.10\\Scripts\\strawberry.exe\\\_\_main\_\_.py'**

## System Information

 - Operating system: Windows 10
 - Strawberry version (if applicable): 0.154.1
 - Python: 3.10.9

## Additional Context

There is no issue with strawberry cli in version 0.152.0 which I am using currently. If we downgrade the package to this version, cli commands work just fine.

Strawberry cli commands fail with error: strawberry.exe\__main__.py not found
After upgrading strawberry to latest version (0.154.1), I am unable to run any strawberry cli commands.

## Describe the Bug
- Upgraded strawberry from 0.152.0 to 0.154.1
```
poetry add strawberry-graphql[debug-server]@0.154.1
```
- Executed below commands:
```
strawberry server myapp.schema
strawberry export-schema myapp.schema:schema
```
- Both these commands are failing in below error:

**FileNotFoundError: [WinError 3] The system cannot find the path specified: 'C:\\Users\\myyuser\\AppData\\Local\\pypoetry\\Cache\\virtualenvs\\straw-k47ybk7v-py3.10\\Scripts\\strawberry.exe\\\_\_main\_\_.py'**

## System Information

 - Operating system: Windows 10
 - Strawberry version (if applicable): 0.154.1
 - Python: 3.10.9

## Additional Context

There is no issue with strawberry cli in version 0.152.0 which I am using currently. If we downgrade the package to this version, cli commands work just fine.



Discussion:
@gauthamkamath unfortunately I was not able to reproduce this bug on my system. 

Operating system: Windows 10
Strawberry version (if applicable): 0.154.1
Python: 3.9.13

Could you try the following?

1. Create a new directory for testing
2. Run `python -m venv .venv`
3. Activate venv (assuming powershell): `.venv/Scripts/Activate.ps1`
4. Upgrade pip, install poetry, and configure config to use venv.
    ```shell
    python -m pip install --upgrade pip
    pip install poetry
    poetry config virtualenvs.prefer-active-python true
    ```
5. Initialize project `poetry init`
6. Add Strawberry dependency: `poetry add strawberry-graphql[debug-server]@0.154.1`
7. Create a `app.py` file with the following contents:
    ```python
    import strawberry
    
    @strawberry.type
    class Query:
    
        foo: str
    
    schema = strawberry.Schema(Query)
    ```
8. Run strawberry server and export-schema:
    ```shell
    strawberry server app
    strawberry export-schema app
    ```
Hi @skilkis , your code works perfectly fine with version: 0.154.1 . 
But I am getting the same issue when I try running with this code: <https://github.com/gauthamkamath/straw.git> (same code as <https://github.com/strawberry-graphql/strawberry/issues/2397#issuecomment-1381711431>)
Could you please have a look?
@gauthamkamath I'll check out your code tomorrow, thanks for the link 😊
@gauthamkamath unfortunately I was not able to reproduce this bug on my system. 

Operating system: Windows 10
Strawberry version (if applicable): 0.154.1
Python: 3.9.13

Could you try the following?

1. Create a new directory for testing
2. Run `python -m venv .venv`
3. Activate venv (assuming powershell): `.venv/Scripts/Activate.ps1`
4. Upgrade pip, install poetry, and configure config to use venv.
    ```shell
    python -m pip install --upgrade pip
    pip install poetry
    poetry config virtualenvs.prefer-active-python true
    ```
5. Initialize project `poetry init`
6. Add Strawberry dependency: `poetry add strawberry-graphql[debug-server]@0.154.1`
7. Create a `app.py` file with the following contents:
    ```python
    import strawberry
    
    @strawberry.type
    class Query:
    
        foo: str
    
    schema = strawberry.Schema(Query)
    ```
8. Run strawberry server and export-schema:
    ```shell
    strawberry server app
    strawberry export-schema app
    ```
Hi @skilkis , your code works perfectly fine with version: 0.154.1 . 
But I am getting the same issue when I try running with this code: <https://github.com/gauthamkamath/straw.git> (same code as <https://github.com/strawberry-graphql/strawberry/issues/2397#issuecomment-1381711431>)
Could you please have a look?
@gauthamkamath I'll check out your code tomorrow, thanks for the link 😊

Resolving patch:
diff --git a/strawberry/lazy_type.py b/strawberry/lazy_type.py
--- a/strawberry/lazy_type.py
+++ b/strawberry/lazy_type.py
@@ -48,12 +48,16 @@ def resolve_type(self) -> Type:
             if main_module.__spec__ and main_module.__spec__.name == self.module:
                 module = main_module
             elif hasattr(main_module, "__file__") and hasattr(module, "__file__"):
-                if (
-                    main_module.__file__
-                    and module.__file__
-                    and Path(main_module.__file__).samefile(module.__file__)
-                ):
-                    module = main_module
+                main_file = main_module.__file__
+                module_file = module.__file__
+                if main_file and module_file:
+                    try:
+                        is_samefile = Path(main_file).samefile(module_file)
+                    except FileNotFoundError:
+                        # Can be raised when run through the CLI as the __main__ file
+                        # path contains `strawberry.exe`
+                        is_samefile = False
+                    module = main_module if is_samefile else module
         return module.__dict__[self.type_name]
 
     # this empty call method allows LazyTypes to be used in generic types


Test patch:
diff --git a/tests/schema/test_lazy/schema.py b/tests/schema/test_lazy/schema.py
new file mode 100644
--- /dev/null
+++ b/tests/schema/test_lazy/schema.py
@@ -0,0 +1,4 @@
+import strawberry
+from tests.schema.test_lazy.type_c import Query
+
+schema = strawberry.Schema(query=Query)
diff --git a/tests/schema/test_lazy/test_lazy_generic.py b/tests/schema/test_lazy/test_lazy_generic.py
--- a/tests/schema/test_lazy/test_lazy_generic.py
+++ b/tests/schema/test_lazy/test_lazy_generic.py
@@ -1,7 +1,9 @@
 import os
 import subprocess
 import sys
+import sysconfig
 import textwrap
+from pathlib import Path
 from typing import TYPE_CHECKING, Generic, List, Optional, Sequence, TypeVar
 from typing_extensions import Annotated
 
@@ -12,6 +14,9 @@
 if TYPE_CHECKING:
     from tests.schema.test_lazy.type_a import TypeA  # noqa
 
+STRAWBERRY_EXECUTABLE = next(
+    Path(sysconfig.get_path("scripts")).glob("strawberry*"), None
+)
 
 T = TypeVar("T")
 
@@ -75,8 +80,18 @@ class Query:
 @pytest.mark.parametrize(
     "commands",
     [
-        pytest.param(["tests/schema/test_lazy/type_c.py"], id="script"),
-        pytest.param(["-m", "tests.schema.test_lazy.type_c"], id="module"),
+        pytest.param(
+            [sys.executable, "tests/schema/test_lazy/type_c.py"],
+            id="script",
+        ),
+        pytest.param(
+            [sys.executable, "-m", "tests.schema.test_lazy.type_c"],
+            id="module",
+        ),
+        pytest.param(
+            [STRAWBERRY_EXECUTABLE, "export-schema", "tests.schema.test_lazy.schema"],
+            id="cli",
+        ),
     ],
 )
 def test_lazy_types_loaded_from_same_module(commands: Sequence[str]):
@@ -86,12 +101,30 @@ def test_lazy_types_loaded_from_same_module(commands: Sequence[str]):
       `subprocess` is used since the test must be run as the main module / script.
     """
     result = subprocess.run(
-        args=[sys.executable, *commands],
+        args=[*commands],
         env=os.environ,
         capture_output=True,
     )
     result.check_returncode()
 
+    expected = """\
+    type Query {
+      typeA: TypeCEdge!
+      typeB: TypeCEdge!
+    }
+
+    type TypeC {
+      name: String!
+    }
+
+    type TypeCEdge {
+      node: TypeC!
+    }
+    """
+
+    schema_sdl = result.stdout.decode().replace(os.linesep, "\n")
+    assert textwrap.dedent(schema_sdl) == textwrap.dedent(expected)
+
 
 def test_lazy_types_declared_within_optional():
     from tests.schema.test_lazy.type_c import Edge, TypeC
diff --git a/tests/schema/test_lazy/type_c.py b/tests/schema/test_lazy/type_c.py
--- a/tests/schema/test_lazy/type_c.py
+++ b/tests/schema/test_lazy/type_c.py
@@ -1,3 +1,4 @@
+import sys
 from typing import Generic, TypeVar
 from typing_extensions import Annotated
 
@@ -27,3 +28,4 @@ class Query:
 
 if __name__ == "__main__":
     schema = strawberry.Schema(query=Query)
+    sys.stdout.write(f"{schema.as_str()}\n")