files: import warnings
  
  import hashlib
  import io
  import json
  import jsonschema
  import pandas as pd
  from toolz.curried import pipe as _pipe
  
  from .schema import core, channels, mixins, Undefined, SCHEMA_URL
  
  from .data import data_transformers
  from ... import utils, expr
  from .display import renderers, VEGALITE_VERSION, VEGAEMBED_VERSION, VEGA_VERSION
  from .theme import themes
  
  
  # ------------------------------------------------------------------------
  # Data Utilities
  def _dataset_name(values):
      """Generate a unique hash of the data
  
      Parameters
      ----------
      values : list or dict
          A list/dict representation of data values.
  
      Returns
      -------
      name : string
          A unique name generated from the hash of the values.
      """
      if isinstance(values, core.InlineDataset):
          values = values.to_dict()
      if values == [{}]:
          return "empty"
      values_json = json.dumps(values, sort_keys=True)
      hsh = hashlib.md5(values_json.encode()).hexdigest()
      return "data-" + hsh
  
  
  def _consolidate_data(data, context):
      """If data is specified inline, then move it to context['datasets']
  
      This function will modify context in-place, and return a new version of data
      """
      values = Undefined
      kwds = {}
  
      if isinstance(data, core.InlineData):
          if data.name is Undefined and data.values is not Undefined:
              if isinstance(data.values, core.InlineDataset):
                  values = data.to_dict()["values"]
              else:
                  values = data.values
              kwds = {"format": data.format}
  
      elif isinstance(data, dict):
          if "name" not in data and "values" in data:
              values = data["values"]
              kwds = {k: v for k, v in data.items() if k != "values"}
  
      if values is not Undefined:
          name = _dataset_name(values)
          data = core.NamedData(name=name, **kwds)
          context.setdefault("datasets", {})[name] = values
  
      return data
  
  
  def _prepare_data(data, context=None):
      """Convert input data to data for use within schema
  
      Parameters
      ----------
      data :
          The input dataset in the form of a DataFrame, dictionary, altair data
          object, or other type that is recognized by the data transformers.
      context : dict (optional)
          The to_dict context in which the data is being prepared. This is used
          to keep track of information that needs to be passed up and down the
          recursive serialization routine, such as global named datasets.
      """
      if data is Undefined:
          return data
  
      # convert dataframes  or objects with __geo_interface__ to dict
      if isinstance(data, pd.DataFrame) or hasattr(data, "__geo_interface__"):
          data = _pipe(data, data_transformers.get())
  
      # convert string input to a URLData
      if isinstance(data, str):
          data = core.UrlData(data)
  
      # consolidate inline data to top-level datasets
      if context is not None and data_transformers.consolidate_datasets:
          data = _consolidate_data(data, context)
  
      # if data is still not a recognized type, then return
      if not isinstance(data, (dict, core.Data)):
          warnings.warn("data of type {} not recognized".format(type(data)))
  
      return data
  
  
  # ------------------------------------------------------------------------
  # Aliases & specializations
  Bin = core.BinParams
  
  
  @utils.use_signature(core.LookupData)
  class LookupData(core.LookupData):
      def to_dict(self, *args, **kwargs):
          """Convert the chart to a dictionary suitable for JSON export."""
          copy = self.copy(deep=False)
          copy.data = _prepare_data(copy.data, kwargs.get("context"))
          return super(LookupData, copy).to_dict(*args, **kwargs)
  
  
  @utils.use_signature(core.FacetMapping)
  class FacetMapping(core.FacetMapping):
      _class_is_valid_at_instantiation = False
  
      def to_dict(self, *args, **kwargs):
          copy = self.copy(deep=False)
          context = kwargs.get("context", {})
          data = context.get("data", None)
          if isinstance(self.row, str):
              copy.row = core.FacetFieldDef(**utils.parse_shorthand(self.row, data))
          if isinstance(self.column, str):
              copy.column = core.FacetFieldDef(**utils.parse_shorthand(self.column, data))
          return super(FacetMapping, copy).to_dict(*args, **kwargs)
  
  
  # ------------------------------------------------------------------------
  # Encoding will contain channel objects that aren't valid at instantiation
  core.FacetedEncoding._class_is_valid_at_instantiation = False
  
  # ------------------------------------------------------------------------
  # These are parameters that are valid at the top level, but are not valid
  # for specs that are within a composite chart
  # (layer, hconcat, vconcat, facet, repeat)
  TOPLEVEL_ONLY_KEYS = {"background", "config", "autosize", "padding", "$schema"}
  
  
  def _get_channels_mapping():
      mapping = {}
      for attr in dir(channels):
          cls = getattr(channels, attr)
          if isinstance(cls, type) and issubclass(cls, core.SchemaBase):
              mapping[cls] = attr.replace("Value", "").lower()
      return mapping
  
  
  # -------------------------------------------------------------------------
  # Tools for working with parameters
  class Parameter(expr.core.OperatorMixin, object):
      """A Parameter object"""
  
      _counter = 0
  
      @classmethod
      def _get_name(cls):
          cls._counter += 1
          return "parameter{:03d}".format(cls._counter)
  
      def __init__(self, name):
          if name is None:
              name = self._get_name()
          self.name = name
  
      def to_dict(self):
          if self.param_type == "variable":
              if self.param.expr is Undefined:
                  return {"expr": self.name}
              else:
                  return {"expr": repr(self.param.expr)}
          elif self.param_type == "selection":
              return {
                  "param": self.name.to_dict()
                  if hasattr(self.name, "to_dict")
                  else self.name
              }
  
      def __invert__(self):
          if self.param_type == "selection":
              return SelectionPredicateComposition({"not": {"param": self.name}})
          else:
              return expr.core.OperatorMixin.__invert__(self)
  
      def __and__(self, other):
          if self.param_type == "selection":
              if isinstance(other, Parameter):
                  other = {"param": other.name}
              return SelectionPredicateComposition({"and": [{"param": self.name}, other]})
          else:
              return expr.core.OperatorMixin.__and__(self, other)
  
      def __or__(self, other):
          if self.param_type == "selection":
              if isinstance(other, Parameter):
                  other = {"param": other.name}
              return SelectionPredicateComposition({"or": [{"param": self.name}, other]})
          else:
              return expr.core.OperatorMixin.__or__(self, other)
  
      def __repr__(self):
          return "Parameter({0!r}, {1})".format(self.name, self.param)
  
      def _to_expr(self):
          if not hasattr(self.param, "expr") or self.param.expr is Undefined:
              return self.name
          else:
              return self.param.expr
  
      def _from_expr(self, expr):
          return parameter(expr=expr)
  
      def __getattr__(self, field_name):
          if field_name.startswith("__") and field_name.endswith("__"):
              raise AttributeError(field_name)
          _attrexpr = expr.core.GetAttrExpression(self.name, field_name)
          # If self is a SelectionParameter and field_name is in its
          # fields or encodings list, then we want to return an expression.
          if check_fields_and_encodings(self, field_name):
              return SelectionExpression(_attrexpr)
          return expr.core.GetAttrExpression(self.name, field_name)
  
  
  # Enables use of ~, &, | with compositions of selection objects.
  class SelectionPredicateComposition(core.PredicateComposition):
      def __invert__(self):
          return SelectionPredicateComposition({"not": self.to_dict()})
  
      def __and__(self, other):
          return SelectionPredicateComposition({"and": [self.to_dict(), other.to_dict()]})
  
      def __or__(self, other):
          return SelectionPredicateComposition({"or": [self.to_dict(), other.to_dict()]})
  
  
  class SelectionExpression(expr.core.OperatorMixin, object):
      def __init__(self, expr):
          self.expr = expr
  
      def to_dict(self):
          return {"expr": repr(self.expr)}
  
      def _to_expr(self):
          return repr(self.expr)
  
      def _from_expr(self, expr):
          return SelectionExpression(expr=expr)
  
  
  def check_fields_and_encodings(parameter, field_name):
      for prop in ["fields", "encodings"]:
          try:
              if field_name in
  
  [... the rest is omitted ...]
files: altair/vegalite/v5/api.py
files: import warnings
  
  import hashlib
  import io
  import json
  import jsonschema
  import pandas as pd
  from toolz.curried import pipe as _pipe
  
  from .schema import core, channels, mixins, Undefined, SCHEMA_URL
  
  from .data import data_transformers
  from ... import utils, expr
  from .display import renderers, VEGALITE_VERSION, VEGAEMBED_VERSION, VEGA_VERSION
  from .theme import themes
  
  
  # ------------------------------------------------------------------------
  # Data Utilities
  def _dataset_name(values):
      """Generate a unique hash of the data
  
      Parameters
      ----------
      values : list or dict
          A list/dict representation of data values.
  
      Returns
      -------
      name : string
          A unique name generated from the hash of the values.
      """
      if isinstance(values, core.InlineDataset):
          values = values.to_dict()
      if values == [{}]:
          return "empty"
      values_json = json.dumps(values, sort_keys=True)
      hsh = hashlib.md5(values_json.encode()).hexdigest()
      return "data-" + hsh
  
  
  def _consolidate_data(data, context):
      """If data is specified inline, then move it to context['datasets']
  
      This function will modify context in-place, and return a new version of data
      """
      values = Undefined
      kwds = {}
  
      if isinstance(data, core.InlineData):
          if data.name is Undefined and data.values is not Undefined:
              if isinstance(data.values, core.InlineDataset):
                  values = data.to_dict()["values"]
              else:
                  values = data.values
              kwds = {"format": data.format}
  
      elif isinstance(data, dict):
          if "name" not in data and "values" in data:
              values = data["values"]
              kwds = {k: v for k, v in data.items() if k != "values"}
  
      if values is not Undefined:
          name = _dataset_name(values)
          data = core.NamedData(name=name, **kwds)
          context.setdefault("datasets", {})[name] = values
  
      return data
  
  
  def _prepare_data(data, context=None):
      """Convert input data to data for use within schema
  
      Parameters
      ----------
      data :
          The input dataset in the form of a DataFrame, dictionary, altair data
          object, or other type that is recognized by the data transformers.
      context : dict (optional)
          The to_dict context in which the data is being prepared. This is used
          to keep track of information that needs to be passed up and down the
          recursive serialization routine, such as global named datasets.
      """
      if data is Undefined:
          return data
  
      # convert dataframes  or objects with __geo_interface__ to dict
      if isinstance(data, pd.DataFrame) or hasattr(data, "__geo_interface__"):
          data = _pipe(data, data_transformers.get())
  
      # convert string input to a URLData
      if isinstance(data, str):
          data = core.UrlData(data)
  
      # consolidate inline data to top-level datasets
      if context is not None and data_transformers.consolidate_datasets:
          data = _consolidate_data(data, context)
  
      # if data is still not a recognized type, then return
      if not isinstance(data, (dict, core.Data)):
          warnings.warn("data of type {} not recognized".format(type(data)))
  
      return data
  
  
  # ------------------------------------------------------------------------
  # Aliases & specializations
  Bin = core.BinParams
  
  
  @utils.use_signature(core.LookupData)
  class LookupData(core.LookupData):
      def to_dict(self, *args, **kwargs):
          """Convert the chart to a dictionary suitable for JSON export."""
          copy = self.copy(deep=False)
          copy.data = _prepare_data(copy.data, kwargs.get("context"))
          return super(LookupData, copy).to_dict(*args, **kwargs)
  
  
  @utils.use_signature(core.FacetMapping)
  class FacetMapping(core.FacetMapping):
      _class_is_valid_at_instantiation = False
  
      def to_dict(self, *args, **kwargs):
          copy = self.copy(deep=False)
          context = kwargs.get("context", {})
          data = context.get("data", None)
          if isinstance(self.row, str):
              copy.row = core.FacetFieldDef(**utils.parse_shorthand(self.row, data))
          if isinstance(self.column, str):
              copy.column = core.FacetFieldDef(**utils.parse_shorthand(self.column, data))
          return super(FacetMapping, copy).to_dict(*args, **kwargs)
  
  
  # ------------------------------------------------------------------------
  # Encoding will contain channel objects that aren't valid at instantiation
  core.FacetedEncoding._class_is_valid_at_instantiation = False
  
  # ------------------------------------------------------------------------
  # These are parameters that are valid at the top level, but are not valid
  # for specs that are within a composite chart
  # (layer, hconcat, vconcat, facet, repeat)
  TOPLEVEL_ONLY_KEYS = {"background", "config", "autosize", "padding", "$schema"}
  
  
  def _get_channels_mapping():
      mapping = {}
      for attr in dir(channels):
          cls = getattr(channels, attr)
          if isinstance(cls, type) and issubclass(cls, core.SchemaBase):
              mapping[cls] = attr.replace("Value", "").lower()
      return mapping
  
  
  # -------------------------------------------------------------------------
  # Tools for working with parameters
  class Parameter(expr.core.OperatorMixin, object):
      """A Parameter object"""
  
      _counter = 0
  
      @classmethod
      def _get_name(cls):
          cls._counter += 1
          return "parameter{:03d}".format(cls._counter)
  
      def __init__(self, name):
          if name is None:
              name = self._get_name()
          self.name = name
  
      def to_dict(self):
          if self.param_type == "variable":
              if self.param.expr is Undefined:
                  return {"expr": self.name}
              else:
                  return {"expr": repr(self.param.expr)}
          elif self.param_type == "selection":
              return {
                  "param": self.name.to_dict()
                  if hasattr(self.name, "to_dict")
                  else self.name
              }
  
      def __invert__(self):
          if self.param_type == "selection":
              return core.PredicateComposition({"not": {"param": self.name}})
          else:
              return expr.core.OperatorMixin.__invert__(self)
  
      def __and__(self, other):
          if self.param_type == "selection":
              if isinstance(other, Parameter):
                  other = {"param": other.name}
              return core.PredicateComposition({"and": [{"param": self.name}, other]})
          else:
              return expr.core.OperatorMixin.__and__(self, other)
  
      def __or__(self, other):
          if self.param_type == "selection":
              if isinstance(other, Parameter):
                  other = {"param": other.name}
              return core.PredicateComposition({"or": [{"param": self.name}, other]})
          else:
              return expr.core.OperatorMixin.__or__(self, other)
  
      def __repr__(self):
          return "Parameter({0!r}, {1})".format(self.name, self.param)
  
      def _to_expr(self):
          if not hasattr(self.param, "expr") or self.param.expr is Undefined:
              return self.name
          else:
              return self.param.expr
  
      def _from_expr(self, expr):
          return parameter(expr=expr)
  
      def __getattr__(self, field_name):
          if field_name.startswith("__") and field_name.endswith("__"):
              raise AttributeError(field_name)
          _attrexpr = expr.core.GetAttrExpression(self.name, field_name)
          # If self is a SelectionParameter and field_name is in its
          # fields or encodings list, then we want to return an expression.
          if check_fields_and_encodings(self, field_name):
              return SelectionExpression(_attrexpr)
          return expr.core.GetAttrExpression(self.name, field_name)
  
  
  class SelectionExpression(expr.core.OperatorMixin, object):
      def __init__(self, expr):
          self.expr = expr
  
      def to_dict(self):
          return {"expr": repr(self.expr)}
  
      def _to_expr(self):
          return repr(self.expr)
  
      def _from_expr(self, expr):
          return SelectionExpression(expr=expr)
  
  
  def check_fields_and_encodings(parameter, field_name):
      for prop in ["fields", "encodings"]:
          try:
              if field_name in getattr(parameter.param.select, prop):
                  return True
          except (AttributeError, TypeError):
              pass
  
      return False
  
  
  # ------------------------------------------------------------------------
  # Top-Level Functions
  
  
  def value(value, **kwargs):
      """Specify a value for use in an encoding"""
      return dict(value=value, **kwargs)
  
  
  def parameter(name=None, select=None, **kwds):
      """Create a named parameter.
  
      Parameters
      ----------
      name : string (optional)
          The name of the parameter. If not specified,
  
  [... the rest is omitted ...]
files: altair/vegalite/v5/api.py
files: """Unit tests for altair API"""
  
  import io
  import json
  import operator
  import os
  import pathlib
  import tempfile
  
  import jsonschema
  import pytest
  import pandas as pd
  
  import altair.vegalite.v5 as alt
  
  try:
      import altair_saver  # noqa: F401
  except ImportError:
      altair_saver = None
  
  
  def getargs(*args, **kwargs):
      return args, kwargs
  
  
  OP_DICT = {
      "layer": operator.add,
      "hconcat": operator.or_,
      "vconcat": operator.and_,
  }
  
  
  def _make_chart_type(chart_type):
      data = pd.DataFrame(
          {
              "x": [28, 55, 43, 91, 81, 53, 19, 87],
              "y": [43, 91, 81, 53, 19, 87, 52, 28],
              "color": list("AAAABBBB"),
          }
      )
      base = (
          alt.Chart(data)
          .mark_point()
          .encode(
              x="x",
              y="y",
              color="color",
          )
      )
  
      if chart_type in ["layer", "hconcat", "vconcat", "concat"]:
          func = getattr(alt, chart_type)
          return func(base.mark_square(), base.mark_circle())
      elif chart_type == "facet":
          return base.facet("color")
      elif chart_type == "facet_encoding":
          return base.encode(facet="color")
      elif chart_type == "repeat":
          return base.encode(alt.X(alt.repeat(), type="quantitative")).repeat(["x", "y"])
      elif chart_type == "chart":
          return base
      else:
          raise ValueError("chart_type='{}' is not recognized".format(chart_type))
  
  
  @pytest.fixture
  def basic_chart():
      data = pd.DataFrame(
          {
              "a": ["A", "B", "C", "D", "E", "F", "G", "H", "I"],
              "b": [28, 55, 43, 91, 81, 53, 19, 87, 52],
          }
      )
  
      return alt.Chart(data).mark_bar().encode(x="a", y="b")
  
  
  def test_chart_data_types():
      def Chart(data):
          return alt.Chart(data).mark_point().encode(x="x:Q", y="y:Q")
  
      # Url Data
      data = "/path/to/my/data.csv"
      dct = Chart(data).to_dict()
      assert dct["data"] == {"url": data}
  
      # Dict Data
      data = {"values": [{"x": 1, "y": 2}, {"x": 2, "y": 3}]}
      with alt.data_transformers.enable(consolidate_datasets=False):
          dct = Chart(data).to_dict()
      assert dct["data"] == data
  
      with alt.data_transformers.enable(consolidate_datasets=True):
          dct = Chart(data).to_dict()
      name = dct["data"]["name"]
      assert dct["datasets"][name] == data["values"]
  
      # DataFrame data
      data = pd.DataFrame({"x": range(5), "y": range(5)})
      with alt.data_transformers.enable(consolidate_datasets=False):
          dct = Chart(data).to_dict()
      assert dct["data"]["values"] == data.to_dict(orient="records")
  
      with alt.data_transformers.enable(consolidate_datasets=True):
          dct = Chart(data).to_dict()
      name = dct["data"]["name"]
      assert dct["datasets"][name] == data.to_dict(orient="records")
  
      # Named data object
      data = alt.NamedData(name="Foo")
      dct = Chart(data).to_dict()
      assert dct["data"] == {"name": "Foo"}
  
  
  def test_chart_infer_types():
      data = pd.DataFrame(
          {
              "x": pd.date_range("2012", periods=10, freq="Y"),
              "y": range(10),
              "c": list("abcabcabca"),
          }
      )
  
      def _check_encodings(chart):
          dct = chart.to_dict()
          assert dct["encoding"]["x"]["type"] == "temporal"
          assert dct["encoding"]["x"]["field"] == "x"
          assert dct["encoding"]["y"]["type"] == "quantitative"
          assert dct["encoding"]["y"]["field"] == "y"
          assert dct["encoding"]["color"]["type"] == "nominal"
          assert dct["encoding"]["color"]["field"] == "c"
  
      # Pass field names by keyword
      chart = alt.Chart(data).mark_point().encode(x="x", y="y", color="c")
      _check_encodings(chart)
  
      # pass Channel objects by keyword
      chart = (
          alt.Chart(data)
          .mark_point()
          .encode(x=alt.X("x"), y=alt.Y("y"), color=alt.Color("c"))
      )
      _check_encodings(chart)
  
      # pass Channel objects by value
      chart = alt.Chart(data).mark_point().encode(alt.X("x"), alt.Y("y"), alt.Color("c"))
      _check_encodings(chart)
  
      # override default types
      chart = (
          alt.Chart(data)
          .mark_point()
          .encode(alt.X("x", type="nominal"), alt.Y("y", type="ordinal"))
      )
      dct = chart.to_dict()
      assert dct["encoding"]["x"]["type"] == "nominal"
      assert dct["encoding"]["y"]["type"] == "ordinal"
  
  
  @pytest.mark.parametrize(
      "args, kwargs",
      [
          getargs(detail=["value:Q", "name:N"], tooltip=["value:Q", "name:N"]),
          getargs(detail=["value", "name"], tooltip=["value", "name"]),
          getargs(alt.Detail(["value:Q", "name:N"]), alt.Tooltip(["value:Q", "name:N"])),
          getargs(alt.Detail(["value", "name"]), alt.Tooltip(["value", "name"])),
          getargs(
              [alt.Detail("value:Q"), alt.Detail("name:N")],
              [alt.Tooltip("value:Q"), alt.Tooltip("name:N")],
          ),
          getargs(
              [alt.Detail("value"), alt.Detail("name")],
              [alt.Tooltip("value"), alt.Tooltip("name")],
          ),
      ],
  )
  def test_multiple_encodings(args, kwargs):
      df = pd.DataFrame({"value": [1, 2, 3], "name": ["A", "B", "C"]})
      encoding_dct = [
          {"field": "value", "type": "quantitative"},
          {"field": "name", "type": "nominal"},
      ]
      chart = alt.Chart(df).mark_point().encode(*args, **kwargs)
      dct = chart.to_dict()
      assert dct["encoding"]["detail"] == encoding_dct
      assert dct["encoding"]["tooltip"] == encoding_dct
  
  
  def test_chart_operations():
      data = pd.DataFrame(
          {
              "x": pd.date_range("2012", periods=10, freq="Y"),
              "y": range(10),
              "c": list("abcabcabca"),
          }
      )
      chart1 = alt.Chart(data).mark_line().encode(x="x", y="y", color="c")
      chart2 = chart1.mark_point()
      chart3 = chart1.mark_circle()
      chart4 = chart1.mark_square()
  
      chart = chart1 + chart2 + chart3
      assert isinstance(chart, alt.LayerChart)
      assert len(chart.layer) == 3
      chart += chart4
      assert len(chart.layer) == 4
  
      chart = chart1 | chart2 | chart3
      assert isinstance(chart, alt.HConcatChart)
      assert len(chart.hconcat) == 3
      chart |= chart4
      assert len(chart.hconcat) == 4
  
      chart = chart1 & chart2 & chart3
      assert isinstance(chart, alt.VConcatChart)
      assert len(chart.vconcat) == 3
      chart &= chart4
      assert len(chart.vconcat) == 4
  
  
  def test_selection_to_dict():
      brush = alt.selection(type="interval")
  
      # test some value selections
      # Note: X and Y cannot have conditions
      alt.Chart("path/to/data.json").mark_point().encode(
          color=alt.condition(brush, alt.ColorValue("red"), alt.ColorValue("blue")),
          opacity=alt.condition(brush, alt.value(0.5), alt.value(1.0)),
          text=alt.condition(brush, alt.TextValue("foo"), alt.value("bar")),
      ).to_dict()
  
  
  
  [... the rest is omitted ...]
files: altair/vegalite/v5/tests/test_api.py
files: """Unit tests for altair API"""
  
  import io
  import json
  import operator
  import os
  import pathlib
  import tempfile
  
  import jsonschema
  import pytest
  import pandas as pd
  
  import altair.vegalite.v5 as alt
  
  try:
      import altair_saver  # noqa: F401
  except ImportError:
      altair_saver = None
  
  
  def getargs(*args, **kwargs):
      return args, kwargs
  
  
  OP_DICT = {
      "layer": operator.add,
      "hconcat": operator.or_,
      "vconcat": operator.and_,
  }
  
  
  def _make_chart_type(chart_type):
      data = pd.DataFrame(
          {
              "x": [28, 55, 43, 91, 81, 53, 19, 87],
              "y": [43, 91, 81, 53, 19, 87, 52, 28],
              "color": list("AAAABBBB"),
          }
      )
      base = (
          alt.Chart(data)
          .mark_point()
          .encode(
              x="x",
              y="y",
              color="color",
          )
      )
  
      if chart_type in ["layer", "hconcat", "vconcat", "concat"]:
          func = getattr(alt, chart_type)
          return func(base.mark_square(), base.mark_circle())
      elif chart_type == "facet":
          return base.facet("color")
      elif chart_type == "facet_encoding":
          return base.encode(facet="color")
      elif chart_type == "repeat":
          return base.encode(alt.X(alt.repeat(), type="quantitative")).repeat(["x", "y"])
      elif chart_type == "chart":
          return base
      else:
          raise ValueError("chart_type='{}' is not recognized".format(chart_type))
  
  
  @pytest.fixture
  def basic_chart():
      data = pd.DataFrame(
          {
              "a": ["A", "B", "C", "D", "E", "F", "G", "H", "I"],
              "b": [28, 55, 43, 91, 81, 53, 19, 87, 52],
          }
      )
  
      return alt.Chart(data).mark_bar().encode(x="a", y="b")
  
  
  def test_chart_data_types():
      def Chart(data):
          return alt.Chart(data).mark_point().encode(x="x:Q", y="y:Q")
  
      # Url Data
      data = "/path/to/my/data.csv"
      dct = Chart(data).to_dict()
      assert dct["data"] == {"url": data}
  
      # Dict Data
      data = {"values": [{"x": 1, "y": 2}, {"x": 2, "y": 3}]}
      with alt.data_transformers.enable(consolidate_datasets=False):
          dct = Chart(data).to_dict()
      assert dct["data"] == data
  
      with alt.data_transformers.enable(consolidate_datasets=True):
          dct = Chart(data).to_dict()
      name = dct["data"]["name"]
      assert dct["datasets"][name] == data["values"]
  
      # DataFrame data
      data = pd.DataFrame({"x": range(5), "y": range(5)})
      with alt.data_transformers.enable(consolidate_datasets=False):
          dct = Chart(data).to_dict()
      assert dct["data"]["values"] == data.to_dict(orient="records")
  
      with alt.data_transformers.enable(consolidate_datasets=True):
          dct = Chart(data).to_dict()
      name = dct["data"]["name"]
      assert dct["datasets"][name] == data.to_dict(orient="records")
  
      # Named data object
      data = alt.NamedData(name="Foo")
      dct = Chart(data).to_dict()
      assert dct["data"] == {"name": "Foo"}
  
  
  def test_chart_infer_types():
      data = pd.DataFrame(
          {
              "x": pd.date_range("2012", periods=10, freq="Y"),
              "y": range(10),
              "c": list("abcabcabca"),
          }
      )
  
      def _check_encodings(chart):
          dct = chart.to_dict()
          assert dct["encoding"]["x"]["type"] == "temporal"
          assert dct["encoding"]["x"]["field"] == "x"
          assert dct["encoding"]["y"]["type"] == "quantitative"
          assert dct["encoding"]["y"]["field"] == "y"
          assert dct["encoding"]["color"]["type"] == "nominal"
          assert dct["encoding"]["color"]["field"] == "c"
  
      # Pass field names by keyword
      chart = alt.Chart(data).mark_point().encode(x="x", y="y", color="c")
      _check_encodings(chart)
  
      # pass Channel objects by keyword
      chart = (
          alt.Chart(data)
          .mark_point()
          .encode(x=alt.X("x"), y=alt.Y("y"), color=alt.Color("c"))
      )
      _check_encodings(chart)
  
      # pass Channel objects by value
      chart = alt.Chart(data).mark_point().encode(alt.X("x"), alt.Y("y"), alt.Color("c"))
      _check_encodings(chart)
  
      # override default types
      chart = (
          alt.Chart(data)
          .mark_point()
          .encode(alt.X("x", type="nominal"), alt.Y("y", type="ordinal"))
      )
      dct = chart.to_dict()
      assert dct["encoding"]["x"]["type"] == "nominal"
      assert dct["encoding"]["y"]["type"] == "ordinal"
  
  
  @pytest.mark.parametrize(
      "args, kwargs",
      [
          getargs(detail=["value:Q", "name:N"], tooltip=["value:Q", "name:N"]),
          getargs(detail=["value", "name"], tooltip=["value", "name"]),
          getargs(alt.Detail(["value:Q", "name:N"]), alt.Tooltip(["value:Q", "name:N"])),
          getargs(alt.Detail(["value", "name"]), alt.Tooltip(["value", "name"])),
          getargs(
              [alt.Detail("value:Q"), alt.Detail("name:N")],
              [alt.Tooltip("value:Q"), alt.Tooltip("name:N")],
          ),
          getargs(
              [alt.Detail("value"), alt.Detail("name")],
              [alt.Tooltip("value"), alt.Tooltip("name")],
          ),
      ],
  )
  def test_multiple_encodings(args, kwargs):
      df = pd.DataFrame({"value": [1, 2, 3], "name": ["A", "B", "C"]})
      encoding_dct = [
          {"field": "value", "type": "quantitative"},
          {"field": "name", "type": "nominal"},
      ]
      chart = alt.Chart(df).mark_point().encode(*args, **kwargs)
      dct = chart.to_dict()
      assert dct["encoding"]["detail"] == encoding_dct
      assert dct["encoding"]["tooltip"] == encoding_dct
  
  
  def test_chart_operations():
      data = pd.DataFrame(
          {
              "x": pd.date_range("2012", periods=10, freq="Y"),
              "y": range(10),
              "c": list("abcabcabca"),
          }
      )
      chart1 = alt.Chart(data).mark_line().encode(x="x", y="y", color="c")
      chart2 = chart1.mark_point()
      chart3 = chart1.mark_circle()
      chart4 = chart1.mark_square()
  
      chart = chart1 + chart2 + chart3
      assert isinstance(chart, alt.LayerChart)
      assert len(chart.layer) == 3
      chart += chart4
      assert len(chart.layer) == 4
  
      chart = chart1 | chart2 | chart3
      assert isinstance(chart, alt.HConcatChart)
      assert len(chart.hconcat) == 3
      chart |= chart4
      assert len(chart.hconcat) == 4
  
      chart = chart1 & chart2 & chart3
      assert isinstance(chart, alt.VConcatChart)
      assert len(chart.vconcat) == 3
      chart &= chart4
      assert len(chart.vconcat) == 4
  
  
  def test_selection_to_dict():
      brush = alt.selection(type="interval")
  
      # test some value selections
      # Note: X and Y cannot have conditions
      alt.Chart("path/to/data.json").mark_point().encode(
          color=alt.condition(brush, alt.ColorValue("red"), alt.ColorValue("blue")),
          opacity=alt.condition(brush, alt.value(0.5), alt.value(1.0)),
          text=alt.condition(brush, alt.TextValue("foo"), alt.value("bar")),
      ).to_dict()
  
  
  
  [... the rest is omitted ...]
files: altair/vegalite/v5/tests/test_api.py