Repository: pydantic/pydantic

Issue:
Union produces anyOf instead of oneOf for OpenAPI generation
### Checks

* [x] I added a descriptive title to this issue
* [x] I have searched (google, github) for similar issues and couldn't find anything
* [x] I have read and followed [the docs](https://pydantic-docs.helpmanual.io/) and still think this is a bug

<!-- Sorry to sound so draconian, but every second saved replying to issues is time spend improving pydantic :-) -->

# Bug

Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`:
```
             pydantic version: 1.9.0
            pydantic compiled: True
                 install path: C:\Users\DEKOEHLS\Programme\Anaconda3\Lib\site-packages\pydantic
               python version: 3.9.7 (default, Sep 16 2021, 16:59:28) [MSC v.1916 64 bit (AMD64)]
                     platform: Windows-10-10.0.19042-SP0
     optional deps. installed: ['dotenv', 'typing-extensions']
```
<!-- or if you're using pydantic prior to v1.3, manually include: OS, python version and pydantic version -->

<!-- Please read the [docs](https://pydantic-docs.helpmanual.io/) and search through issues to
confirm your bug hasn't already been reported. -->

<!-- Where possible please include a self-contained code snippet describing your bug: -->

```py
from typing import Literal, Union
from pydantic import BaseModel, Field


class Cat(BaseModel):
    pet_type: Literal['cat']
    meows: int


class Dog(BaseModel):
    pet_type: Literal['dog']
    barks: float


class Pet(BaseModel):
    __root__: Union[Cat, Dog] = Field(..., discriminator='pet_type')

Pet.schema_json()
```

Hi all,

Example from https://pydantic-docs.helpmanual.io/usage/types/#discriminated-unions-aka-tagged-unions:

Using the class Pet above in FastAPI to allow either Cat or Dog as an input leads to an OpenAPI.json which makes Pet like (printed as yaml)

````yaml
Pet:
  anyOf:
  - $ref: '#/components/schemas/Cat'
  - $ref: '#/components/schemas/Dog'
  
  discriminator:
    propertyName: pet_type
````

both OpenApi (https://swagger.io/docs/specification/data-models/oneof-anyof-allof-not/) and the specification https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.2.md#discriminatorObject linked by the pydantic docs (link on top) state that it should be oneOf.
This also corresponds to the "typing" interpretation of *Union* which is, besides the naming, not a union of the arguments but a "one of those elements"

I already found a issue here which has been closed:
https://github.com/samuelcolvin/pydantic/issues/656
I didn't understand the arguments to be honest, However, I think it's just wrong to make it an anyOf.

I tried to post it on FastAPI since it leads to an incorrect openapi.json so I thought maybe a workaround on FastAPI side was meaningful. They forwarded me back here though.
https://github.com/tiangolo/fastapi/issues/4959

Best
Stefan


Discussion:

Resolving patch:
diff --git a/pydantic/schema.py b/pydantic/schema.py
--- a/pydantic/schema.py
+++ b/pydantic/schema.py
@@ -705,7 +705,8 @@ def field_singleton_sub_fields_schema(
     else:
         s: Dict[str, Any] = {}
         # https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#discriminator-object
-        if field.discriminator_key is not None:
+        field_has_discriminator: bool = field.discriminator_key is not None
+        if field_has_discriminator:
             assert field.sub_fields_mapping is not None
 
             discriminator_models_refs: Dict[str, Union[str, Dict[str, Any]]] = {}
@@ -748,16 +749,16 @@ def field_singleton_sub_fields_schema(
             definitions.update(sub_definitions)
             if schema_overrides and 'allOf' in sub_schema:
                 # if the sub_field is a referenced schema we only need the referenced
-                # object. Otherwise we will end up with several allOf inside anyOf.
+                # object. Otherwise we will end up with several allOf inside anyOf/oneOf.
                 # See https://github.com/pydantic/pydantic/issues/1209
                 sub_schema = sub_schema['allOf'][0]
 
-            if sub_schema.keys() == {'discriminator', 'anyOf'}:
-                # we don't want discriminator information inside anyOf choices, this is dealt with elsewhere
+            if sub_schema.keys() == {'discriminator', 'oneOf'}:
+                # we don't want discriminator information inside oneOf choices, this is dealt with elsewhere
                 sub_schema.pop('discriminator')
             sub_field_schemas.append(sub_schema)
             nested_models.update(sub_nested_models)
-        s['anyOf'] = sub_field_schemas
+        s['oneOf' if field_has_discriminator else 'anyOf'] = sub_field_schemas
         return s, definitions, nested_models
 
 


Test patch:
diff --git a/tests/test_dataclasses.py b/tests/test_dataclasses.py
--- a/tests/test_dataclasses.py
+++ b/tests/test_dataclasses.py
@@ -1190,7 +1190,7 @@ class Users(BaseModel):
     }
 
 
-def test_discrimated_union_basemodel_instance_value():
+def test_discriminated_union_basemodel_instance_value():
     @pydantic.dataclasses.dataclass
     class A:
         l: Literal['a']
@@ -1212,7 +1212,7 @@ class Top:
             'sub': {
                 'title': 'Sub',
                 'discriminator': {'propertyName': 'l', 'mapping': {'a': '#/definitions/A', 'b': '#/definitions/B'}},
-                'anyOf': [{'$ref': '#/definitions/A'}, {'$ref': '#/definitions/B'}],
+                'oneOf': [{'$ref': '#/definitions/A'}, {'$ref': '#/definitions/B'}],
             }
         },
         'required': ['sub'],
diff --git a/tests/test_forward_ref.py b/tests/test_forward_ref.py
--- a/tests/test_forward_ref.py
+++ b/tests/test_forward_ref.py
@@ -588,7 +588,7 @@ class Dog(BaseModel):
     assert module.Pet.schema() == {
         'title': 'Pet',
         'discriminator': {'propertyName': 'type', 'mapping': {'cat': '#/definitions/Cat', 'dog': '#/definitions/Dog'}},
-        'anyOf': [{'$ref': '#/definitions/Cat'}, {'$ref': '#/definitions/Dog'}],
+        'oneOf': [{'$ref': '#/definitions/Cat'}, {'$ref': '#/definitions/Dog'}],
         'definitions': {
             'Cat': {
                 'title': 'Cat',
diff --git a/tests/test_schema.py b/tests/test_schema.py
--- a/tests/test_schema.py
+++ b/tests/test_schema.py
@@ -2675,7 +2675,7 @@ class Model(BaseModel):
                         'lizard': '#/definitions/Lizard',
                     },
                 },
-                'anyOf': [
+                'oneOf': [
                     {'$ref': '#/definitions/Cat'},
                     {'$ref': '#/definitions/Dog'},
                     {'$ref': '#/definitions/Lizard'},
@@ -2708,7 +2708,7 @@ class Model(BaseModel):
                     'propertyName': 'color',
                     'mapping': {'black': '#/definitions/BlackCat', 'white': '#/definitions/WhiteCat'},
                 },
-                'anyOf': [{'$ref': '#/definitions/BlackCat'}, {'$ref': '#/definitions/WhiteCat'}],
+                'oneOf': [{'$ref': '#/definitions/BlackCat'}, {'$ref': '#/definitions/WhiteCat'}],
             },
             'Dog': {
                 'title': 'Dog',
@@ -2775,11 +2775,11 @@ class Model(BaseModel):
                         'dog': '#/definitions/Dog',
                     },
                 },
-                'anyOf': [
+                'oneOf': [
                     {
-                        'anyOf': [
+                        'oneOf': [
                             {
-                                'anyOf': [
+                                'oneOf': [
                                     {'$ref': '#/definitions/BlackCatWithHeight'},
                                     {'$ref': '#/definitions/BlackCatWithWeight'},
                                 ]
@@ -2858,7 +2858,7 @@ class Model(BaseModel):
         'properties': {
             'number': {'title': 'Number', 'type': 'integer'},
             'pet': {
-                'anyOf': [{'$ref': '#/definitions/Cat'}, {'$ref': '#/definitions/Dog'}],
+                'oneOf': [{'$ref': '#/definitions/Cat'}, {'$ref': '#/definitions/Dog'}],
                 'discriminator': {
                     'mapping': {'cat': '#/definitions/Cat', 'dog': '#/definitions/Dog'},
                     'propertyName': 'typeOfPet',
@@ -2960,9 +2960,9 @@ class Model(BaseModel):
                         'dog': '#/definitions/Dog',
                     },
                 },
-                'anyOf': [
+                'oneOf': [
                     {
-                        'anyOf': [
+                        'oneOf': [
                             {'$ref': '#/definitions/BlackCat'},
                             {'$ref': '#/definitions/WhiteCat'},
                         ],